jszip.js 358 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370
  1. /*!
  2. JSZip v3.7.1 - A JavaScript class for generating and reading zip files
  3. <http://stuartk.com/jszip>
  4. (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
  5. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
  6. JSZip uses the library pako released under the MIT license :
  7. https://github.com/nodeca/pako/blob/master/LICENSE
  8. */
  9. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSZip = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  10. 'use strict';
  11. var utils = require('./utils');
  12. var support = require('./support');
  13. // private property
  14. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  15. // public method for encoding
  16. exports.encode = function(input) {
  17. var output = [];
  18. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  19. var i = 0, len = input.length, remainingBytes = len;
  20. var isArray = utils.getTypeOf(input) !== "string";
  21. while (i < input.length) {
  22. remainingBytes = len - i;
  23. if (!isArray) {
  24. chr1 = input.charCodeAt(i++);
  25. chr2 = i < len ? input.charCodeAt(i++) : 0;
  26. chr3 = i < len ? input.charCodeAt(i++) : 0;
  27. } else {
  28. chr1 = input[i++];
  29. chr2 = i < len ? input[i++] : 0;
  30. chr3 = i < len ? input[i++] : 0;
  31. }
  32. enc1 = chr1 >> 2;
  33. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  34. enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;
  35. enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;
  36. output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));
  37. }
  38. return output.join("");
  39. };
  40. // public method for decoding
  41. exports.decode = function(input) {
  42. var chr1, chr2, chr3;
  43. var enc1, enc2, enc3, enc4;
  44. var i = 0, resultIndex = 0;
  45. var dataUrlPrefix = "data:";
  46. if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {
  47. // This is a common error: people give a data url
  48. // (data:image/png;base64,iVBOR...) with a {base64: true} and
  49. // wonders why things don't work.
  50. // We can detect that the string input looks like a data url but we
  51. // *can't* be sure it is one: removing everything up to the comma would
  52. // be too dangerous.
  53. throw new Error("Invalid base64 input, it looks like a data url.");
  54. }
  55. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  56. var totalLength = input.length * 3 / 4;
  57. if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {
  58. totalLength--;
  59. }
  60. if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {
  61. totalLength--;
  62. }
  63. if (totalLength % 1 !== 0) {
  64. // totalLength is not an integer, the length does not match a valid
  65. // base64 content. That can happen if:
  66. // - the input is not a base64 content
  67. // - the input is *almost* a base64 content, with a extra chars at the
  68. // beginning or at the end
  69. // - the input uses a base64 variant (base64url for example)
  70. throw new Error("Invalid base64 input, bad content length.");
  71. }
  72. var output;
  73. if (support.uint8array) {
  74. output = new Uint8Array(totalLength|0);
  75. } else {
  76. output = new Array(totalLength|0);
  77. }
  78. while (i < input.length) {
  79. enc1 = _keyStr.indexOf(input.charAt(i++));
  80. enc2 = _keyStr.indexOf(input.charAt(i++));
  81. enc3 = _keyStr.indexOf(input.charAt(i++));
  82. enc4 = _keyStr.indexOf(input.charAt(i++));
  83. chr1 = (enc1 << 2) | (enc2 >> 4);
  84. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  85. chr3 = ((enc3 & 3) << 6) | enc4;
  86. output[resultIndex++] = chr1;
  87. if (enc3 !== 64) {
  88. output[resultIndex++] = chr2;
  89. }
  90. if (enc4 !== 64) {
  91. output[resultIndex++] = chr3;
  92. }
  93. }
  94. return output;
  95. };
  96. },{"./support":30,"./utils":32}],2:[function(require,module,exports){
  97. 'use strict';
  98. var external = require("./external");
  99. var DataWorker = require('./stream/DataWorker');
  100. var Crc32Probe = require('./stream/Crc32Probe');
  101. var DataLengthProbe = require('./stream/DataLengthProbe');
  102. /**
  103. * Represent a compressed object, with everything needed to decompress it.
  104. * @constructor
  105. * @param {number} compressedSize the size of the data compressed.
  106. * @param {number} uncompressedSize the size of the data after decompression.
  107. * @param {number} crc32 the crc32 of the decompressed file.
  108. * @param {object} compression the type of compression, see lib/compressions.js.
  109. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.
  110. */
  111. function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {
  112. this.compressedSize = compressedSize;
  113. this.uncompressedSize = uncompressedSize;
  114. this.crc32 = crc32;
  115. this.compression = compression;
  116. this.compressedContent = data;
  117. }
  118. CompressedObject.prototype = {
  119. /**
  120. * Create a worker to get the uncompressed content.
  121. * @return {GenericWorker} the worker.
  122. */
  123. getContentWorker: function () {
  124. var worker = new DataWorker(external.Promise.resolve(this.compressedContent))
  125. .pipe(this.compression.uncompressWorker())
  126. .pipe(new DataLengthProbe("data_length"));
  127. var that = this;
  128. worker.on("end", function () {
  129. if (this.streamInfo['data_length'] !== that.uncompressedSize) {
  130. throw new Error("Bug : uncompressed data size mismatch");
  131. }
  132. });
  133. return worker;
  134. },
  135. /**
  136. * Create a worker to get the compressed content.
  137. * @return {GenericWorker} the worker.
  138. */
  139. getCompressedWorker: function () {
  140. return new DataWorker(external.Promise.resolve(this.compressedContent))
  141. .withStreamInfo("compressedSize", this.compressedSize)
  142. .withStreamInfo("uncompressedSize", this.uncompressedSize)
  143. .withStreamInfo("crc32", this.crc32)
  144. .withStreamInfo("compression", this.compression)
  145. ;
  146. }
  147. };
  148. /**
  149. * Chain the given worker with other workers to compress the content with the
  150. * given compression.
  151. * @param {GenericWorker} uncompressedWorker the worker to pipe.
  152. * @param {Object} compression the compression object.
  153. * @param {Object} compressionOptions the options to use when compressing.
  154. * @return {GenericWorker} the new worker compressing the content.
  155. */
  156. CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {
  157. return uncompressedWorker
  158. .pipe(new Crc32Probe())
  159. .pipe(new DataLengthProbe("uncompressedSize"))
  160. .pipe(compression.compressWorker(compressionOptions))
  161. .pipe(new DataLengthProbe("compressedSize"))
  162. .withStreamInfo("compression", compression);
  163. };
  164. module.exports = CompressedObject;
  165. },{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){
  166. 'use strict';
  167. var GenericWorker = require("./stream/GenericWorker");
  168. exports.STORE = {
  169. magic: "\x00\x00",
  170. compressWorker : function (compressionOptions) {
  171. return new GenericWorker("STORE compression");
  172. },
  173. uncompressWorker : function () {
  174. return new GenericWorker("STORE decompression");
  175. }
  176. };
  177. exports.DEFLATE = require('./flate');
  178. },{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){
  179. 'use strict';
  180. var utils = require('./utils');
  181. /**
  182. * The following functions come from pako, from pako/lib/zlib/crc32.js
  183. * released under the MIT license, see pako https://github.com/nodeca/pako/
  184. */
  185. // Use ordinary array, since untyped makes no boost here
  186. function makeTable() {
  187. var c, table = [];
  188. for(var n =0; n < 256; n++){
  189. c = n;
  190. for(var k =0; k < 8; k++){
  191. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  192. }
  193. table[n] = c;
  194. }
  195. return table;
  196. }
  197. // Create table on load. Just 255 signed longs. Not a problem.
  198. var crcTable = makeTable();
  199. function crc32(crc, buf, len, pos) {
  200. var t = crcTable, end = pos + len;
  201. crc = crc ^ (-1);
  202. for (var i = pos; i < end; i++ ) {
  203. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  204. }
  205. return (crc ^ (-1)); // >>> 0;
  206. }
  207. // That's all for the pako functions.
  208. /**
  209. * Compute the crc32 of a string.
  210. * This is almost the same as the function crc32, but for strings. Using the
  211. * same function for the two use cases leads to horrible performances.
  212. * @param {Number} crc the starting value of the crc.
  213. * @param {String} str the string to use.
  214. * @param {Number} len the length of the string.
  215. * @param {Number} pos the starting position for the crc32 computation.
  216. * @return {Number} the computed crc32.
  217. */
  218. function crc32str(crc, str, len, pos) {
  219. var t = crcTable, end = pos + len;
  220. crc = crc ^ (-1);
  221. for (var i = pos; i < end; i++ ) {
  222. crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];
  223. }
  224. return (crc ^ (-1)); // >>> 0;
  225. }
  226. module.exports = function crc32wrapper(input, crc) {
  227. if (typeof input === "undefined" || !input.length) {
  228. return 0;
  229. }
  230. var isArray = utils.getTypeOf(input) !== "string";
  231. if(isArray) {
  232. return crc32(crc|0, input, input.length, 0);
  233. } else {
  234. return crc32str(crc|0, input, input.length, 0);
  235. }
  236. };
  237. },{"./utils":32}],5:[function(require,module,exports){
  238. 'use strict';
  239. exports.base64 = false;
  240. exports.binary = false;
  241. exports.dir = false;
  242. exports.createFolders = true;
  243. exports.date = null;
  244. exports.compression = null;
  245. exports.compressionOptions = null;
  246. exports.comment = null;
  247. exports.unixPermissions = null;
  248. exports.dosPermissions = null;
  249. },{}],6:[function(require,module,exports){
  250. /* global Promise */
  251. 'use strict';
  252. // load the global object first:
  253. // - it should be better integrated in the system (unhandledRejection in node)
  254. // - the environment may have a custom Promise implementation (see zone.js)
  255. var ES6Promise = null;
  256. if (typeof Promise !== "undefined") {
  257. ES6Promise = Promise;
  258. } else {
  259. ES6Promise = require("lie");
  260. }
  261. /**
  262. * Let the user use/change some implementations.
  263. */
  264. module.exports = {
  265. Promise: ES6Promise
  266. };
  267. },{"lie":37}],7:[function(require,module,exports){
  268. 'use strict';
  269. var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
  270. var pako = require("pako");
  271. var utils = require("./utils");
  272. var GenericWorker = require("./stream/GenericWorker");
  273. var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array";
  274. exports.magic = "\x08\x00";
  275. /**
  276. * Create a worker that uses pako to inflate/deflate.
  277. * @constructor
  278. * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate".
  279. * @param {Object} options the options to use when (de)compressing.
  280. */
  281. function FlateWorker(action, options) {
  282. GenericWorker.call(this, "FlateWorker/" + action);
  283. this._pako = null;
  284. this._pakoAction = action;
  285. this._pakoOptions = options;
  286. // the `meta` object from the last chunk received
  287. // this allow this worker to pass around metadata
  288. this.meta = {};
  289. }
  290. utils.inherits(FlateWorker, GenericWorker);
  291. /**
  292. * @see GenericWorker.processChunk
  293. */
  294. FlateWorker.prototype.processChunk = function (chunk) {
  295. this.meta = chunk.meta;
  296. if (this._pako === null) {
  297. this._createPako();
  298. }
  299. this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);
  300. };
  301. /**
  302. * @see GenericWorker.flush
  303. */
  304. FlateWorker.prototype.flush = function () {
  305. GenericWorker.prototype.flush.call(this);
  306. if (this._pako === null) {
  307. this._createPako();
  308. }
  309. this._pako.push([], true);
  310. };
  311. /**
  312. * @see GenericWorker.cleanUp
  313. */
  314. FlateWorker.prototype.cleanUp = function () {
  315. GenericWorker.prototype.cleanUp.call(this);
  316. this._pako = null;
  317. };
  318. /**
  319. * Create the _pako object.
  320. * TODO: lazy-loading this object isn't the best solution but it's the
  321. * quickest. The best solution is to lazy-load the worker list. See also the
  322. * issue #446.
  323. */
  324. FlateWorker.prototype._createPako = function () {
  325. this._pako = new pako[this._pakoAction]({
  326. raw: true,
  327. level: this._pakoOptions.level || -1 // default compression
  328. });
  329. var self = this;
  330. this._pako.onData = function(data) {
  331. self.push({
  332. data : data,
  333. meta : self.meta
  334. });
  335. };
  336. };
  337. exports.compressWorker = function (compressionOptions) {
  338. return new FlateWorker("Deflate", compressionOptions);
  339. };
  340. exports.uncompressWorker = function () {
  341. return new FlateWorker("Inflate", {});
  342. };
  343. },{"./stream/GenericWorker":28,"./utils":32,"pako":38}],8:[function(require,module,exports){
  344. 'use strict';
  345. var utils = require('../utils');
  346. var GenericWorker = require('../stream/GenericWorker');
  347. var utf8 = require('../utf8');
  348. var crc32 = require('../crc32');
  349. var signature = require('../signature');
  350. /**
  351. * Transform an integer into a string in hexadecimal.
  352. * @private
  353. * @param {number} dec the number to convert.
  354. * @param {number} bytes the number of bytes to generate.
  355. * @returns {string} the result.
  356. */
  357. var decToHex = function(dec, bytes) {
  358. var hex = "", i;
  359. for (i = 0; i < bytes; i++) {
  360. hex += String.fromCharCode(dec & 0xff);
  361. dec = dec >>> 8;
  362. }
  363. return hex;
  364. };
  365. /**
  366. * Generate the UNIX part of the external file attributes.
  367. * @param {Object} unixPermissions the unix permissions or null.
  368. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  369. * @return {Number} a 32 bit integer.
  370. *
  371. * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
  372. *
  373. * TTTTsstrwxrwxrwx0000000000ADVSHR
  374. * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
  375. * ^^^_________________________ setuid, setgid, sticky
  376. * ^^^^^^^^^________________ permissions
  377. * ^^^^^^^^^^______ not used ?
  378. * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
  379. */
  380. var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
  381. var result = unixPermissions;
  382. if (!unixPermissions) {
  383. // I can't use octal values in strict mode, hence the hexa.
  384. // 040775 => 0x41fd
  385. // 0100664 => 0x81b4
  386. result = isDir ? 0x41fd : 0x81b4;
  387. }
  388. return (result & 0xFFFF) << 16;
  389. };
  390. /**
  391. * Generate the DOS part of the external file attributes.
  392. * @param {Object} dosPermissions the dos permissions or null.
  393. * @param {Boolean} isDir true if the entry is a directory, false otherwise.
  394. * @return {Number} a 32 bit integer.
  395. *
  396. * Bit 0 Read-Only
  397. * Bit 1 Hidden
  398. * Bit 2 System
  399. * Bit 3 Volume Label
  400. * Bit 4 Directory
  401. * Bit 5 Archive
  402. */
  403. var generateDosExternalFileAttr = function (dosPermissions, isDir) {
  404. // the dir flag is already set for compatibility
  405. return (dosPermissions || 0) & 0x3F;
  406. };
  407. /**
  408. * Generate the various parts used in the construction of the final zip file.
  409. * @param {Object} streamInfo the hash with information about the compressed file.
  410. * @param {Boolean} streamedContent is the content streamed ?
  411. * @param {Boolean} streamingEnded is the stream finished ?
  412. * @param {number} offset the current offset from the start of the zip file.
  413. * @param {String} platform let's pretend we are this platform (change platform dependents fields)
  414. * @param {Function} encodeFileName the function to encode the file name / comment.
  415. * @return {Object} the zip parts.
  416. */
  417. var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
  418. var file = streamInfo['file'],
  419. compression = streamInfo['compression'],
  420. useCustomEncoding = encodeFileName !== utf8.utf8encode,
  421. encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
  422. utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
  423. comment = file.comment,
  424. encodedComment = utils.transformTo("string", encodeFileName(comment)),
  425. utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
  426. useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
  427. useUTF8ForComment = utfEncodedComment.length !== comment.length,
  428. dosTime,
  429. dosDate,
  430. extraFields = "",
  431. unicodePathExtraField = "",
  432. unicodeCommentExtraField = "",
  433. dir = file.dir,
  434. date = file.date;
  435. var dataInfo = {
  436. crc32 : 0,
  437. compressedSize : 0,
  438. uncompressedSize : 0
  439. };
  440. // if the content is streamed, the sizes/crc32 are only available AFTER
  441. // the end of the stream.
  442. if (!streamedContent || streamingEnded) {
  443. dataInfo.crc32 = streamInfo['crc32'];
  444. dataInfo.compressedSize = streamInfo['compressedSize'];
  445. dataInfo.uncompressedSize = streamInfo['uncompressedSize'];
  446. }
  447. var bitflag = 0;
  448. if (streamedContent) {
  449. // Bit 3: the sizes/crc32 are set to zero in the local header.
  450. // The correct values are put in the data descriptor immediately
  451. // following the compressed data.
  452. bitflag |= 0x0008;
  453. }
  454. if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
  455. // Bit 11: Language encoding flag (EFS).
  456. bitflag |= 0x0800;
  457. }
  458. var extFileAttr = 0;
  459. var versionMadeBy = 0;
  460. if (dir) {
  461. // dos or unix, we set the dos dir flag
  462. extFileAttr |= 0x00010;
  463. }
  464. if(platform === "UNIX") {
  465. versionMadeBy = 0x031E; // UNIX, version 3.0
  466. extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
  467. } else { // DOS or other, fallback to DOS
  468. versionMadeBy = 0x0014; // DOS, version 2.0
  469. extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
  470. }
  471. // date
  472. // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
  473. // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
  474. // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
  475. dosTime = date.getUTCHours();
  476. dosTime = dosTime << 6;
  477. dosTime = dosTime | date.getUTCMinutes();
  478. dosTime = dosTime << 5;
  479. dosTime = dosTime | date.getUTCSeconds() / 2;
  480. dosDate = date.getUTCFullYear() - 1980;
  481. dosDate = dosDate << 4;
  482. dosDate = dosDate | (date.getUTCMonth() + 1);
  483. dosDate = dosDate << 5;
  484. dosDate = dosDate | date.getUTCDate();
  485. if (useUTF8ForFileName) {
  486. // set the unicode path extra field. unzip needs at least one extra
  487. // field to correctly handle unicode path, so using the path is as good
  488. // as any other information. This could improve the situation with
  489. // other archive managers too.
  490. // This field is usually used without the utf8 flag, with a non
  491. // unicode path in the header (winrar, winzip). This helps (a bit)
  492. // with the messy Windows' default compressed folders feature but
  493. // breaks on p7zip which doesn't seek the unicode path extra field.
  494. // So for now, UTF-8 everywhere !
  495. unicodePathExtraField =
  496. // Version
  497. decToHex(1, 1) +
  498. // NameCRC32
  499. decToHex(crc32(encodedFileName), 4) +
  500. // UnicodeName
  501. utfEncodedFileName;
  502. extraFields +=
  503. // Info-ZIP Unicode Path Extra Field
  504. "\x75\x70" +
  505. // size
  506. decToHex(unicodePathExtraField.length, 2) +
  507. // content
  508. unicodePathExtraField;
  509. }
  510. if(useUTF8ForComment) {
  511. unicodeCommentExtraField =
  512. // Version
  513. decToHex(1, 1) +
  514. // CommentCRC32
  515. decToHex(crc32(encodedComment), 4) +
  516. // UnicodeName
  517. utfEncodedComment;
  518. extraFields +=
  519. // Info-ZIP Unicode Path Extra Field
  520. "\x75\x63" +
  521. // size
  522. decToHex(unicodeCommentExtraField.length, 2) +
  523. // content
  524. unicodeCommentExtraField;
  525. }
  526. var header = "";
  527. // version needed to extract
  528. header += "\x0A\x00";
  529. // general purpose bit flag
  530. header += decToHex(bitflag, 2);
  531. // compression method
  532. header += compression.magic;
  533. // last mod file time
  534. header += decToHex(dosTime, 2);
  535. // last mod file date
  536. header += decToHex(dosDate, 2);
  537. // crc-32
  538. header += decToHex(dataInfo.crc32, 4);
  539. // compressed size
  540. header += decToHex(dataInfo.compressedSize, 4);
  541. // uncompressed size
  542. header += decToHex(dataInfo.uncompressedSize, 4);
  543. // file name length
  544. header += decToHex(encodedFileName.length, 2);
  545. // extra field length
  546. header += decToHex(extraFields.length, 2);
  547. var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
  548. var dirRecord = signature.CENTRAL_FILE_HEADER +
  549. // version made by (00: DOS)
  550. decToHex(versionMadeBy, 2) +
  551. // file header (common to file and central directory)
  552. header +
  553. // file comment length
  554. decToHex(encodedComment.length, 2) +
  555. // disk number start
  556. "\x00\x00" +
  557. // internal file attributes TODO
  558. "\x00\x00" +
  559. // external file attributes
  560. decToHex(extFileAttr, 4) +
  561. // relative offset of local header
  562. decToHex(offset, 4) +
  563. // file name
  564. encodedFileName +
  565. // extra field
  566. extraFields +
  567. // file comment
  568. encodedComment;
  569. return {
  570. fileRecord: fileRecord,
  571. dirRecord: dirRecord
  572. };
  573. };
  574. /**
  575. * Generate the EOCD record.
  576. * @param {Number} entriesCount the number of entries in the zip file.
  577. * @param {Number} centralDirLength the length (in bytes) of the central dir.
  578. * @param {Number} localDirLength the length (in bytes) of the local dir.
  579. * @param {String} comment the zip file comment as a binary string.
  580. * @param {Function} encodeFileName the function to encode the comment.
  581. * @return {String} the EOCD record.
  582. */
  583. var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
  584. var dirEnd = "";
  585. var encodedComment = utils.transformTo("string", encodeFileName(comment));
  586. // end of central dir signature
  587. dirEnd = signature.CENTRAL_DIRECTORY_END +
  588. // number of this disk
  589. "\x00\x00" +
  590. // number of the disk with the start of the central directory
  591. "\x00\x00" +
  592. // total number of entries in the central directory on this disk
  593. decToHex(entriesCount, 2) +
  594. // total number of entries in the central directory
  595. decToHex(entriesCount, 2) +
  596. // size of the central directory 4 bytes
  597. decToHex(centralDirLength, 4) +
  598. // offset of start of central directory with respect to the starting disk number
  599. decToHex(localDirLength, 4) +
  600. // .ZIP file comment length
  601. decToHex(encodedComment.length, 2) +
  602. // .ZIP file comment
  603. encodedComment;
  604. return dirEnd;
  605. };
  606. /**
  607. * Generate data descriptors for a file entry.
  608. * @param {Object} streamInfo the hash generated by a worker, containing information
  609. * on the file entry.
  610. * @return {String} the data descriptors.
  611. */
  612. var generateDataDescriptors = function (streamInfo) {
  613. var descriptor = "";
  614. descriptor = signature.DATA_DESCRIPTOR +
  615. // crc-32 4 bytes
  616. decToHex(streamInfo['crc32'], 4) +
  617. // compressed size 4 bytes
  618. decToHex(streamInfo['compressedSize'], 4) +
  619. // uncompressed size 4 bytes
  620. decToHex(streamInfo['uncompressedSize'], 4);
  621. return descriptor;
  622. };
  623. /**
  624. * A worker to concatenate other workers to create a zip file.
  625. * @param {Boolean} streamFiles `true` to stream the content of the files,
  626. * `false` to accumulate it.
  627. * @param {String} comment the comment to use.
  628. * @param {String} platform the platform to use, "UNIX" or "DOS".
  629. * @param {Function} encodeFileName the function to encode file names and comments.
  630. */
  631. function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
  632. GenericWorker.call(this, "ZipFileWorker");
  633. // The number of bytes written so far. This doesn't count accumulated chunks.
  634. this.bytesWritten = 0;
  635. // The comment of the zip file
  636. this.zipComment = comment;
  637. // The platform "generating" the zip file.
  638. this.zipPlatform = platform;
  639. // the function to encode file names and comments.
  640. this.encodeFileName = encodeFileName;
  641. // Should we stream the content of the files ?
  642. this.streamFiles = streamFiles;
  643. // If `streamFiles` is false, we will need to accumulate the content of the
  644. // files to calculate sizes / crc32 (and write them *before* the content).
  645. // This boolean indicates if we are accumulating chunks (it will change a lot
  646. // during the lifetime of this worker).
  647. this.accumulate = false;
  648. // The buffer receiving chunks when accumulating content.
  649. this.contentBuffer = [];
  650. // The list of generated directory records.
  651. this.dirRecords = [];
  652. // The offset (in bytes) from the beginning of the zip file for the current source.
  653. this.currentSourceOffset = 0;
  654. // The total number of entries in this zip file.
  655. this.entriesCount = 0;
  656. // the name of the file currently being added, null when handling the end of the zip file.
  657. // Used for the emitted metadata.
  658. this.currentFile = null;
  659. this._sources = [];
  660. }
  661. utils.inherits(ZipFileWorker, GenericWorker);
  662. /**
  663. * @see GenericWorker.push
  664. */
  665. ZipFileWorker.prototype.push = function (chunk) {
  666. var currentFilePercent = chunk.meta.percent || 0;
  667. var entriesCount = this.entriesCount;
  668. var remainingFiles = this._sources.length;
  669. if(this.accumulate) {
  670. this.contentBuffer.push(chunk);
  671. } else {
  672. this.bytesWritten += chunk.data.length;
  673. GenericWorker.prototype.push.call(this, {
  674. data : chunk.data,
  675. meta : {
  676. currentFile : this.currentFile,
  677. percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
  678. }
  679. });
  680. }
  681. };
  682. /**
  683. * The worker started a new source (an other worker).
  684. * @param {Object} streamInfo the streamInfo object from the new source.
  685. */
  686. ZipFileWorker.prototype.openedSource = function (streamInfo) {
  687. this.currentSourceOffset = this.bytesWritten;
  688. this.currentFile = streamInfo['file'].name;
  689. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  690. // don't stream folders (because they don't have any content)
  691. if(streamedContent) {
  692. var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  693. this.push({
  694. data : record.fileRecord,
  695. meta : {percent:0}
  696. });
  697. } else {
  698. // we need to wait for the whole file before pushing anything
  699. this.accumulate = true;
  700. }
  701. };
  702. /**
  703. * The worker finished a source (an other worker).
  704. * @param {Object} streamInfo the streamInfo object from the finished source.
  705. */
  706. ZipFileWorker.prototype.closedSource = function (streamInfo) {
  707. this.accumulate = false;
  708. var streamedContent = this.streamFiles && !streamInfo['file'].dir;
  709. var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
  710. this.dirRecords.push(record.dirRecord);
  711. if(streamedContent) {
  712. // after the streamed file, we put data descriptors
  713. this.push({
  714. data : generateDataDescriptors(streamInfo),
  715. meta : {percent:100}
  716. });
  717. } else {
  718. // the content wasn't streamed, we need to push everything now
  719. // first the file record, then the content
  720. this.push({
  721. data : record.fileRecord,
  722. meta : {percent:0}
  723. });
  724. while(this.contentBuffer.length) {
  725. this.push(this.contentBuffer.shift());
  726. }
  727. }
  728. this.currentFile = null;
  729. };
  730. /**
  731. * @see GenericWorker.flush
  732. */
  733. ZipFileWorker.prototype.flush = function () {
  734. var localDirLength = this.bytesWritten;
  735. for(var i = 0; i < this.dirRecords.length; i++) {
  736. this.push({
  737. data : this.dirRecords[i],
  738. meta : {percent:100}
  739. });
  740. }
  741. var centralDirLength = this.bytesWritten - localDirLength;
  742. var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
  743. this.push({
  744. data : dirEnd,
  745. meta : {percent:100}
  746. });
  747. };
  748. /**
  749. * Prepare the next source to be read.
  750. */
  751. ZipFileWorker.prototype.prepareNextSource = function () {
  752. this.previous = this._sources.shift();
  753. this.openedSource(this.previous.streamInfo);
  754. if (this.isPaused) {
  755. this.previous.pause();
  756. } else {
  757. this.previous.resume();
  758. }
  759. };
  760. /**
  761. * @see GenericWorker.registerPrevious
  762. */
  763. ZipFileWorker.prototype.registerPrevious = function (previous) {
  764. this._sources.push(previous);
  765. var self = this;
  766. previous.on('data', function (chunk) {
  767. self.processChunk(chunk);
  768. });
  769. previous.on('end', function () {
  770. self.closedSource(self.previous.streamInfo);
  771. if(self._sources.length) {
  772. self.prepareNextSource();
  773. } else {
  774. self.end();
  775. }
  776. });
  777. previous.on('error', function (e) {
  778. self.error(e);
  779. });
  780. return this;
  781. };
  782. /**
  783. * @see GenericWorker.resume
  784. */
  785. ZipFileWorker.prototype.resume = function () {
  786. if(!GenericWorker.prototype.resume.call(this)) {
  787. return false;
  788. }
  789. if (!this.previous && this._sources.length) {
  790. this.prepareNextSource();
  791. return true;
  792. }
  793. if (!this.previous && !this._sources.length && !this.generatedError) {
  794. this.end();
  795. return true;
  796. }
  797. };
  798. /**
  799. * @see GenericWorker.error
  800. */
  801. ZipFileWorker.prototype.error = function (e) {
  802. var sources = this._sources;
  803. if(!GenericWorker.prototype.error.call(this, e)) {
  804. return false;
  805. }
  806. for(var i = 0; i < sources.length; i++) {
  807. try {
  808. sources[i].error(e);
  809. } catch(e) {
  810. // the `error` exploded, nothing to do
  811. }
  812. }
  813. return true;
  814. };
  815. /**
  816. * @see GenericWorker.lock
  817. */
  818. ZipFileWorker.prototype.lock = function () {
  819. GenericWorker.prototype.lock.call(this);
  820. var sources = this._sources;
  821. for(var i = 0; i < sources.length; i++) {
  822. sources[i].lock();
  823. }
  824. };
  825. module.exports = ZipFileWorker;
  826. },{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){
  827. 'use strict';
  828. var compressions = require('../compressions');
  829. var ZipFileWorker = require('./ZipFileWorker');
  830. /**
  831. * Find the compression to use.
  832. * @param {String} fileCompression the compression defined at the file level, if any.
  833. * @param {String} zipCompression the compression defined at the load() level.
  834. * @return {Object} the compression object to use.
  835. */
  836. var getCompression = function (fileCompression, zipCompression) {
  837. var compressionName = fileCompression || zipCompression;
  838. var compression = compressions[compressionName];
  839. if (!compression) {
  840. throw new Error(compressionName + " is not a valid compression method !");
  841. }
  842. return compression;
  843. };
  844. /**
  845. * Create a worker to generate a zip file.
  846. * @param {JSZip} zip the JSZip instance at the right root level.
  847. * @param {Object} options to generate the zip file.
  848. * @param {String} comment the comment to use.
  849. */
  850. exports.generateWorker = function (zip, options, comment) {
  851. var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);
  852. var entriesCount = 0;
  853. try {
  854. zip.forEach(function (relativePath, file) {
  855. entriesCount++;
  856. var compression = getCompression(file.options.compression, options.compression);
  857. var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
  858. var dir = file.dir, date = file.date;
  859. file._compressWorker(compression, compressionOptions)
  860. .withStreamInfo("file", {
  861. name : relativePath,
  862. dir : dir,
  863. date : date,
  864. comment : file.comment || "",
  865. unixPermissions : file.unixPermissions,
  866. dosPermissions : file.dosPermissions
  867. })
  868. .pipe(zipFileWorker);
  869. });
  870. zipFileWorker.entriesCount = entriesCount;
  871. } catch (e) {
  872. zipFileWorker.error(e);
  873. }
  874. return zipFileWorker;
  875. };
  876. },{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){
  877. 'use strict';
  878. /**
  879. * Representation a of zip file in js
  880. * @constructor
  881. */
  882. function JSZip() {
  883. // if this constructor is used without `new`, it adds `new` before itself:
  884. if(!(this instanceof JSZip)) {
  885. return new JSZip();
  886. }
  887. if(arguments.length) {
  888. throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
  889. }
  890. // object containing the files :
  891. // {
  892. // "folder/" : {...},
  893. // "folder/data.txt" : {...}
  894. // }
  895. // NOTE: we use a null prototype because we do not
  896. // want filenames like "toString" coming from a zip file
  897. // to overwrite methods and attributes in a normal Object.
  898. this.files = Object.create(null);
  899. this.comment = null;
  900. // Where we are in the hierarchy
  901. this.root = "";
  902. this.clone = function() {
  903. var newObj = new JSZip();
  904. for (var i in this) {
  905. if (typeof this[i] !== "function") {
  906. newObj[i] = this[i];
  907. }
  908. }
  909. return newObj;
  910. };
  911. }
  912. JSZip.prototype = require('./object');
  913. JSZip.prototype.loadAsync = require('./load');
  914. JSZip.support = require('./support');
  915. JSZip.defaults = require('./defaults');
  916. // TODO find a better way to handle this version,
  917. // a require('package.json').version doesn't work with webpack, see #327
  918. JSZip.version = "3.7.1";
  919. JSZip.loadAsync = function (content, options) {
  920. return new JSZip().loadAsync(content, options);
  921. };
  922. JSZip.external = require("./external");
  923. module.exports = JSZip;
  924. },{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){
  925. 'use strict';
  926. var utils = require('./utils');
  927. var external = require("./external");
  928. var utf8 = require('./utf8');
  929. var ZipEntries = require('./zipEntries');
  930. var Crc32Probe = require('./stream/Crc32Probe');
  931. var nodejsUtils = require("./nodejsUtils");
  932. /**
  933. * Check the CRC32 of an entry.
  934. * @param {ZipEntry} zipEntry the zip entry to check.
  935. * @return {Promise} the result.
  936. */
  937. function checkEntryCRC32(zipEntry) {
  938. return new external.Promise(function (resolve, reject) {
  939. var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
  940. worker.on("error", function (e) {
  941. reject(e);
  942. })
  943. .on("end", function () {
  944. if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
  945. reject(new Error("Corrupted zip : CRC32 mismatch"));
  946. } else {
  947. resolve();
  948. }
  949. })
  950. .resume();
  951. });
  952. }
  953. module.exports = function (data, options) {
  954. var zip = this;
  955. options = utils.extend(options || {}, {
  956. base64: false,
  957. checkCRC32: false,
  958. optimizedBinaryString: false,
  959. createFolders: false,
  960. decodeFileName: utf8.utf8decode
  961. });
  962. if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  963. return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
  964. }
  965. return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
  966. .then(function (data) {
  967. var zipEntries = new ZipEntries(options);
  968. zipEntries.load(data);
  969. return zipEntries;
  970. }).then(function checkCRC32(zipEntries) {
  971. var promises = [external.Promise.resolve(zipEntries)];
  972. var files = zipEntries.files;
  973. if (options.checkCRC32) {
  974. for (var i = 0; i < files.length; i++) {
  975. promises.push(checkEntryCRC32(files[i]));
  976. }
  977. }
  978. return external.Promise.all(promises);
  979. }).then(function addFiles(results) {
  980. var zipEntries = results.shift();
  981. var files = zipEntries.files;
  982. for (var i = 0; i < files.length; i++) {
  983. var input = files[i];
  984. zip.file(input.fileNameStr, input.decompressed, {
  985. binary: true,
  986. optimizedBinaryString: true,
  987. date: input.date,
  988. dir: input.dir,
  989. comment: input.fileCommentStr.length ? input.fileCommentStr : null,
  990. unixPermissions: input.unixPermissions,
  991. dosPermissions: input.dosPermissions,
  992. createFolders: options.createFolders
  993. });
  994. }
  995. if (zipEntries.zipComment.length) {
  996. zip.comment = zipEntries.zipComment;
  997. }
  998. return zip;
  999. });
  1000. };
  1001. },{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){
  1002. "use strict";
  1003. var utils = require('../utils');
  1004. var GenericWorker = require('../stream/GenericWorker');
  1005. /**
  1006. * A worker that use a nodejs stream as source.
  1007. * @constructor
  1008. * @param {String} filename the name of the file entry for this stream.
  1009. * @param {Readable} stream the nodejs stream.
  1010. */
  1011. function NodejsStreamInputAdapter(filename, stream) {
  1012. GenericWorker.call(this, "Nodejs stream input adapter for " + filename);
  1013. this._upstreamEnded = false;
  1014. this._bindStream(stream);
  1015. }
  1016. utils.inherits(NodejsStreamInputAdapter, GenericWorker);
  1017. /**
  1018. * Prepare the stream and bind the callbacks on it.
  1019. * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.
  1020. * @param {Stream} stream the nodejs stream to use.
  1021. */
  1022. NodejsStreamInputAdapter.prototype._bindStream = function (stream) {
  1023. var self = this;
  1024. this._stream = stream;
  1025. stream.pause();
  1026. stream
  1027. .on("data", function (chunk) {
  1028. self.push({
  1029. data: chunk,
  1030. meta : {
  1031. percent : 0
  1032. }
  1033. });
  1034. })
  1035. .on("error", function (e) {
  1036. if(self.isPaused) {
  1037. this.generatedError = e;
  1038. } else {
  1039. self.error(e);
  1040. }
  1041. })
  1042. .on("end", function () {
  1043. if(self.isPaused) {
  1044. self._upstreamEnded = true;
  1045. } else {
  1046. self.end();
  1047. }
  1048. });
  1049. };
  1050. NodejsStreamInputAdapter.prototype.pause = function () {
  1051. if(!GenericWorker.prototype.pause.call(this)) {
  1052. return false;
  1053. }
  1054. this._stream.pause();
  1055. return true;
  1056. };
  1057. NodejsStreamInputAdapter.prototype.resume = function () {
  1058. if(!GenericWorker.prototype.resume.call(this)) {
  1059. return false;
  1060. }
  1061. if(this._upstreamEnded) {
  1062. this.end();
  1063. } else {
  1064. this._stream.resume();
  1065. }
  1066. return true;
  1067. };
  1068. module.exports = NodejsStreamInputAdapter;
  1069. },{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){
  1070. 'use strict';
  1071. var Readable = require('readable-stream').Readable;
  1072. var utils = require('../utils');
  1073. utils.inherits(NodejsStreamOutputAdapter, Readable);
  1074. /**
  1075. * A nodejs stream using a worker as source.
  1076. * @see the SourceWrapper in http://nodejs.org/api/stream.html
  1077. * @constructor
  1078. * @param {StreamHelper} helper the helper wrapping the worker
  1079. * @param {Object} options the nodejs stream options
  1080. * @param {Function} updateCb the update callback.
  1081. */
  1082. function NodejsStreamOutputAdapter(helper, options, updateCb) {
  1083. Readable.call(this, options);
  1084. this._helper = helper;
  1085. var self = this;
  1086. helper.on("data", function (data, meta) {
  1087. if (!self.push(data)) {
  1088. self._helper.pause();
  1089. }
  1090. if(updateCb) {
  1091. updateCb(meta);
  1092. }
  1093. })
  1094. .on("error", function(e) {
  1095. self.emit('error', e);
  1096. })
  1097. .on("end", function () {
  1098. self.push(null);
  1099. });
  1100. }
  1101. NodejsStreamOutputAdapter.prototype._read = function() {
  1102. this._helper.resume();
  1103. };
  1104. module.exports = NodejsStreamOutputAdapter;
  1105. },{"../utils":32,"readable-stream":16}],14:[function(require,module,exports){
  1106. 'use strict';
  1107. module.exports = {
  1108. /**
  1109. * True if this is running in Nodejs, will be undefined in a browser.
  1110. * In a browser, browserify won't include this file and the whole module
  1111. * will be resolved an empty object.
  1112. */
  1113. isNode : typeof Buffer !== "undefined",
  1114. /**
  1115. * Create a new nodejs Buffer from an existing content.
  1116. * @param {Object} data the data to pass to the constructor.
  1117. * @param {String} encoding the encoding to use.
  1118. * @return {Buffer} a new Buffer.
  1119. */
  1120. newBufferFrom: function(data, encoding) {
  1121. if (Buffer.from && Buffer.from !== Uint8Array.from) {
  1122. return Buffer.from(data, encoding);
  1123. } else {
  1124. if (typeof data === "number") {
  1125. // Safeguard for old Node.js versions. On newer versions,
  1126. // Buffer.from(number) / Buffer(number, encoding) already throw.
  1127. throw new Error("The \"data\" argument must not be a number");
  1128. }
  1129. return new Buffer(data, encoding);
  1130. }
  1131. },
  1132. /**
  1133. * Create a new nodejs Buffer with the specified size.
  1134. * @param {Integer} size the size of the buffer.
  1135. * @return {Buffer} a new Buffer.
  1136. */
  1137. allocBuffer: function (size) {
  1138. if (Buffer.alloc) {
  1139. return Buffer.alloc(size);
  1140. } else {
  1141. var buf = new Buffer(size);
  1142. buf.fill(0);
  1143. return buf;
  1144. }
  1145. },
  1146. /**
  1147. * Find out if an object is a Buffer.
  1148. * @param {Object} b the object to test.
  1149. * @return {Boolean} true if the object is a Buffer, false otherwise.
  1150. */
  1151. isBuffer : function(b){
  1152. return Buffer.isBuffer(b);
  1153. },
  1154. isStream : function (obj) {
  1155. return obj &&
  1156. typeof obj.on === "function" &&
  1157. typeof obj.pause === "function" &&
  1158. typeof obj.resume === "function";
  1159. }
  1160. };
  1161. },{}],15:[function(require,module,exports){
  1162. 'use strict';
  1163. var utf8 = require('./utf8');
  1164. var utils = require('./utils');
  1165. var GenericWorker = require('./stream/GenericWorker');
  1166. var StreamHelper = require('./stream/StreamHelper');
  1167. var defaults = require('./defaults');
  1168. var CompressedObject = require('./compressedObject');
  1169. var ZipObject = require('./zipObject');
  1170. var generate = require("./generate");
  1171. var nodejsUtils = require("./nodejsUtils");
  1172. var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
  1173. /**
  1174. * Add a file in the current folder.
  1175. * @private
  1176. * @param {string} name the name of the file
  1177. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  1178. * @param {Object} originalOptions the options of the file
  1179. * @return {Object} the new file.
  1180. */
  1181. var fileAdd = function(name, data, originalOptions) {
  1182. // be sure sub folders exist
  1183. var dataType = utils.getTypeOf(data),
  1184. parent;
  1185. /*
  1186. * Correct options.
  1187. */
  1188. var o = utils.extend(originalOptions || {}, defaults);
  1189. o.date = o.date || new Date();
  1190. if (o.compression !== null) {
  1191. o.compression = o.compression.toUpperCase();
  1192. }
  1193. if (typeof o.unixPermissions === "string") {
  1194. o.unixPermissions = parseInt(o.unixPermissions, 8);
  1195. }
  1196. // UNX_IFDIR 0040000 see zipinfo.c
  1197. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  1198. o.dir = true;
  1199. }
  1200. // Bit 4 Directory
  1201. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  1202. o.dir = true;
  1203. }
  1204. if (o.dir) {
  1205. name = forceTrailingSlash(name);
  1206. }
  1207. if (o.createFolders && (parent = parentFolder(name))) {
  1208. folderAdd.call(this, parent, true);
  1209. }
  1210. var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
  1211. if (!originalOptions || typeof originalOptions.binary === "undefined") {
  1212. o.binary = !isUnicodeString;
  1213. }
  1214. var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
  1215. if (isCompressedEmpty || o.dir || !data || data.length === 0) {
  1216. o.base64 = false;
  1217. o.binary = true;
  1218. data = "";
  1219. o.compression = "STORE";
  1220. dataType = "string";
  1221. }
  1222. /*
  1223. * Convert content to fit.
  1224. */
  1225. var zipObjectContent = null;
  1226. if (data instanceof CompressedObject || data instanceof GenericWorker) {
  1227. zipObjectContent = data;
  1228. } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  1229. zipObjectContent = new NodejsStreamInputAdapter(name, data);
  1230. } else {
  1231. zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
  1232. }
  1233. var object = new ZipObject(name, zipObjectContent, o);
  1234. this.files[name] = object;
  1235. /*
  1236. TODO: we can't throw an exception because we have async promises
  1237. (we can have a promise of a Date() for example) but returning a
  1238. promise is useless because file(name, data) returns the JSZip
  1239. object for chaining. Should we break that to allow the user
  1240. to catch the error ?
  1241. return external.Promise.resolve(zipObjectContent)
  1242. .then(function () {
  1243. return object;
  1244. });
  1245. */
  1246. };
  1247. /**
  1248. * Find the parent folder of the path.
  1249. * @private
  1250. * @param {string} path the path to use
  1251. * @return {string} the parent folder, or ""
  1252. */
  1253. var parentFolder = function (path) {
  1254. if (path.slice(-1) === '/') {
  1255. path = path.substring(0, path.length - 1);
  1256. }
  1257. var lastSlash = path.lastIndexOf('/');
  1258. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  1259. };
  1260. /**
  1261. * Returns the path with a slash at the end.
  1262. * @private
  1263. * @param {String} path the path to check.
  1264. * @return {String} the path with a trailing slash.
  1265. */
  1266. var forceTrailingSlash = function(path) {
  1267. // Check the name ends with a /
  1268. if (path.slice(-1) !== "/") {
  1269. path += "/"; // IE doesn't like substr(-1)
  1270. }
  1271. return path;
  1272. };
  1273. /**
  1274. * Add a (sub) folder in the current folder.
  1275. * @private
  1276. * @param {string} name the folder's name
  1277. * @param {boolean=} [createFolders] If true, automatically create sub
  1278. * folders. Defaults to false.
  1279. * @return {Object} the new folder.
  1280. */
  1281. var folderAdd = function(name, createFolders) {
  1282. createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders;
  1283. name = forceTrailingSlash(name);
  1284. // Does this folder already exist?
  1285. if (!this.files[name]) {
  1286. fileAdd.call(this, name, null, {
  1287. dir: true,
  1288. createFolders: createFolders
  1289. });
  1290. }
  1291. return this.files[name];
  1292. };
  1293. /**
  1294. * Cross-window, cross-Node-context regular expression detection
  1295. * @param {Object} object Anything
  1296. * @return {Boolean} true if the object is a regular expression,
  1297. * false otherwise
  1298. */
  1299. function isRegExp(object) {
  1300. return Object.prototype.toString.call(object) === "[object RegExp]";
  1301. }
  1302. // return the actual prototype of JSZip
  1303. var out = {
  1304. /**
  1305. * @see loadAsync
  1306. */
  1307. load: function() {
  1308. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1309. },
  1310. /**
  1311. * Call a callback function for each entry at this folder level.
  1312. * @param {Function} cb the callback function:
  1313. * function (relativePath, file) {...}
  1314. * It takes 2 arguments : the relative path and the file.
  1315. */
  1316. forEach: function(cb) {
  1317. var filename, relativePath, file;
  1318. /* jshint ignore:start */
  1319. // ignore warning about unwanted properties because this.files is a null prototype object
  1320. for (filename in this.files) {
  1321. file = this.files[filename];
  1322. relativePath = filename.slice(this.root.length, filename.length);
  1323. if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
  1324. cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
  1325. }
  1326. }
  1327. /* jshint ignore:end */
  1328. },
  1329. /**
  1330. * Filter nested files/folders with the specified function.
  1331. * @param {Function} search the predicate to use :
  1332. * function (relativePath, file) {...}
  1333. * It takes 2 arguments : the relative path and the file.
  1334. * @return {Array} An array of matching elements.
  1335. */
  1336. filter: function(search) {
  1337. var result = [];
  1338. this.forEach(function (relativePath, entry) {
  1339. if (search(relativePath, entry)) { // the file matches the function
  1340. result.push(entry);
  1341. }
  1342. });
  1343. return result;
  1344. },
  1345. /**
  1346. * Add a file to the zip file, or search a file.
  1347. * @param {string|RegExp} name The name of the file to add (if data is defined),
  1348. * the name of the file to find (if no data) or a regex to match files.
  1349. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  1350. * @param {Object} o File options
  1351. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  1352. * a file (when searching by string) or an array of files (when searching by regex).
  1353. */
  1354. file: function(name, data, o) {
  1355. if (arguments.length === 1) {
  1356. if (isRegExp(name)) {
  1357. var regexp = name;
  1358. return this.filter(function(relativePath, file) {
  1359. return !file.dir && regexp.test(relativePath);
  1360. });
  1361. }
  1362. else { // text
  1363. var obj = this.files[this.root + name];
  1364. if (obj && !obj.dir) {
  1365. return obj;
  1366. } else {
  1367. return null;
  1368. }
  1369. }
  1370. }
  1371. else { // more than one argument : we have data !
  1372. name = this.root + name;
  1373. fileAdd.call(this, name, data, o);
  1374. }
  1375. return this;
  1376. },
  1377. /**
  1378. * Add a directory to the zip file, or search.
  1379. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  1380. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  1381. */
  1382. folder: function(arg) {
  1383. if (!arg) {
  1384. return this;
  1385. }
  1386. if (isRegExp(arg)) {
  1387. return this.filter(function(relativePath, file) {
  1388. return file.dir && arg.test(relativePath);
  1389. });
  1390. }
  1391. // else, name is a new folder
  1392. var name = this.root + arg;
  1393. var newFolder = folderAdd.call(this, name);
  1394. // Allow chaining by returning a new object with this folder as the root
  1395. var ret = this.clone();
  1396. ret.root = newFolder.name;
  1397. return ret;
  1398. },
  1399. /**
  1400. * Delete a file, or a directory and all sub-files, from the zip
  1401. * @param {string} name the name of the file to delete
  1402. * @return {JSZip} this JSZip object
  1403. */
  1404. remove: function(name) {
  1405. name = this.root + name;
  1406. var file = this.files[name];
  1407. if (!file) {
  1408. // Look for any folders
  1409. if (name.slice(-1) !== "/") {
  1410. name += "/";
  1411. }
  1412. file = this.files[name];
  1413. }
  1414. if (file && !file.dir) {
  1415. // file
  1416. delete this.files[name];
  1417. } else {
  1418. // maybe a folder, delete recursively
  1419. var kids = this.filter(function(relativePath, file) {
  1420. return file.name.slice(0, name.length) === name;
  1421. });
  1422. for (var i = 0; i < kids.length; i++) {
  1423. delete this.files[kids[i].name];
  1424. }
  1425. }
  1426. return this;
  1427. },
  1428. /**
  1429. * Generate the complete zip file
  1430. * @param {Object} options the options to generate the zip file :
  1431. * - compression, "STORE" by default.
  1432. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1433. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
  1434. */
  1435. generate: function(options) {
  1436. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  1437. },
  1438. /**
  1439. * Generate the complete zip file as an internal stream.
  1440. * @param {Object} options the options to generate the zip file :
  1441. * - compression, "STORE" by default.
  1442. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  1443. * @return {StreamHelper} the streamed zip file.
  1444. */
  1445. generateInternalStream: function(options) {
  1446. var worker, opts = {};
  1447. try {
  1448. opts = utils.extend(options || {}, {
  1449. streamFiles: false,
  1450. compression: "STORE",
  1451. compressionOptions : null,
  1452. type: "",
  1453. platform: "DOS",
  1454. comment: null,
  1455. mimeType: 'application/zip',
  1456. encodeFileName: utf8.utf8encode
  1457. });
  1458. opts.type = opts.type.toLowerCase();
  1459. opts.compression = opts.compression.toUpperCase();
  1460. // "binarystring" is preferred but the internals use "string".
  1461. if(opts.type === "binarystring") {
  1462. opts.type = "string";
  1463. }
  1464. if (!opts.type) {
  1465. throw new Error("No output type specified.");
  1466. }
  1467. utils.checkSupport(opts.type);
  1468. // accept nodejs `process.platform`
  1469. if(
  1470. opts.platform === 'darwin' ||
  1471. opts.platform === 'freebsd' ||
  1472. opts.platform === 'linux' ||
  1473. opts.platform === 'sunos'
  1474. ) {
  1475. opts.platform = "UNIX";
  1476. }
  1477. if (opts.platform === 'win32') {
  1478. opts.platform = "DOS";
  1479. }
  1480. var comment = opts.comment || this.comment || "";
  1481. worker = generate.generateWorker(this, opts, comment);
  1482. } catch (e) {
  1483. worker = new GenericWorker("error");
  1484. worker.error(e);
  1485. }
  1486. return new StreamHelper(worker, opts.type || "string", opts.mimeType);
  1487. },
  1488. /**
  1489. * Generate the complete zip file asynchronously.
  1490. * @see generateInternalStream
  1491. */
  1492. generateAsync: function(options, onUpdate) {
  1493. return this.generateInternalStream(options).accumulate(onUpdate);
  1494. },
  1495. /**
  1496. * Generate the complete zip file asynchronously.
  1497. * @see generateInternalStream
  1498. */
  1499. generateNodeStream: function(options, onUpdate) {
  1500. options = options || {};
  1501. if (!options.type) {
  1502. options.type = "nodebuffer";
  1503. }
  1504. return this.generateInternalStream(options).toNodejsStream(onUpdate);
  1505. }
  1506. };
  1507. module.exports = out;
  1508. },{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(require,module,exports){
  1509. /*
  1510. * This file is used by module bundlers (browserify/webpack/etc) when
  1511. * including a stream implementation. We use "readable-stream" to get a
  1512. * consistent behavior between nodejs versions but bundlers often have a shim
  1513. * for "stream". Using this shim greatly improve the compatibility and greatly
  1514. * reduce the final size of the bundle (only one stream implementation, not
  1515. * two).
  1516. */
  1517. module.exports = require("stream");
  1518. },{"stream":undefined}],17:[function(require,module,exports){
  1519. 'use strict';
  1520. var DataReader = require('./DataReader');
  1521. var utils = require('../utils');
  1522. function ArrayReader(data) {
  1523. DataReader.call(this, data);
  1524. for(var i = 0; i < this.data.length; i++) {
  1525. data[i] = data[i] & 0xFF;
  1526. }
  1527. }
  1528. utils.inherits(ArrayReader, DataReader);
  1529. /**
  1530. * @see DataReader.byteAt
  1531. */
  1532. ArrayReader.prototype.byteAt = function(i) {
  1533. return this.data[this.zero + i];
  1534. };
  1535. /**
  1536. * @see DataReader.lastIndexOfSignature
  1537. */
  1538. ArrayReader.prototype.lastIndexOfSignature = function(sig) {
  1539. var sig0 = sig.charCodeAt(0),
  1540. sig1 = sig.charCodeAt(1),
  1541. sig2 = sig.charCodeAt(2),
  1542. sig3 = sig.charCodeAt(3);
  1543. for (var i = this.length - 4; i >= 0; --i) {
  1544. if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
  1545. return i - this.zero;
  1546. }
  1547. }
  1548. return -1;
  1549. };
  1550. /**
  1551. * @see DataReader.readAndCheckSignature
  1552. */
  1553. ArrayReader.prototype.readAndCheckSignature = function (sig) {
  1554. var sig0 = sig.charCodeAt(0),
  1555. sig1 = sig.charCodeAt(1),
  1556. sig2 = sig.charCodeAt(2),
  1557. sig3 = sig.charCodeAt(3),
  1558. data = this.readData(4);
  1559. return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];
  1560. };
  1561. /**
  1562. * @see DataReader.readData
  1563. */
  1564. ArrayReader.prototype.readData = function(size) {
  1565. this.checkOffset(size);
  1566. if(size === 0) {
  1567. return [];
  1568. }
  1569. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1570. this.index += size;
  1571. return result;
  1572. };
  1573. module.exports = ArrayReader;
  1574. },{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){
  1575. 'use strict';
  1576. var utils = require('../utils');
  1577. function DataReader(data) {
  1578. this.data = data; // type : see implementation
  1579. this.length = data.length;
  1580. this.index = 0;
  1581. this.zero = 0;
  1582. }
  1583. DataReader.prototype = {
  1584. /**
  1585. * Check that the offset will not go too far.
  1586. * @param {string} offset the additional offset to check.
  1587. * @throws {Error} an Error if the offset is out of bounds.
  1588. */
  1589. checkOffset: function(offset) {
  1590. this.checkIndex(this.index + offset);
  1591. },
  1592. /**
  1593. * Check that the specified index will not be too far.
  1594. * @param {string} newIndex the index to check.
  1595. * @throws {Error} an Error if the index is out of bounds.
  1596. */
  1597. checkIndex: function(newIndex) {
  1598. if (this.length < this.zero + newIndex || newIndex < 0) {
  1599. throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
  1600. }
  1601. },
  1602. /**
  1603. * Change the index.
  1604. * @param {number} newIndex The new index.
  1605. * @throws {Error} if the new index is out of the data.
  1606. */
  1607. setIndex: function(newIndex) {
  1608. this.checkIndex(newIndex);
  1609. this.index = newIndex;
  1610. },
  1611. /**
  1612. * Skip the next n bytes.
  1613. * @param {number} n the number of bytes to skip.
  1614. * @throws {Error} if the new index is out of the data.
  1615. */
  1616. skip: function(n) {
  1617. this.setIndex(this.index + n);
  1618. },
  1619. /**
  1620. * Get the byte at the specified index.
  1621. * @param {number} i the index to use.
  1622. * @return {number} a byte.
  1623. */
  1624. byteAt: function(i) {
  1625. // see implementations
  1626. },
  1627. /**
  1628. * Get the next number with a given byte size.
  1629. * @param {number} size the number of bytes to read.
  1630. * @return {number} the corresponding number.
  1631. */
  1632. readInt: function(size) {
  1633. var result = 0,
  1634. i;
  1635. this.checkOffset(size);
  1636. for (i = this.index + size - 1; i >= this.index; i--) {
  1637. result = (result << 8) + this.byteAt(i);
  1638. }
  1639. this.index += size;
  1640. return result;
  1641. },
  1642. /**
  1643. * Get the next string with a given byte size.
  1644. * @param {number} size the number of bytes to read.
  1645. * @return {string} the corresponding string.
  1646. */
  1647. readString: function(size) {
  1648. return utils.transformTo("string", this.readData(size));
  1649. },
  1650. /**
  1651. * Get raw data without conversion, <size> bytes.
  1652. * @param {number} size the number of bytes to read.
  1653. * @return {Object} the raw data, implementation specific.
  1654. */
  1655. readData: function(size) {
  1656. // see implementations
  1657. },
  1658. /**
  1659. * Find the last occurrence of a zip signature (4 bytes).
  1660. * @param {string} sig the signature to find.
  1661. * @return {number} the index of the last occurrence, -1 if not found.
  1662. */
  1663. lastIndexOfSignature: function(sig) {
  1664. // see implementations
  1665. },
  1666. /**
  1667. * Read the signature (4 bytes) at the current position and compare it with sig.
  1668. * @param {string} sig the expected signature
  1669. * @return {boolean} true if the signature matches, false otherwise.
  1670. */
  1671. readAndCheckSignature: function(sig) {
  1672. // see implementations
  1673. },
  1674. /**
  1675. * Get the next date.
  1676. * @return {Date} the date.
  1677. */
  1678. readDate: function() {
  1679. var dostime = this.readInt(4);
  1680. return new Date(Date.UTC(
  1681. ((dostime >> 25) & 0x7f) + 1980, // year
  1682. ((dostime >> 21) & 0x0f) - 1, // month
  1683. (dostime >> 16) & 0x1f, // day
  1684. (dostime >> 11) & 0x1f, // hour
  1685. (dostime >> 5) & 0x3f, // minute
  1686. (dostime & 0x1f) << 1)); // second
  1687. }
  1688. };
  1689. module.exports = DataReader;
  1690. },{"../utils":32}],19:[function(require,module,exports){
  1691. 'use strict';
  1692. var Uint8ArrayReader = require('./Uint8ArrayReader');
  1693. var utils = require('../utils');
  1694. function NodeBufferReader(data) {
  1695. Uint8ArrayReader.call(this, data);
  1696. }
  1697. utils.inherits(NodeBufferReader, Uint8ArrayReader);
  1698. /**
  1699. * @see DataReader.readData
  1700. */
  1701. NodeBufferReader.prototype.readData = function(size) {
  1702. this.checkOffset(size);
  1703. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1704. this.index += size;
  1705. return result;
  1706. };
  1707. module.exports = NodeBufferReader;
  1708. },{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){
  1709. 'use strict';
  1710. var DataReader = require('./DataReader');
  1711. var utils = require('../utils');
  1712. function StringReader(data) {
  1713. DataReader.call(this, data);
  1714. }
  1715. utils.inherits(StringReader, DataReader);
  1716. /**
  1717. * @see DataReader.byteAt
  1718. */
  1719. StringReader.prototype.byteAt = function(i) {
  1720. return this.data.charCodeAt(this.zero + i);
  1721. };
  1722. /**
  1723. * @see DataReader.lastIndexOfSignature
  1724. */
  1725. StringReader.prototype.lastIndexOfSignature = function(sig) {
  1726. return this.data.lastIndexOf(sig) - this.zero;
  1727. };
  1728. /**
  1729. * @see DataReader.readAndCheckSignature
  1730. */
  1731. StringReader.prototype.readAndCheckSignature = function (sig) {
  1732. var data = this.readData(4);
  1733. return sig === data;
  1734. };
  1735. /**
  1736. * @see DataReader.readData
  1737. */
  1738. StringReader.prototype.readData = function(size) {
  1739. this.checkOffset(size);
  1740. // this will work because the constructor applied the "& 0xff" mask.
  1741. var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
  1742. this.index += size;
  1743. return result;
  1744. };
  1745. module.exports = StringReader;
  1746. },{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){
  1747. 'use strict';
  1748. var ArrayReader = require('./ArrayReader');
  1749. var utils = require('../utils');
  1750. function Uint8ArrayReader(data) {
  1751. ArrayReader.call(this, data);
  1752. }
  1753. utils.inherits(Uint8ArrayReader, ArrayReader);
  1754. /**
  1755. * @see DataReader.readData
  1756. */
  1757. Uint8ArrayReader.prototype.readData = function(size) {
  1758. this.checkOffset(size);
  1759. if(size === 0) {
  1760. // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
  1761. return new Uint8Array(0);
  1762. }
  1763. var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
  1764. this.index += size;
  1765. return result;
  1766. };
  1767. module.exports = Uint8ArrayReader;
  1768. },{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){
  1769. 'use strict';
  1770. var utils = require('../utils');
  1771. var support = require('../support');
  1772. var ArrayReader = require('./ArrayReader');
  1773. var StringReader = require('./StringReader');
  1774. var NodeBufferReader = require('./NodeBufferReader');
  1775. var Uint8ArrayReader = require('./Uint8ArrayReader');
  1776. /**
  1777. * Create a reader adapted to the data.
  1778. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.
  1779. * @return {DataReader} the data reader.
  1780. */
  1781. module.exports = function (data) {
  1782. var type = utils.getTypeOf(data);
  1783. utils.checkSupport(type);
  1784. if (type === "string" && !support.uint8array) {
  1785. return new StringReader(data);
  1786. }
  1787. if (type === "nodebuffer") {
  1788. return new NodeBufferReader(data);
  1789. }
  1790. if (support.uint8array) {
  1791. return new Uint8ArrayReader(utils.transformTo("uint8array", data));
  1792. }
  1793. return new ArrayReader(utils.transformTo("array", data));
  1794. };
  1795. },{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){
  1796. 'use strict';
  1797. exports.LOCAL_FILE_HEADER = "PK\x03\x04";
  1798. exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
  1799. exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
  1800. exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
  1801. exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
  1802. exports.DATA_DESCRIPTOR = "PK\x07\x08";
  1803. },{}],24:[function(require,module,exports){
  1804. 'use strict';
  1805. var GenericWorker = require('./GenericWorker');
  1806. var utils = require('../utils');
  1807. /**
  1808. * A worker which convert chunks to a specified type.
  1809. * @constructor
  1810. * @param {String} destType the destination type.
  1811. */
  1812. function ConvertWorker(destType) {
  1813. GenericWorker.call(this, "ConvertWorker to " + destType);
  1814. this.destType = destType;
  1815. }
  1816. utils.inherits(ConvertWorker, GenericWorker);
  1817. /**
  1818. * @see GenericWorker.processChunk
  1819. */
  1820. ConvertWorker.prototype.processChunk = function (chunk) {
  1821. this.push({
  1822. data : utils.transformTo(this.destType, chunk.data),
  1823. meta : chunk.meta
  1824. });
  1825. };
  1826. module.exports = ConvertWorker;
  1827. },{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){
  1828. 'use strict';
  1829. var GenericWorker = require('./GenericWorker');
  1830. var crc32 = require('../crc32');
  1831. var utils = require('../utils');
  1832. /**
  1833. * A worker which calculate the crc32 of the data flowing through.
  1834. * @constructor
  1835. */
  1836. function Crc32Probe() {
  1837. GenericWorker.call(this, "Crc32Probe");
  1838. this.withStreamInfo("crc32", 0);
  1839. }
  1840. utils.inherits(Crc32Probe, GenericWorker);
  1841. /**
  1842. * @see GenericWorker.processChunk
  1843. */
  1844. Crc32Probe.prototype.processChunk = function (chunk) {
  1845. this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);
  1846. this.push(chunk);
  1847. };
  1848. module.exports = Crc32Probe;
  1849. },{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){
  1850. 'use strict';
  1851. var utils = require('../utils');
  1852. var GenericWorker = require('./GenericWorker');
  1853. /**
  1854. * A worker which calculate the total length of the data flowing through.
  1855. * @constructor
  1856. * @param {String} propName the name used to expose the length
  1857. */
  1858. function DataLengthProbe(propName) {
  1859. GenericWorker.call(this, "DataLengthProbe for " + propName);
  1860. this.propName = propName;
  1861. this.withStreamInfo(propName, 0);
  1862. }
  1863. utils.inherits(DataLengthProbe, GenericWorker);
  1864. /**
  1865. * @see GenericWorker.processChunk
  1866. */
  1867. DataLengthProbe.prototype.processChunk = function (chunk) {
  1868. if(chunk) {
  1869. var length = this.streamInfo[this.propName] || 0;
  1870. this.streamInfo[this.propName] = length + chunk.data.length;
  1871. }
  1872. GenericWorker.prototype.processChunk.call(this, chunk);
  1873. };
  1874. module.exports = DataLengthProbe;
  1875. },{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){
  1876. 'use strict';
  1877. var utils = require('../utils');
  1878. var GenericWorker = require('./GenericWorker');
  1879. // the size of the generated chunks
  1880. // TODO expose this as a public variable
  1881. var DEFAULT_BLOCK_SIZE = 16 * 1024;
  1882. /**
  1883. * A worker that reads a content and emits chunks.
  1884. * @constructor
  1885. * @param {Promise} dataP the promise of the data to split
  1886. */
  1887. function DataWorker(dataP) {
  1888. GenericWorker.call(this, "DataWorker");
  1889. var self = this;
  1890. this.dataIsReady = false;
  1891. this.index = 0;
  1892. this.max = 0;
  1893. this.data = null;
  1894. this.type = "";
  1895. this._tickScheduled = false;
  1896. dataP.then(function (data) {
  1897. self.dataIsReady = true;
  1898. self.data = data;
  1899. self.max = data && data.length || 0;
  1900. self.type = utils.getTypeOf(data);
  1901. if(!self.isPaused) {
  1902. self._tickAndRepeat();
  1903. }
  1904. }, function (e) {
  1905. self.error(e);
  1906. });
  1907. }
  1908. utils.inherits(DataWorker, GenericWorker);
  1909. /**
  1910. * @see GenericWorker.cleanUp
  1911. */
  1912. DataWorker.prototype.cleanUp = function () {
  1913. GenericWorker.prototype.cleanUp.call(this);
  1914. this.data = null;
  1915. };
  1916. /**
  1917. * @see GenericWorker.resume
  1918. */
  1919. DataWorker.prototype.resume = function () {
  1920. if(!GenericWorker.prototype.resume.call(this)) {
  1921. return false;
  1922. }
  1923. if (!this._tickScheduled && this.dataIsReady) {
  1924. this._tickScheduled = true;
  1925. utils.delay(this._tickAndRepeat, [], this);
  1926. }
  1927. return true;
  1928. };
  1929. /**
  1930. * Trigger a tick a schedule an other call to this function.
  1931. */
  1932. DataWorker.prototype._tickAndRepeat = function() {
  1933. this._tickScheduled = false;
  1934. if(this.isPaused || this.isFinished) {
  1935. return;
  1936. }
  1937. this._tick();
  1938. if(!this.isFinished) {
  1939. utils.delay(this._tickAndRepeat, [], this);
  1940. this._tickScheduled = true;
  1941. }
  1942. };
  1943. /**
  1944. * Read and push a chunk.
  1945. */
  1946. DataWorker.prototype._tick = function() {
  1947. if(this.isPaused || this.isFinished) {
  1948. return false;
  1949. }
  1950. var size = DEFAULT_BLOCK_SIZE;
  1951. var data = null, nextIndex = Math.min(this.max, this.index + size);
  1952. if (this.index >= this.max) {
  1953. // EOF
  1954. return this.end();
  1955. } else {
  1956. switch(this.type) {
  1957. case "string":
  1958. data = this.data.substring(this.index, nextIndex);
  1959. break;
  1960. case "uint8array":
  1961. data = this.data.subarray(this.index, nextIndex);
  1962. break;
  1963. case "array":
  1964. case "nodebuffer":
  1965. data = this.data.slice(this.index, nextIndex);
  1966. break;
  1967. }
  1968. this.index = nextIndex;
  1969. return this.push({
  1970. data : data,
  1971. meta : {
  1972. percent : this.max ? this.index / this.max * 100 : 0
  1973. }
  1974. });
  1975. }
  1976. };
  1977. module.exports = DataWorker;
  1978. },{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){
  1979. 'use strict';
  1980. /**
  1981. * A worker that does nothing but passing chunks to the next one. This is like
  1982. * a nodejs stream but with some differences. On the good side :
  1983. * - it works on IE 6-9 without any issue / polyfill
  1984. * - it weights less than the full dependencies bundled with browserify
  1985. * - it forwards errors (no need to declare an error handler EVERYWHERE)
  1986. *
  1987. * A chunk is an object with 2 attributes : `meta` and `data`. The former is an
  1988. * object containing anything (`percent` for example), see each worker for more
  1989. * details. The latter is the real data (String, Uint8Array, etc).
  1990. *
  1991. * @constructor
  1992. * @param {String} name the name of the stream (mainly used for debugging purposes)
  1993. */
  1994. function GenericWorker(name) {
  1995. // the name of the worker
  1996. this.name = name || "default";
  1997. // an object containing metadata about the workers chain
  1998. this.streamInfo = {};
  1999. // an error which happened when the worker was paused
  2000. this.generatedError = null;
  2001. // an object containing metadata to be merged by this worker into the general metadata
  2002. this.extraStreamInfo = {};
  2003. // true if the stream is paused (and should not do anything), false otherwise
  2004. this.isPaused = true;
  2005. // true if the stream is finished (and should not do anything), false otherwise
  2006. this.isFinished = false;
  2007. // true if the stream is locked to prevent further structure updates (pipe), false otherwise
  2008. this.isLocked = false;
  2009. // the event listeners
  2010. this._listeners = {
  2011. 'data':[],
  2012. 'end':[],
  2013. 'error':[]
  2014. };
  2015. // the previous worker, if any
  2016. this.previous = null;
  2017. }
  2018. GenericWorker.prototype = {
  2019. /**
  2020. * Push a chunk to the next workers.
  2021. * @param {Object} chunk the chunk to push
  2022. */
  2023. push : function (chunk) {
  2024. this.emit("data", chunk);
  2025. },
  2026. /**
  2027. * End the stream.
  2028. * @return {Boolean} true if this call ended the worker, false otherwise.
  2029. */
  2030. end : function () {
  2031. if (this.isFinished) {
  2032. return false;
  2033. }
  2034. this.flush();
  2035. try {
  2036. this.emit("end");
  2037. this.cleanUp();
  2038. this.isFinished = true;
  2039. } catch (e) {
  2040. this.emit("error", e);
  2041. }
  2042. return true;
  2043. },
  2044. /**
  2045. * End the stream with an error.
  2046. * @param {Error} e the error which caused the premature end.
  2047. * @return {Boolean} true if this call ended the worker with an error, false otherwise.
  2048. */
  2049. error : function (e) {
  2050. if (this.isFinished) {
  2051. return false;
  2052. }
  2053. if(this.isPaused) {
  2054. this.generatedError = e;
  2055. } else {
  2056. this.isFinished = true;
  2057. this.emit("error", e);
  2058. // in the workers chain exploded in the middle of the chain,
  2059. // the error event will go downward but we also need to notify
  2060. // workers upward that there has been an error.
  2061. if(this.previous) {
  2062. this.previous.error(e);
  2063. }
  2064. this.cleanUp();
  2065. }
  2066. return true;
  2067. },
  2068. /**
  2069. * Add a callback on an event.
  2070. * @param {String} name the name of the event (data, end, error)
  2071. * @param {Function} listener the function to call when the event is triggered
  2072. * @return {GenericWorker} the current object for chainability
  2073. */
  2074. on : function (name, listener) {
  2075. this._listeners[name].push(listener);
  2076. return this;
  2077. },
  2078. /**
  2079. * Clean any references when a worker is ending.
  2080. */
  2081. cleanUp : function () {
  2082. this.streamInfo = this.generatedError = this.extraStreamInfo = null;
  2083. this._listeners = [];
  2084. },
  2085. /**
  2086. * Trigger an event. This will call registered callback with the provided arg.
  2087. * @param {String} name the name of the event (data, end, error)
  2088. * @param {Object} arg the argument to call the callback with.
  2089. */
  2090. emit : function (name, arg) {
  2091. if (this._listeners[name]) {
  2092. for(var i = 0; i < this._listeners[name].length; i++) {
  2093. this._listeners[name][i].call(this, arg);
  2094. }
  2095. }
  2096. },
  2097. /**
  2098. * Chain a worker with an other.
  2099. * @param {Worker} next the worker receiving events from the current one.
  2100. * @return {worker} the next worker for chainability
  2101. */
  2102. pipe : function (next) {
  2103. return next.registerPrevious(this);
  2104. },
  2105. /**
  2106. * Same as `pipe` in the other direction.
  2107. * Using an API with `pipe(next)` is very easy.
  2108. * Implementing the API with the point of view of the next one registering
  2109. * a source is easier, see the ZipFileWorker.
  2110. * @param {Worker} previous the previous worker, sending events to this one
  2111. * @return {Worker} the current worker for chainability
  2112. */
  2113. registerPrevious : function (previous) {
  2114. if (this.isLocked) {
  2115. throw new Error("The stream '" + this + "' has already been used.");
  2116. }
  2117. // sharing the streamInfo...
  2118. this.streamInfo = previous.streamInfo;
  2119. // ... and adding our own bits
  2120. this.mergeStreamInfo();
  2121. this.previous = previous;
  2122. var self = this;
  2123. previous.on('data', function (chunk) {
  2124. self.processChunk(chunk);
  2125. });
  2126. previous.on('end', function () {
  2127. self.end();
  2128. });
  2129. previous.on('error', function (e) {
  2130. self.error(e);
  2131. });
  2132. return this;
  2133. },
  2134. /**
  2135. * Pause the stream so it doesn't send events anymore.
  2136. * @return {Boolean} true if this call paused the worker, false otherwise.
  2137. */
  2138. pause : function () {
  2139. if(this.isPaused || this.isFinished) {
  2140. return false;
  2141. }
  2142. this.isPaused = true;
  2143. if(this.previous) {
  2144. this.previous.pause();
  2145. }
  2146. return true;
  2147. },
  2148. /**
  2149. * Resume a paused stream.
  2150. * @return {Boolean} true if this call resumed the worker, false otherwise.
  2151. */
  2152. resume : function () {
  2153. if(!this.isPaused || this.isFinished) {
  2154. return false;
  2155. }
  2156. this.isPaused = false;
  2157. // if true, the worker tried to resume but failed
  2158. var withError = false;
  2159. if(this.generatedError) {
  2160. this.error(this.generatedError);
  2161. withError = true;
  2162. }
  2163. if(this.previous) {
  2164. this.previous.resume();
  2165. }
  2166. return !withError;
  2167. },
  2168. /**
  2169. * Flush any remaining bytes as the stream is ending.
  2170. */
  2171. flush : function () {},
  2172. /**
  2173. * Process a chunk. This is usually the method overridden.
  2174. * @param {Object} chunk the chunk to process.
  2175. */
  2176. processChunk : function(chunk) {
  2177. this.push(chunk);
  2178. },
  2179. /**
  2180. * Add a key/value to be added in the workers chain streamInfo once activated.
  2181. * @param {String} key the key to use
  2182. * @param {Object} value the associated value
  2183. * @return {Worker} the current worker for chainability
  2184. */
  2185. withStreamInfo : function (key, value) {
  2186. this.extraStreamInfo[key] = value;
  2187. this.mergeStreamInfo();
  2188. return this;
  2189. },
  2190. /**
  2191. * Merge this worker's streamInfo into the chain's streamInfo.
  2192. */
  2193. mergeStreamInfo : function () {
  2194. for(var key in this.extraStreamInfo) {
  2195. if (!this.extraStreamInfo.hasOwnProperty(key)) {
  2196. continue;
  2197. }
  2198. this.streamInfo[key] = this.extraStreamInfo[key];
  2199. }
  2200. },
  2201. /**
  2202. * Lock the stream to prevent further updates on the workers chain.
  2203. * After calling this method, all calls to pipe will fail.
  2204. */
  2205. lock: function () {
  2206. if (this.isLocked) {
  2207. throw new Error("The stream '" + this + "' has already been used.");
  2208. }
  2209. this.isLocked = true;
  2210. if (this.previous) {
  2211. this.previous.lock();
  2212. }
  2213. },
  2214. /**
  2215. *
  2216. * Pretty print the workers chain.
  2217. */
  2218. toString : function () {
  2219. var me = "Worker " + this.name;
  2220. if (this.previous) {
  2221. return this.previous + " -> " + me;
  2222. } else {
  2223. return me;
  2224. }
  2225. }
  2226. };
  2227. module.exports = GenericWorker;
  2228. },{}],29:[function(require,module,exports){
  2229. 'use strict';
  2230. var utils = require('../utils');
  2231. var ConvertWorker = require('./ConvertWorker');
  2232. var GenericWorker = require('./GenericWorker');
  2233. var base64 = require('../base64');
  2234. var support = require("../support");
  2235. var external = require("../external");
  2236. var NodejsStreamOutputAdapter = null;
  2237. if (support.nodestream) {
  2238. try {
  2239. NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');
  2240. } catch(e) {}
  2241. }
  2242. /**
  2243. * Apply the final transformation of the data. If the user wants a Blob for
  2244. * example, it's easier to work with an U8intArray and finally do the
  2245. * ArrayBuffer/Blob conversion.
  2246. * @param {String} type the name of the final type
  2247. * @param {String|Uint8Array|Buffer} content the content to transform
  2248. * @param {String} mimeType the mime type of the content, if applicable.
  2249. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
  2250. */
  2251. function transformZipOutput(type, content, mimeType) {
  2252. switch(type) {
  2253. case "blob" :
  2254. return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType);
  2255. case "base64" :
  2256. return base64.encode(content);
  2257. default :
  2258. return utils.transformTo(type, content);
  2259. }
  2260. }
  2261. /**
  2262. * Concatenate an array of data of the given type.
  2263. * @param {String} type the type of the data in the given array.
  2264. * @param {Array} dataArray the array containing the data chunks to concatenate
  2265. * @return {String|Uint8Array|Buffer} the concatenated data
  2266. * @throws Error if the asked type is unsupported
  2267. */
  2268. function concat (type, dataArray) {
  2269. var i, index = 0, res = null, totalLength = 0;
  2270. for(i = 0; i < dataArray.length; i++) {
  2271. totalLength += dataArray[i].length;
  2272. }
  2273. switch(type) {
  2274. case "string":
  2275. return dataArray.join("");
  2276. case "array":
  2277. return Array.prototype.concat.apply([], dataArray);
  2278. case "uint8array":
  2279. res = new Uint8Array(totalLength);
  2280. for(i = 0; i < dataArray.length; i++) {
  2281. res.set(dataArray[i], index);
  2282. index += dataArray[i].length;
  2283. }
  2284. return res;
  2285. case "nodebuffer":
  2286. return Buffer.concat(dataArray);
  2287. default:
  2288. throw new Error("concat : unsupported type '" + type + "'");
  2289. }
  2290. }
  2291. /**
  2292. * Listen a StreamHelper, accumulate its content and concatenate it into a
  2293. * complete block.
  2294. * @param {StreamHelper} helper the helper to use.
  2295. * @param {Function} updateCallback a callback called on each update. Called
  2296. * with one arg :
  2297. * - the metadata linked to the update received.
  2298. * @return Promise the promise for the accumulation.
  2299. */
  2300. function accumulate(helper, updateCallback) {
  2301. return new external.Promise(function (resolve, reject){
  2302. var dataArray = [];
  2303. var chunkType = helper._internalType,
  2304. resultType = helper._outputType,
  2305. mimeType = helper._mimeType;
  2306. helper
  2307. .on('data', function (data, meta) {
  2308. dataArray.push(data);
  2309. if(updateCallback) {
  2310. updateCallback(meta);
  2311. }
  2312. })
  2313. .on('error', function(err) {
  2314. dataArray = [];
  2315. reject(err);
  2316. })
  2317. .on('end', function (){
  2318. try {
  2319. var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);
  2320. resolve(result);
  2321. } catch (e) {
  2322. reject(e);
  2323. }
  2324. dataArray = [];
  2325. })
  2326. .resume();
  2327. });
  2328. }
  2329. /**
  2330. * An helper to easily use workers outside of JSZip.
  2331. * @constructor
  2332. * @param {Worker} worker the worker to wrap
  2333. * @param {String} outputType the type of data expected by the use
  2334. * @param {String} mimeType the mime type of the content, if applicable.
  2335. */
  2336. function StreamHelper(worker, outputType, mimeType) {
  2337. var internalType = outputType;
  2338. switch(outputType) {
  2339. case "blob":
  2340. case "arraybuffer":
  2341. internalType = "uint8array";
  2342. break;
  2343. case "base64":
  2344. internalType = "string";
  2345. break;
  2346. }
  2347. try {
  2348. // the type used internally
  2349. this._internalType = internalType;
  2350. // the type used to output results
  2351. this._outputType = outputType;
  2352. // the mime type
  2353. this._mimeType = mimeType;
  2354. utils.checkSupport(internalType);
  2355. this._worker = worker.pipe(new ConvertWorker(internalType));
  2356. // the last workers can be rewired without issues but we need to
  2357. // prevent any updates on previous workers.
  2358. worker.lock();
  2359. } catch(e) {
  2360. this._worker = new GenericWorker("error");
  2361. this._worker.error(e);
  2362. }
  2363. }
  2364. StreamHelper.prototype = {
  2365. /**
  2366. * Listen a StreamHelper, accumulate its content and concatenate it into a
  2367. * complete block.
  2368. * @param {Function} updateCb the update callback.
  2369. * @return Promise the promise for the accumulation.
  2370. */
  2371. accumulate : function (updateCb) {
  2372. return accumulate(this, updateCb);
  2373. },
  2374. /**
  2375. * Add a listener on an event triggered on a stream.
  2376. * @param {String} evt the name of the event
  2377. * @param {Function} fn the listener
  2378. * @return {StreamHelper} the current helper.
  2379. */
  2380. on : function (evt, fn) {
  2381. var self = this;
  2382. if(evt === "data") {
  2383. this._worker.on(evt, function (chunk) {
  2384. fn.call(self, chunk.data, chunk.meta);
  2385. });
  2386. } else {
  2387. this._worker.on(evt, function () {
  2388. utils.delay(fn, arguments, self);
  2389. });
  2390. }
  2391. return this;
  2392. },
  2393. /**
  2394. * Resume the flow of chunks.
  2395. * @return {StreamHelper} the current helper.
  2396. */
  2397. resume : function () {
  2398. utils.delay(this._worker.resume, [], this._worker);
  2399. return this;
  2400. },
  2401. /**
  2402. * Pause the flow of chunks.
  2403. * @return {StreamHelper} the current helper.
  2404. */
  2405. pause : function () {
  2406. this._worker.pause();
  2407. return this;
  2408. },
  2409. /**
  2410. * Return a nodejs stream for this helper.
  2411. * @param {Function} updateCb the update callback.
  2412. * @return {NodejsStreamOutputAdapter} the nodejs stream.
  2413. */
  2414. toNodejsStream : function (updateCb) {
  2415. utils.checkSupport("nodestream");
  2416. if (this._outputType !== "nodebuffer") {
  2417. // an object stream containing blob/arraybuffer/uint8array/string
  2418. // is strange and I don't know if it would be useful.
  2419. // I you find this comment and have a good usecase, please open a
  2420. // bug report !
  2421. throw new Error(this._outputType + " is not supported by this method");
  2422. }
  2423. return new NodejsStreamOutputAdapter(this, {
  2424. objectMode : this._outputType !== "nodebuffer"
  2425. }, updateCb);
  2426. }
  2427. };
  2428. module.exports = StreamHelper;
  2429. },{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){
  2430. 'use strict';
  2431. exports.base64 = true;
  2432. exports.array = true;
  2433. exports.string = true;
  2434. exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  2435. exports.nodebuffer = typeof Buffer !== "undefined";
  2436. // contains true if JSZip can read/generate Uint8Array, false otherwise.
  2437. exports.uint8array = typeof Uint8Array !== "undefined";
  2438. if (typeof ArrayBuffer === "undefined") {
  2439. exports.blob = false;
  2440. }
  2441. else {
  2442. var buffer = new ArrayBuffer(0);
  2443. try {
  2444. exports.blob = new Blob([buffer], {
  2445. type: "application/zip"
  2446. }).size === 0;
  2447. }
  2448. catch (e) {
  2449. try {
  2450. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  2451. var builder = new Builder();
  2452. builder.append(buffer);
  2453. exports.blob = builder.getBlob('application/zip').size === 0;
  2454. }
  2455. catch (e) {
  2456. exports.blob = false;
  2457. }
  2458. }
  2459. }
  2460. try {
  2461. exports.nodestream = !!require('readable-stream').Readable;
  2462. } catch(e) {
  2463. exports.nodestream = false;
  2464. }
  2465. },{"readable-stream":16}],31:[function(require,module,exports){
  2466. 'use strict';
  2467. var utils = require('./utils');
  2468. var support = require('./support');
  2469. var nodejsUtils = require('./nodejsUtils');
  2470. var GenericWorker = require('./stream/GenericWorker');
  2471. /**
  2472. * The following functions come from pako, from pako/lib/utils/strings
  2473. * released under the MIT license, see pako https://github.com/nodeca/pako/
  2474. */
  2475. // Table with utf8 lengths (calculated by first byte of sequence)
  2476. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  2477. // because max possible codepoint is 0x10ffff
  2478. var _utf8len = new Array(256);
  2479. for (var i=0; i<256; i++) {
  2480. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  2481. }
  2482. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  2483. // convert string to array (typed, when possible)
  2484. var string2buf = function (str) {
  2485. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  2486. // count binary size
  2487. for (m_pos = 0; m_pos < str_len; m_pos++) {
  2488. c = str.charCodeAt(m_pos);
  2489. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2490. c2 = str.charCodeAt(m_pos+1);
  2491. if ((c2 & 0xfc00) === 0xdc00) {
  2492. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2493. m_pos++;
  2494. }
  2495. }
  2496. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  2497. }
  2498. // allocate buffer
  2499. if (support.uint8array) {
  2500. buf = new Uint8Array(buf_len);
  2501. } else {
  2502. buf = new Array(buf_len);
  2503. }
  2504. // convert
  2505. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  2506. c = str.charCodeAt(m_pos);
  2507. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  2508. c2 = str.charCodeAt(m_pos+1);
  2509. if ((c2 & 0xfc00) === 0xdc00) {
  2510. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  2511. m_pos++;
  2512. }
  2513. }
  2514. if (c < 0x80) {
  2515. /* one byte */
  2516. buf[i++] = c;
  2517. } else if (c < 0x800) {
  2518. /* two bytes */
  2519. buf[i++] = 0xC0 | (c >>> 6);
  2520. buf[i++] = 0x80 | (c & 0x3f);
  2521. } else if (c < 0x10000) {
  2522. /* three bytes */
  2523. buf[i++] = 0xE0 | (c >>> 12);
  2524. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2525. buf[i++] = 0x80 | (c & 0x3f);
  2526. } else {
  2527. /* four bytes */
  2528. buf[i++] = 0xf0 | (c >>> 18);
  2529. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  2530. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  2531. buf[i++] = 0x80 | (c & 0x3f);
  2532. }
  2533. }
  2534. return buf;
  2535. };
  2536. // Calculate max possible position in utf8 buffer,
  2537. // that will not break sequence. If that's not possible
  2538. // - (very small limits) return max size as is.
  2539. //
  2540. // buf[] - utf8 bytes array
  2541. // max - length limit (mandatory);
  2542. var utf8border = function(buf, max) {
  2543. var pos;
  2544. max = max || buf.length;
  2545. if (max > buf.length) { max = buf.length; }
  2546. // go back from last position, until start of sequence found
  2547. pos = max-1;
  2548. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  2549. // Fuckup - very small and broken sequence,
  2550. // return max, because we should return something anyway.
  2551. if (pos < 0) { return max; }
  2552. // If we came to start of buffer - that means vuffer is too small,
  2553. // return max too.
  2554. if (pos === 0) { return max; }
  2555. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  2556. };
  2557. // convert array to string
  2558. var buf2string = function (buf) {
  2559. var str, i, out, c, c_len;
  2560. var len = buf.length;
  2561. // Reserve max possible length (2 words per char)
  2562. // NB: by unknown reasons, Array is significantly faster for
  2563. // String.fromCharCode.apply than Uint16Array.
  2564. var utf16buf = new Array(len*2);
  2565. for (out=0, i=0; i<len;) {
  2566. c = buf[i++];
  2567. // quick process ascii
  2568. if (c < 0x80) { utf16buf[out++] = c; continue; }
  2569. c_len = _utf8len[c];
  2570. // skip 5 & 6 byte codes
  2571. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  2572. // apply mask on first byte
  2573. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  2574. // join the rest
  2575. while (c_len > 1 && i < len) {
  2576. c = (c << 6) | (buf[i++] & 0x3f);
  2577. c_len--;
  2578. }
  2579. // terminated by end of string?
  2580. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  2581. if (c < 0x10000) {
  2582. utf16buf[out++] = c;
  2583. } else {
  2584. c -= 0x10000;
  2585. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  2586. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  2587. }
  2588. }
  2589. // shrinkBuf(utf16buf, out)
  2590. if (utf16buf.length !== out) {
  2591. if(utf16buf.subarray) {
  2592. utf16buf = utf16buf.subarray(0, out);
  2593. } else {
  2594. utf16buf.length = out;
  2595. }
  2596. }
  2597. // return String.fromCharCode.apply(null, utf16buf);
  2598. return utils.applyFromCharCode(utf16buf);
  2599. };
  2600. // That's all for the pako functions.
  2601. /**
  2602. * Transform a javascript string into an array (typed if possible) of bytes,
  2603. * UTF-8 encoded.
  2604. * @param {String} str the string to encode
  2605. * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
  2606. */
  2607. exports.utf8encode = function utf8encode(str) {
  2608. if (support.nodebuffer) {
  2609. return nodejsUtils.newBufferFrom(str, "utf-8");
  2610. }
  2611. return string2buf(str);
  2612. };
  2613. /**
  2614. * Transform a bytes array (or a representation) representing an UTF-8 encoded
  2615. * string into a javascript string.
  2616. * @param {Array|Uint8Array|Buffer} buf the data de decode
  2617. * @return {String} the decoded string.
  2618. */
  2619. exports.utf8decode = function utf8decode(buf) {
  2620. if (support.nodebuffer) {
  2621. return utils.transformTo("nodebuffer", buf).toString("utf-8");
  2622. }
  2623. buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
  2624. return buf2string(buf);
  2625. };
  2626. /**
  2627. * A worker to decode utf8 encoded binary chunks into string chunks.
  2628. * @constructor
  2629. */
  2630. function Utf8DecodeWorker() {
  2631. GenericWorker.call(this, "utf-8 decode");
  2632. // the last bytes if a chunk didn't end with a complete codepoint.
  2633. this.leftOver = null;
  2634. }
  2635. utils.inherits(Utf8DecodeWorker, GenericWorker);
  2636. /**
  2637. * @see GenericWorker.processChunk
  2638. */
  2639. Utf8DecodeWorker.prototype.processChunk = function (chunk) {
  2640. var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data);
  2641. // 1st step, re-use what's left of the previous chunk
  2642. if (this.leftOver && this.leftOver.length) {
  2643. if(support.uint8array) {
  2644. var previousData = data;
  2645. data = new Uint8Array(previousData.length + this.leftOver.length);
  2646. data.set(this.leftOver, 0);
  2647. data.set(previousData, this.leftOver.length);
  2648. } else {
  2649. data = this.leftOver.concat(data);
  2650. }
  2651. this.leftOver = null;
  2652. }
  2653. var nextBoundary = utf8border(data);
  2654. var usableData = data;
  2655. if (nextBoundary !== data.length) {
  2656. if (support.uint8array) {
  2657. usableData = data.subarray(0, nextBoundary);
  2658. this.leftOver = data.subarray(nextBoundary, data.length);
  2659. } else {
  2660. usableData = data.slice(0, nextBoundary);
  2661. this.leftOver = data.slice(nextBoundary, data.length);
  2662. }
  2663. }
  2664. this.push({
  2665. data : exports.utf8decode(usableData),
  2666. meta : chunk.meta
  2667. });
  2668. };
  2669. /**
  2670. * @see GenericWorker.flush
  2671. */
  2672. Utf8DecodeWorker.prototype.flush = function () {
  2673. if(this.leftOver && this.leftOver.length) {
  2674. this.push({
  2675. data : exports.utf8decode(this.leftOver),
  2676. meta : {}
  2677. });
  2678. this.leftOver = null;
  2679. }
  2680. };
  2681. exports.Utf8DecodeWorker = Utf8DecodeWorker;
  2682. /**
  2683. * A worker to endcode string chunks into utf8 encoded binary chunks.
  2684. * @constructor
  2685. */
  2686. function Utf8EncodeWorker() {
  2687. GenericWorker.call(this, "utf-8 encode");
  2688. }
  2689. utils.inherits(Utf8EncodeWorker, GenericWorker);
  2690. /**
  2691. * @see GenericWorker.processChunk
  2692. */
  2693. Utf8EncodeWorker.prototype.processChunk = function (chunk) {
  2694. this.push({
  2695. data : exports.utf8encode(chunk.data),
  2696. meta : chunk.meta
  2697. });
  2698. };
  2699. exports.Utf8EncodeWorker = Utf8EncodeWorker;
  2700. },{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){
  2701. 'use strict';
  2702. var support = require('./support');
  2703. var base64 = require('./base64');
  2704. var nodejsUtils = require('./nodejsUtils');
  2705. var setImmediate = require('set-immediate-shim');
  2706. var external = require("./external");
  2707. /**
  2708. * Convert a string that pass as a "binary string": it should represent a byte
  2709. * array but may have > 255 char codes. Be sure to take only the first byte
  2710. * and returns the byte array.
  2711. * @param {String} str the string to transform.
  2712. * @return {Array|Uint8Array} the string in a binary format.
  2713. */
  2714. function string2binary(str) {
  2715. var result = null;
  2716. if (support.uint8array) {
  2717. result = new Uint8Array(str.length);
  2718. } else {
  2719. result = new Array(str.length);
  2720. }
  2721. return stringToArrayLike(str, result);
  2722. }
  2723. /**
  2724. * Create a new blob with the given content and the given type.
  2725. * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use
  2726. * an Uint8Array because the stock browser of android 4 won't accept it (it
  2727. * will be silently converted to a string, "[object Uint8Array]").
  2728. *
  2729. * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:
  2730. * when a large amount of Array is used to create the Blob, the amount of
  2731. * memory consumed is nearly 100 times the original data amount.
  2732. *
  2733. * @param {String} type the mime type of the blob.
  2734. * @return {Blob} the created blob.
  2735. */
  2736. exports.newBlob = function(part, type) {
  2737. exports.checkSupport("blob");
  2738. try {
  2739. // Blob constructor
  2740. return new Blob([part], {
  2741. type: type
  2742. });
  2743. }
  2744. catch (e) {
  2745. try {
  2746. // deprecated, browser only, old way
  2747. var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
  2748. var builder = new Builder();
  2749. builder.append(part);
  2750. return builder.getBlob(type);
  2751. }
  2752. catch (e) {
  2753. // well, fuck ?!
  2754. throw new Error("Bug : can't construct the Blob.");
  2755. }
  2756. }
  2757. };
  2758. /**
  2759. * The identity function.
  2760. * @param {Object} input the input.
  2761. * @return {Object} the same input.
  2762. */
  2763. function identity(input) {
  2764. return input;
  2765. }
  2766. /**
  2767. * Fill in an array with a string.
  2768. * @param {String} str the string to use.
  2769. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
  2770. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
  2771. */
  2772. function stringToArrayLike(str, array) {
  2773. for (var i = 0; i < str.length; ++i) {
  2774. array[i] = str.charCodeAt(i) & 0xFF;
  2775. }
  2776. return array;
  2777. }
  2778. /**
  2779. * An helper for the function arrayLikeToString.
  2780. * This contains static information and functions that
  2781. * can be optimized by the browser JIT compiler.
  2782. */
  2783. var arrayToStringHelper = {
  2784. /**
  2785. * Transform an array of int into a string, chunk by chunk.
  2786. * See the performances notes on arrayLikeToString.
  2787. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  2788. * @param {String} type the type of the array.
  2789. * @param {Integer} chunk the chunk size.
  2790. * @return {String} the resulting string.
  2791. * @throws Error if the chunk is too big for the stack.
  2792. */
  2793. stringifyByChunk: function(array, type, chunk) {
  2794. var result = [], k = 0, len = array.length;
  2795. // shortcut
  2796. if (len <= chunk) {
  2797. return String.fromCharCode.apply(null, array);
  2798. }
  2799. while (k < len) {
  2800. if (type === "array" || type === "nodebuffer") {
  2801. result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
  2802. }
  2803. else {
  2804. result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
  2805. }
  2806. k += chunk;
  2807. }
  2808. return result.join("");
  2809. },
  2810. /**
  2811. * Call String.fromCharCode on every item in the array.
  2812. * This is the naive implementation, which generate A LOT of intermediate string.
  2813. * This should be used when everything else fail.
  2814. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  2815. * @return {String} the result.
  2816. */
  2817. stringifyByChar: function(array){
  2818. var resultStr = "";
  2819. for(var i = 0; i < array.length; i++) {
  2820. resultStr += String.fromCharCode(array[i]);
  2821. }
  2822. return resultStr;
  2823. },
  2824. applyCanBeUsed : {
  2825. /**
  2826. * true if the browser accepts to use String.fromCharCode on Uint8Array
  2827. */
  2828. uint8array : (function () {
  2829. try {
  2830. return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
  2831. } catch (e) {
  2832. return false;
  2833. }
  2834. })(),
  2835. /**
  2836. * true if the browser accepts to use String.fromCharCode on nodejs Buffer.
  2837. */
  2838. nodebuffer : (function () {
  2839. try {
  2840. return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
  2841. } catch (e) {
  2842. return false;
  2843. }
  2844. })()
  2845. }
  2846. };
  2847. /**
  2848. * Transform an array-like object to a string.
  2849. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
  2850. * @return {String} the result.
  2851. */
  2852. function arrayLikeToString(array) {
  2853. // Performances notes :
  2854. // --------------------
  2855. // String.fromCharCode.apply(null, array) is the fastest, see
  2856. // see http://jsperf.com/converting-a-uint8array-to-a-string/2
  2857. // but the stack is limited (and we can get huge arrays !).
  2858. //
  2859. // result += String.fromCharCode(array[i]); generate too many strings !
  2860. //
  2861. // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
  2862. // TODO : we now have workers that split the work. Do we still need that ?
  2863. var chunk = 65536,
  2864. type = exports.getTypeOf(array),
  2865. canUseApply = true;
  2866. if (type === "uint8array") {
  2867. canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
  2868. } else if (type === "nodebuffer") {
  2869. canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
  2870. }
  2871. if (canUseApply) {
  2872. while (chunk > 1) {
  2873. try {
  2874. return arrayToStringHelper.stringifyByChunk(array, type, chunk);
  2875. } catch (e) {
  2876. chunk = Math.floor(chunk / 2);
  2877. }
  2878. }
  2879. }
  2880. // no apply or chunk error : slow and painful algorithm
  2881. // default browser on android 4.*
  2882. return arrayToStringHelper.stringifyByChar(array);
  2883. }
  2884. exports.applyFromCharCode = arrayLikeToString;
  2885. /**
  2886. * Copy the data from an array-like to an other array-like.
  2887. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
  2888. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
  2889. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
  2890. */
  2891. function arrayLikeToArrayLike(arrayFrom, arrayTo) {
  2892. for (var i = 0; i < arrayFrom.length; i++) {
  2893. arrayTo[i] = arrayFrom[i];
  2894. }
  2895. return arrayTo;
  2896. }
  2897. // a matrix containing functions to transform everything into everything.
  2898. var transform = {};
  2899. // string to ?
  2900. transform["string"] = {
  2901. "string": identity,
  2902. "array": function(input) {
  2903. return stringToArrayLike(input, new Array(input.length));
  2904. },
  2905. "arraybuffer": function(input) {
  2906. return transform["string"]["uint8array"](input).buffer;
  2907. },
  2908. "uint8array": function(input) {
  2909. return stringToArrayLike(input, new Uint8Array(input.length));
  2910. },
  2911. "nodebuffer": function(input) {
  2912. return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
  2913. }
  2914. };
  2915. // array to ?
  2916. transform["array"] = {
  2917. "string": arrayLikeToString,
  2918. "array": identity,
  2919. "arraybuffer": function(input) {
  2920. return (new Uint8Array(input)).buffer;
  2921. },
  2922. "uint8array": function(input) {
  2923. return new Uint8Array(input);
  2924. },
  2925. "nodebuffer": function(input) {
  2926. return nodejsUtils.newBufferFrom(input);
  2927. }
  2928. };
  2929. // arraybuffer to ?
  2930. transform["arraybuffer"] = {
  2931. "string": function(input) {
  2932. return arrayLikeToString(new Uint8Array(input));
  2933. },
  2934. "array": function(input) {
  2935. return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
  2936. },
  2937. "arraybuffer": identity,
  2938. "uint8array": function(input) {
  2939. return new Uint8Array(input);
  2940. },
  2941. "nodebuffer": function(input) {
  2942. return nodejsUtils.newBufferFrom(new Uint8Array(input));
  2943. }
  2944. };
  2945. // uint8array to ?
  2946. transform["uint8array"] = {
  2947. "string": arrayLikeToString,
  2948. "array": function(input) {
  2949. return arrayLikeToArrayLike(input, new Array(input.length));
  2950. },
  2951. "arraybuffer": function(input) {
  2952. return input.buffer;
  2953. },
  2954. "uint8array": identity,
  2955. "nodebuffer": function(input) {
  2956. return nodejsUtils.newBufferFrom(input);
  2957. }
  2958. };
  2959. // nodebuffer to ?
  2960. transform["nodebuffer"] = {
  2961. "string": arrayLikeToString,
  2962. "array": function(input) {
  2963. return arrayLikeToArrayLike(input, new Array(input.length));
  2964. },
  2965. "arraybuffer": function(input) {
  2966. return transform["nodebuffer"]["uint8array"](input).buffer;
  2967. },
  2968. "uint8array": function(input) {
  2969. return arrayLikeToArrayLike(input, new Uint8Array(input.length));
  2970. },
  2971. "nodebuffer": identity
  2972. };
  2973. /**
  2974. * Transform an input into any type.
  2975. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
  2976. * If no output type is specified, the unmodified input will be returned.
  2977. * @param {String} outputType the output type.
  2978. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
  2979. * @throws {Error} an Error if the browser doesn't support the requested output type.
  2980. */
  2981. exports.transformTo = function(outputType, input) {
  2982. if (!input) {
  2983. // undefined, null, etc
  2984. // an empty string won't harm.
  2985. input = "";
  2986. }
  2987. if (!outputType) {
  2988. return input;
  2989. }
  2990. exports.checkSupport(outputType);
  2991. var inputType = exports.getTypeOf(input);
  2992. var result = transform[inputType][outputType](input);
  2993. return result;
  2994. };
  2995. /**
  2996. * Return the type of the input.
  2997. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
  2998. * @param {Object} input the input to identify.
  2999. * @return {String} the (lowercase) type of the input.
  3000. */
  3001. exports.getTypeOf = function(input) {
  3002. if (typeof input === "string") {
  3003. return "string";
  3004. }
  3005. if (Object.prototype.toString.call(input) === "[object Array]") {
  3006. return "array";
  3007. }
  3008. if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
  3009. return "nodebuffer";
  3010. }
  3011. if (support.uint8array && input instanceof Uint8Array) {
  3012. return "uint8array";
  3013. }
  3014. if (support.arraybuffer && input instanceof ArrayBuffer) {
  3015. return "arraybuffer";
  3016. }
  3017. };
  3018. /**
  3019. * Throw an exception if the type is not supported.
  3020. * @param {String} type the type to check.
  3021. * @throws {Error} an Error if the browser doesn't support the requested type.
  3022. */
  3023. exports.checkSupport = function(type) {
  3024. var supported = support[type.toLowerCase()];
  3025. if (!supported) {
  3026. throw new Error(type + " is not supported by this platform");
  3027. }
  3028. };
  3029. exports.MAX_VALUE_16BITS = 65535;
  3030. exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
  3031. /**
  3032. * Prettify a string read as binary.
  3033. * @param {string} str the string to prettify.
  3034. * @return {string} a pretty string.
  3035. */
  3036. exports.pretty = function(str) {
  3037. var res = '',
  3038. code, i;
  3039. for (i = 0; i < (str || "").length; i++) {
  3040. code = str.charCodeAt(i);
  3041. res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
  3042. }
  3043. return res;
  3044. };
  3045. /**
  3046. * Defer the call of a function.
  3047. * @param {Function} callback the function to call asynchronously.
  3048. * @param {Array} args the arguments to give to the callback.
  3049. */
  3050. exports.delay = function(callback, args, self) {
  3051. setImmediate(function () {
  3052. callback.apply(self || null, args || []);
  3053. });
  3054. };
  3055. /**
  3056. * Extends a prototype with an other, without calling a constructor with
  3057. * side effects. Inspired by nodejs' `utils.inherits`
  3058. * @param {Function} ctor the constructor to augment
  3059. * @param {Function} superCtor the parent constructor to use
  3060. */
  3061. exports.inherits = function (ctor, superCtor) {
  3062. var Obj = function() {};
  3063. Obj.prototype = superCtor.prototype;
  3064. ctor.prototype = new Obj();
  3065. };
  3066. /**
  3067. * Merge the objects passed as parameters into a new one.
  3068. * @private
  3069. * @param {...Object} var_args All objects to merge.
  3070. * @return {Object} a new object with the data of the others.
  3071. */
  3072. exports.extend = function() {
  3073. var result = {}, i, attr;
  3074. for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
  3075. for (attr in arguments[i]) {
  3076. if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
  3077. result[attr] = arguments[i][attr];
  3078. }
  3079. }
  3080. }
  3081. return result;
  3082. };
  3083. /**
  3084. * Transform arbitrary content into a Promise.
  3085. * @param {String} name a name for the content being processed.
  3086. * @param {Object} inputData the content to process.
  3087. * @param {Boolean} isBinary true if the content is not an unicode string
  3088. * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
  3089. * @param {Boolean} isBase64 true if the string content is encoded with base64.
  3090. * @return {Promise} a promise in a format usable by JSZip.
  3091. */
  3092. exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
  3093. // if inputData is already a promise, this flatten it.
  3094. var promise = external.Promise.resolve(inputData).then(function(data) {
  3095. var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
  3096. if (isBlob && typeof FileReader !== "undefined") {
  3097. return new external.Promise(function (resolve, reject) {
  3098. var reader = new FileReader();
  3099. reader.onload = function(e) {
  3100. resolve(e.target.result);
  3101. };
  3102. reader.onerror = function(e) {
  3103. reject(e.target.error);
  3104. };
  3105. reader.readAsArrayBuffer(data);
  3106. });
  3107. } else {
  3108. return data;
  3109. }
  3110. });
  3111. return promise.then(function(data) {
  3112. var dataType = exports.getTypeOf(data);
  3113. if (!dataType) {
  3114. return external.Promise.reject(
  3115. new Error("Can't read the data of '" + name + "'. Is it " +
  3116. "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")
  3117. );
  3118. }
  3119. // special case : it's way easier to work with Uint8Array than with ArrayBuffer
  3120. if (dataType === "arraybuffer") {
  3121. data = exports.transformTo("uint8array", data);
  3122. } else if (dataType === "string") {
  3123. if (isBase64) {
  3124. data = base64.decode(data);
  3125. }
  3126. else if (isBinary) {
  3127. // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
  3128. if (isOptimizedBinaryString !== true) {
  3129. // this is a string, not in a base64 format.
  3130. // Be sure that this is a correct "binary string"
  3131. data = string2binary(data);
  3132. }
  3133. }
  3134. }
  3135. return data;
  3136. });
  3137. };
  3138. },{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"set-immediate-shim":54}],33:[function(require,module,exports){
  3139. 'use strict';
  3140. var readerFor = require('./reader/readerFor');
  3141. var utils = require('./utils');
  3142. var sig = require('./signature');
  3143. var ZipEntry = require('./zipEntry');
  3144. var utf8 = require('./utf8');
  3145. var support = require('./support');
  3146. // class ZipEntries {{{
  3147. /**
  3148. * All the entries in the zip file.
  3149. * @constructor
  3150. * @param {Object} loadOptions Options for loading the stream.
  3151. */
  3152. function ZipEntries(loadOptions) {
  3153. this.files = [];
  3154. this.loadOptions = loadOptions;
  3155. }
  3156. ZipEntries.prototype = {
  3157. /**
  3158. * Check that the reader is on the specified signature.
  3159. * @param {string} expectedSignature the expected signature.
  3160. * @throws {Error} if it is an other signature.
  3161. */
  3162. checkSignature: function(expectedSignature) {
  3163. if (!this.reader.readAndCheckSignature(expectedSignature)) {
  3164. this.reader.index -= 4;
  3165. var signature = this.reader.readString(4);
  3166. throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
  3167. }
  3168. },
  3169. /**
  3170. * Check if the given signature is at the given index.
  3171. * @param {number} askedIndex the index to check.
  3172. * @param {string} expectedSignature the signature to expect.
  3173. * @return {boolean} true if the signature is here, false otherwise.
  3174. */
  3175. isSignature: function(askedIndex, expectedSignature) {
  3176. var currentIndex = this.reader.index;
  3177. this.reader.setIndex(askedIndex);
  3178. var signature = this.reader.readString(4);
  3179. var result = signature === expectedSignature;
  3180. this.reader.setIndex(currentIndex);
  3181. return result;
  3182. },
  3183. /**
  3184. * Read the end of the central directory.
  3185. */
  3186. readBlockEndOfCentral: function() {
  3187. this.diskNumber = this.reader.readInt(2);
  3188. this.diskWithCentralDirStart = this.reader.readInt(2);
  3189. this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
  3190. this.centralDirRecords = this.reader.readInt(2);
  3191. this.centralDirSize = this.reader.readInt(4);
  3192. this.centralDirOffset = this.reader.readInt(4);
  3193. this.zipCommentLength = this.reader.readInt(2);
  3194. // warning : the encoding depends of the system locale
  3195. // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
  3196. // On a windows machine, this field is encoded with the localized windows code page.
  3197. var zipComment = this.reader.readData(this.zipCommentLength);
  3198. var decodeParamType = support.uint8array ? "uint8array" : "array";
  3199. // To get consistent behavior with the generation part, we will assume that
  3200. // this is utf8 encoded unless specified otherwise.
  3201. var decodeContent = utils.transformTo(decodeParamType, zipComment);
  3202. this.zipComment = this.loadOptions.decodeFileName(decodeContent);
  3203. },
  3204. /**
  3205. * Read the end of the Zip 64 central directory.
  3206. * Not merged with the method readEndOfCentral :
  3207. * The end of central can coexist with its Zip64 brother,
  3208. * I don't want to read the wrong number of bytes !
  3209. */
  3210. readBlockZip64EndOfCentral: function() {
  3211. this.zip64EndOfCentralSize = this.reader.readInt(8);
  3212. this.reader.skip(4);
  3213. // this.versionMadeBy = this.reader.readString(2);
  3214. // this.versionNeeded = this.reader.readInt(2);
  3215. this.diskNumber = this.reader.readInt(4);
  3216. this.diskWithCentralDirStart = this.reader.readInt(4);
  3217. this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
  3218. this.centralDirRecords = this.reader.readInt(8);
  3219. this.centralDirSize = this.reader.readInt(8);
  3220. this.centralDirOffset = this.reader.readInt(8);
  3221. this.zip64ExtensibleData = {};
  3222. var extraDataSize = this.zip64EndOfCentralSize - 44,
  3223. index = 0,
  3224. extraFieldId,
  3225. extraFieldLength,
  3226. extraFieldValue;
  3227. while (index < extraDataSize) {
  3228. extraFieldId = this.reader.readInt(2);
  3229. extraFieldLength = this.reader.readInt(4);
  3230. extraFieldValue = this.reader.readData(extraFieldLength);
  3231. this.zip64ExtensibleData[extraFieldId] = {
  3232. id: extraFieldId,
  3233. length: extraFieldLength,
  3234. value: extraFieldValue
  3235. };
  3236. }
  3237. },
  3238. /**
  3239. * Read the end of the Zip 64 central directory locator.
  3240. */
  3241. readBlockZip64EndOfCentralLocator: function() {
  3242. this.diskWithZip64CentralDirStart = this.reader.readInt(4);
  3243. this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
  3244. this.disksCount = this.reader.readInt(4);
  3245. if (this.disksCount > 1) {
  3246. throw new Error("Multi-volumes zip are not supported");
  3247. }
  3248. },
  3249. /**
  3250. * Read the local files, based on the offset read in the central part.
  3251. */
  3252. readLocalFiles: function() {
  3253. var i, file;
  3254. for (i = 0; i < this.files.length; i++) {
  3255. file = this.files[i];
  3256. this.reader.setIndex(file.localHeaderOffset);
  3257. this.checkSignature(sig.LOCAL_FILE_HEADER);
  3258. file.readLocalPart(this.reader);
  3259. file.handleUTF8();
  3260. file.processAttributes();
  3261. }
  3262. },
  3263. /**
  3264. * Read the central directory.
  3265. */
  3266. readCentralDir: function() {
  3267. var file;
  3268. this.reader.setIndex(this.centralDirOffset);
  3269. while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {
  3270. file = new ZipEntry({
  3271. zip64: this.zip64
  3272. }, this.loadOptions);
  3273. file.readCentralPart(this.reader);
  3274. this.files.push(file);
  3275. }
  3276. if (this.centralDirRecords !== this.files.length) {
  3277. if (this.centralDirRecords !== 0 && this.files.length === 0) {
  3278. // We expected some records but couldn't find ANY.
  3279. // This is really suspicious, as if something went wrong.
  3280. throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length);
  3281. } else {
  3282. // We found some records but not all.
  3283. // Something is wrong but we got something for the user: no error here.
  3284. // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length);
  3285. }
  3286. }
  3287. },
  3288. /**
  3289. * Read the end of central directory.
  3290. */
  3291. readEndOfCentral: function() {
  3292. var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
  3293. if (offset < 0) {
  3294. // Check if the content is a truncated zip or complete garbage.
  3295. // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
  3296. // extractible zip for example) but it can give a good hint.
  3297. // If an ajax request was used without responseType, we will also
  3298. // get unreadable data.
  3299. var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);
  3300. if (isGarbage) {
  3301. throw new Error("Can't find end of central directory : is this a zip file ? " +
  3302. "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");
  3303. } else {
  3304. throw new Error("Corrupted zip: can't find end of central directory");
  3305. }
  3306. }
  3307. this.reader.setIndex(offset);
  3308. var endOfCentralDirOffset = offset;
  3309. this.checkSignature(sig.CENTRAL_DIRECTORY_END);
  3310. this.readBlockEndOfCentral();
  3311. /* extract from the zip spec :
  3312. 4) If one of the fields in the end of central directory
  3313. record is too small to hold required data, the field
  3314. should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
  3315. ZIP64 format record should be created.
  3316. 5) The end of central directory record and the
  3317. Zip64 end of central directory locator record must
  3318. reside on the same disk when splitting or spanning
  3319. an archive.
  3320. */
  3321. if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {
  3322. this.zip64 = true;
  3323. /*
  3324. Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
  3325. the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents
  3326. all numbers as 64-bit double precision IEEE 754 floating point numbers.
  3327. So, we have 53bits for integers and bitwise operations treat everything as 32bits.
  3328. see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
  3329. and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
  3330. */
  3331. // should look for a zip64 EOCD locator
  3332. offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3333. if (offset < 0) {
  3334. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");
  3335. }
  3336. this.reader.setIndex(offset);
  3337. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
  3338. this.readBlockZip64EndOfCentralLocator();
  3339. // now the zip64 EOCD record
  3340. if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {
  3341. // console.warn("ZIP64 end of central directory not where expected.");
  3342. this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3343. if (this.relativeOffsetEndOfZip64CentralDir < 0) {
  3344. throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");
  3345. }
  3346. }
  3347. this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
  3348. this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
  3349. this.readBlockZip64EndOfCentral();
  3350. }
  3351. var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;
  3352. if (this.zip64) {
  3353. expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator
  3354. expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;
  3355. }
  3356. var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;
  3357. if (extraBytes > 0) {
  3358. // console.warn(extraBytes, "extra bytes at beginning or within zipfile");
  3359. if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {
  3360. // The offsets seem wrong, but we have something at the specified offset.
  3361. // So… we keep it.
  3362. } else {
  3363. // the offset is wrong, update the "zero" of the reader
  3364. // this happens if data has been prepended (crx files for example)
  3365. this.reader.zero = extraBytes;
  3366. }
  3367. } else if (extraBytes < 0) {
  3368. throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes.");
  3369. }
  3370. },
  3371. prepareReader: function(data) {
  3372. this.reader = readerFor(data);
  3373. },
  3374. /**
  3375. * Read a zip file and create ZipEntries.
  3376. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
  3377. */
  3378. load: function(data) {
  3379. this.prepareReader(data);
  3380. this.readEndOfCentral();
  3381. this.readCentralDir();
  3382. this.readLocalFiles();
  3383. }
  3384. };
  3385. // }}} end of ZipEntries
  3386. module.exports = ZipEntries;
  3387. },{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){
  3388. 'use strict';
  3389. var readerFor = require('./reader/readerFor');
  3390. var utils = require('./utils');
  3391. var CompressedObject = require('./compressedObject');
  3392. var crc32fn = require('./crc32');
  3393. var utf8 = require('./utf8');
  3394. var compressions = require('./compressions');
  3395. var support = require('./support');
  3396. var MADE_BY_DOS = 0x00;
  3397. var MADE_BY_UNIX = 0x03;
  3398. /**
  3399. * Find a compression registered in JSZip.
  3400. * @param {string} compressionMethod the method magic to find.
  3401. * @return {Object|null} the JSZip compression object, null if none found.
  3402. */
  3403. var findCompression = function(compressionMethod) {
  3404. for (var method in compressions) {
  3405. if (!compressions.hasOwnProperty(method)) {
  3406. continue;
  3407. }
  3408. if (compressions[method].magic === compressionMethod) {
  3409. return compressions[method];
  3410. }
  3411. }
  3412. return null;
  3413. };
  3414. // class ZipEntry {{{
  3415. /**
  3416. * An entry in the zip file.
  3417. * @constructor
  3418. * @param {Object} options Options of the current file.
  3419. * @param {Object} loadOptions Options for loading the stream.
  3420. */
  3421. function ZipEntry(options, loadOptions) {
  3422. this.options = options;
  3423. this.loadOptions = loadOptions;
  3424. }
  3425. ZipEntry.prototype = {
  3426. /**
  3427. * say if the file is encrypted.
  3428. * @return {boolean} true if the file is encrypted, false otherwise.
  3429. */
  3430. isEncrypted: function() {
  3431. // bit 1 is set
  3432. return (this.bitFlag & 0x0001) === 0x0001;
  3433. },
  3434. /**
  3435. * say if the file has utf-8 filename/comment.
  3436. * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
  3437. */
  3438. useUTF8: function() {
  3439. // bit 11 is set
  3440. return (this.bitFlag & 0x0800) === 0x0800;
  3441. },
  3442. /**
  3443. * Read the local part of a zip file and add the info in this object.
  3444. * @param {DataReader} reader the reader to use.
  3445. */
  3446. readLocalPart: function(reader) {
  3447. var compression, localExtraFieldsLength;
  3448. // we already know everything from the central dir !
  3449. // If the central dir data are false, we are doomed.
  3450. // On the bright side, the local part is scary : zip64, data descriptors, both, etc.
  3451. // The less data we get here, the more reliable this should be.
  3452. // Let's skip the whole header and dash to the data !
  3453. reader.skip(22);
  3454. // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
  3455. // Strangely, the filename here is OK.
  3456. // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
  3457. // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
  3458. // Search "unzip mismatching "local" filename continuing with "central" filename version" on
  3459. // the internet.
  3460. //
  3461. // I think I see the logic here : the central directory is used to display
  3462. // content and the local directory is used to extract the files. Mixing / and \
  3463. // may be used to display \ to windows users and use / when extracting the files.
  3464. // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
  3465. this.fileNameLength = reader.readInt(2);
  3466. localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
  3467. // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.
  3468. this.fileName = reader.readData(this.fileNameLength);
  3469. reader.skip(localExtraFieldsLength);
  3470. if (this.compressedSize === -1 || this.uncompressedSize === -1) {
  3471. throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)");
  3472. }
  3473. compression = findCompression(this.compressionMethod);
  3474. if (compression === null) { // no compression found
  3475. throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")");
  3476. }
  3477. this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));
  3478. },
  3479. /**
  3480. * Read the central part of a zip file and add the info in this object.
  3481. * @param {DataReader} reader the reader to use.
  3482. */
  3483. readCentralPart: function(reader) {
  3484. this.versionMadeBy = reader.readInt(2);
  3485. reader.skip(2);
  3486. // this.versionNeeded = reader.readInt(2);
  3487. this.bitFlag = reader.readInt(2);
  3488. this.compressionMethod = reader.readString(2);
  3489. this.date = reader.readDate();
  3490. this.crc32 = reader.readInt(4);
  3491. this.compressedSize = reader.readInt(4);
  3492. this.uncompressedSize = reader.readInt(4);
  3493. var fileNameLength = reader.readInt(2);
  3494. this.extraFieldsLength = reader.readInt(2);
  3495. this.fileCommentLength = reader.readInt(2);
  3496. this.diskNumberStart = reader.readInt(2);
  3497. this.internalFileAttributes = reader.readInt(2);
  3498. this.externalFileAttributes = reader.readInt(4);
  3499. this.localHeaderOffset = reader.readInt(4);
  3500. if (this.isEncrypted()) {
  3501. throw new Error("Encrypted zip are not supported");
  3502. }
  3503. // will be read in the local part, see the comments there
  3504. reader.skip(fileNameLength);
  3505. this.readExtraFields(reader);
  3506. this.parseZIP64ExtraField(reader);
  3507. this.fileComment = reader.readData(this.fileCommentLength);
  3508. },
  3509. /**
  3510. * Parse the external file attributes and get the unix/dos permissions.
  3511. */
  3512. processAttributes: function () {
  3513. this.unixPermissions = null;
  3514. this.dosPermissions = null;
  3515. var madeBy = this.versionMadeBy >> 8;
  3516. // Check if we have the DOS directory flag set.
  3517. // We look for it in the DOS and UNIX permissions
  3518. // but some unknown platform could set it as a compatibility flag.
  3519. this.dir = this.externalFileAttributes & 0x0010 ? true : false;
  3520. if(madeBy === MADE_BY_DOS) {
  3521. // first 6 bits (0 to 5)
  3522. this.dosPermissions = this.externalFileAttributes & 0x3F;
  3523. }
  3524. if(madeBy === MADE_BY_UNIX) {
  3525. this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
  3526. // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
  3527. }
  3528. // fail safe : if the name ends with a / it probably means a folder
  3529. if (!this.dir && this.fileNameStr.slice(-1) === '/') {
  3530. this.dir = true;
  3531. }
  3532. },
  3533. /**
  3534. * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
  3535. * @param {DataReader} reader the reader to use.
  3536. */
  3537. parseZIP64ExtraField: function(reader) {
  3538. if (!this.extraFields[0x0001]) {
  3539. return;
  3540. }
  3541. // should be something, preparing the extra reader
  3542. var extraReader = readerFor(this.extraFields[0x0001].value);
  3543. // I really hope that these 64bits integer can fit in 32 bits integer, because js
  3544. // won't let us have more.
  3545. if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
  3546. this.uncompressedSize = extraReader.readInt(8);
  3547. }
  3548. if (this.compressedSize === utils.MAX_VALUE_32BITS) {
  3549. this.compressedSize = extraReader.readInt(8);
  3550. }
  3551. if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
  3552. this.localHeaderOffset = extraReader.readInt(8);
  3553. }
  3554. if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
  3555. this.diskNumberStart = extraReader.readInt(4);
  3556. }
  3557. },
  3558. /**
  3559. * Read the central part of a zip file and add the info in this object.
  3560. * @param {DataReader} reader the reader to use.
  3561. */
  3562. readExtraFields: function(reader) {
  3563. var end = reader.index + this.extraFieldsLength,
  3564. extraFieldId,
  3565. extraFieldLength,
  3566. extraFieldValue;
  3567. if (!this.extraFields) {
  3568. this.extraFields = {};
  3569. }
  3570. while (reader.index + 4 < end) {
  3571. extraFieldId = reader.readInt(2);
  3572. extraFieldLength = reader.readInt(2);
  3573. extraFieldValue = reader.readData(extraFieldLength);
  3574. this.extraFields[extraFieldId] = {
  3575. id: extraFieldId,
  3576. length: extraFieldLength,
  3577. value: extraFieldValue
  3578. };
  3579. }
  3580. reader.setIndex(end);
  3581. },
  3582. /**
  3583. * Apply an UTF8 transformation if needed.
  3584. */
  3585. handleUTF8: function() {
  3586. var decodeParamType = support.uint8array ? "uint8array" : "array";
  3587. if (this.useUTF8()) {
  3588. this.fileNameStr = utf8.utf8decode(this.fileName);
  3589. this.fileCommentStr = utf8.utf8decode(this.fileComment);
  3590. } else {
  3591. var upath = this.findExtraFieldUnicodePath();
  3592. if (upath !== null) {
  3593. this.fileNameStr = upath;
  3594. } else {
  3595. // ASCII text or unsupported code page
  3596. var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);
  3597. this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);
  3598. }
  3599. var ucomment = this.findExtraFieldUnicodeComment();
  3600. if (ucomment !== null) {
  3601. this.fileCommentStr = ucomment;
  3602. } else {
  3603. // ASCII text or unsupported code page
  3604. var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);
  3605. this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);
  3606. }
  3607. }
  3608. },
  3609. /**
  3610. * Find the unicode path declared in the extra field, if any.
  3611. * @return {String} the unicode path, null otherwise.
  3612. */
  3613. findExtraFieldUnicodePath: function() {
  3614. var upathField = this.extraFields[0x7075];
  3615. if (upathField) {
  3616. var extraReader = readerFor(upathField.value);
  3617. // wrong version
  3618. if (extraReader.readInt(1) !== 1) {
  3619. return null;
  3620. }
  3621. // the crc of the filename changed, this field is out of date.
  3622. if (crc32fn(this.fileName) !== extraReader.readInt(4)) {
  3623. return null;
  3624. }
  3625. return utf8.utf8decode(extraReader.readData(upathField.length - 5));
  3626. }
  3627. return null;
  3628. },
  3629. /**
  3630. * Find the unicode comment declared in the extra field, if any.
  3631. * @return {String} the unicode comment, null otherwise.
  3632. */
  3633. findExtraFieldUnicodeComment: function() {
  3634. var ucommentField = this.extraFields[0x6375];
  3635. if (ucommentField) {
  3636. var extraReader = readerFor(ucommentField.value);
  3637. // wrong version
  3638. if (extraReader.readInt(1) !== 1) {
  3639. return null;
  3640. }
  3641. // the crc of the comment changed, this field is out of date.
  3642. if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {
  3643. return null;
  3644. }
  3645. return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));
  3646. }
  3647. return null;
  3648. }
  3649. };
  3650. module.exports = ZipEntry;
  3651. },{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){
  3652. 'use strict';
  3653. var StreamHelper = require('./stream/StreamHelper');
  3654. var DataWorker = require('./stream/DataWorker');
  3655. var utf8 = require('./utf8');
  3656. var CompressedObject = require('./compressedObject');
  3657. var GenericWorker = require('./stream/GenericWorker');
  3658. /**
  3659. * A simple object representing a file in the zip file.
  3660. * @constructor
  3661. * @param {string} name the name of the file
  3662. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
  3663. * @param {Object} options the options of the file
  3664. */
  3665. var ZipObject = function(name, data, options) {
  3666. this.name = name;
  3667. this.dir = options.dir;
  3668. this.date = options.date;
  3669. this.comment = options.comment;
  3670. this.unixPermissions = options.unixPermissions;
  3671. this.dosPermissions = options.dosPermissions;
  3672. this._data = data;
  3673. this._dataBinary = options.binary;
  3674. // keep only the compression
  3675. this.options = {
  3676. compression : options.compression,
  3677. compressionOptions : options.compressionOptions
  3678. };
  3679. };
  3680. ZipObject.prototype = {
  3681. /**
  3682. * Create an internal stream for the content of this object.
  3683. * @param {String} type the type of each chunk.
  3684. * @return StreamHelper the stream.
  3685. */
  3686. internalStream: function (type) {
  3687. var result = null, outputType = "string";
  3688. try {
  3689. if (!type) {
  3690. throw new Error("No output type specified.");
  3691. }
  3692. outputType = type.toLowerCase();
  3693. var askUnicodeString = outputType === "string" || outputType === "text";
  3694. if (outputType === "binarystring" || outputType === "text") {
  3695. outputType = "string";
  3696. }
  3697. result = this._decompressWorker();
  3698. var isUnicodeString = !this._dataBinary;
  3699. if (isUnicodeString && !askUnicodeString) {
  3700. result = result.pipe(new utf8.Utf8EncodeWorker());
  3701. }
  3702. if (!isUnicodeString && askUnicodeString) {
  3703. result = result.pipe(new utf8.Utf8DecodeWorker());
  3704. }
  3705. } catch (e) {
  3706. result = new GenericWorker("error");
  3707. result.error(e);
  3708. }
  3709. return new StreamHelper(result, outputType, "");
  3710. },
  3711. /**
  3712. * Prepare the content in the asked type.
  3713. * @param {String} type the type of the result.
  3714. * @param {Function} onUpdate a function to call on each internal update.
  3715. * @return Promise the promise of the result.
  3716. */
  3717. async: function (type, onUpdate) {
  3718. return this.internalStream(type).accumulate(onUpdate);
  3719. },
  3720. /**
  3721. * Prepare the content as a nodejs stream.
  3722. * @param {String} type the type of each chunk.
  3723. * @param {Function} onUpdate a function to call on each internal update.
  3724. * @return Stream the stream.
  3725. */
  3726. nodeStream: function (type, onUpdate) {
  3727. return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate);
  3728. },
  3729. /**
  3730. * Return a worker for the compressed content.
  3731. * @private
  3732. * @param {Object} compression the compression object to use.
  3733. * @param {Object} compressionOptions the options to use when compressing.
  3734. * @return Worker the worker.
  3735. */
  3736. _compressWorker: function (compression, compressionOptions) {
  3737. if (
  3738. this._data instanceof CompressedObject &&
  3739. this._data.compression.magic === compression.magic
  3740. ) {
  3741. return this._data.getCompressedWorker();
  3742. } else {
  3743. var result = this._decompressWorker();
  3744. if(!this._dataBinary) {
  3745. result = result.pipe(new utf8.Utf8EncodeWorker());
  3746. }
  3747. return CompressedObject.createWorkerFrom(result, compression, compressionOptions);
  3748. }
  3749. },
  3750. /**
  3751. * Return a worker for the decompressed content.
  3752. * @private
  3753. * @return Worker the worker.
  3754. */
  3755. _decompressWorker : function () {
  3756. if (this._data instanceof CompressedObject) {
  3757. return this._data.getContentWorker();
  3758. } else if (this._data instanceof GenericWorker) {
  3759. return this._data;
  3760. } else {
  3761. return new DataWorker(this._data);
  3762. }
  3763. }
  3764. };
  3765. var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"];
  3766. var removedFn = function () {
  3767. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  3768. };
  3769. for(var i = 0; i < removedMethods.length; i++) {
  3770. ZipObject.prototype[removedMethods[i]] = removedFn;
  3771. }
  3772. module.exports = ZipObject;
  3773. },{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){
  3774. (function (global){
  3775. 'use strict';
  3776. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  3777. var scheduleDrain;
  3778. {
  3779. if (Mutation) {
  3780. var called = 0;
  3781. var observer = new Mutation(nextTick);
  3782. var element = global.document.createTextNode('');
  3783. observer.observe(element, {
  3784. characterData: true
  3785. });
  3786. scheduleDrain = function () {
  3787. element.data = (called = ++called % 2);
  3788. };
  3789. } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  3790. var channel = new global.MessageChannel();
  3791. channel.port1.onmessage = nextTick;
  3792. scheduleDrain = function () {
  3793. channel.port2.postMessage(0);
  3794. };
  3795. } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  3796. scheduleDrain = function () {
  3797. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  3798. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  3799. var scriptEl = global.document.createElement('script');
  3800. scriptEl.onreadystatechange = function () {
  3801. nextTick();
  3802. scriptEl.onreadystatechange = null;
  3803. scriptEl.parentNode.removeChild(scriptEl);
  3804. scriptEl = null;
  3805. };
  3806. global.document.documentElement.appendChild(scriptEl);
  3807. };
  3808. } else {
  3809. scheduleDrain = function () {
  3810. setTimeout(nextTick, 0);
  3811. };
  3812. }
  3813. }
  3814. var draining;
  3815. var queue = [];
  3816. //named nextTick for less confusing stack traces
  3817. function nextTick() {
  3818. draining = true;
  3819. var i, oldQueue;
  3820. var len = queue.length;
  3821. while (len) {
  3822. oldQueue = queue;
  3823. queue = [];
  3824. i = -1;
  3825. while (++i < len) {
  3826. oldQueue[i]();
  3827. }
  3828. len = queue.length;
  3829. }
  3830. draining = false;
  3831. }
  3832. module.exports = immediate;
  3833. function immediate(task) {
  3834. if (queue.push(task) === 1 && !draining) {
  3835. scheduleDrain();
  3836. }
  3837. }
  3838. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3839. },{}],37:[function(require,module,exports){
  3840. 'use strict';
  3841. var immediate = require('immediate');
  3842. /* istanbul ignore next */
  3843. function INTERNAL() {}
  3844. var handlers = {};
  3845. var REJECTED = ['REJECTED'];
  3846. var FULFILLED = ['FULFILLED'];
  3847. var PENDING = ['PENDING'];
  3848. module.exports = Promise;
  3849. function Promise(resolver) {
  3850. if (typeof resolver !== 'function') {
  3851. throw new TypeError('resolver must be a function');
  3852. }
  3853. this.state = PENDING;
  3854. this.queue = [];
  3855. this.outcome = void 0;
  3856. if (resolver !== INTERNAL) {
  3857. safelyResolveThenable(this, resolver);
  3858. }
  3859. }
  3860. Promise.prototype["finally"] = function (callback) {
  3861. if (typeof callback !== 'function') {
  3862. return this;
  3863. }
  3864. var p = this.constructor;
  3865. return this.then(resolve, reject);
  3866. function resolve(value) {
  3867. function yes () {
  3868. return value;
  3869. }
  3870. return p.resolve(callback()).then(yes);
  3871. }
  3872. function reject(reason) {
  3873. function no () {
  3874. throw reason;
  3875. }
  3876. return p.resolve(callback()).then(no);
  3877. }
  3878. };
  3879. Promise.prototype["catch"] = function (onRejected) {
  3880. return this.then(null, onRejected);
  3881. };
  3882. Promise.prototype.then = function (onFulfilled, onRejected) {
  3883. if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  3884. typeof onRejected !== 'function' && this.state === REJECTED) {
  3885. return this;
  3886. }
  3887. var promise = new this.constructor(INTERNAL);
  3888. if (this.state !== PENDING) {
  3889. var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  3890. unwrap(promise, resolver, this.outcome);
  3891. } else {
  3892. this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  3893. }
  3894. return promise;
  3895. };
  3896. function QueueItem(promise, onFulfilled, onRejected) {
  3897. this.promise = promise;
  3898. if (typeof onFulfilled === 'function') {
  3899. this.onFulfilled = onFulfilled;
  3900. this.callFulfilled = this.otherCallFulfilled;
  3901. }
  3902. if (typeof onRejected === 'function') {
  3903. this.onRejected = onRejected;
  3904. this.callRejected = this.otherCallRejected;
  3905. }
  3906. }
  3907. QueueItem.prototype.callFulfilled = function (value) {
  3908. handlers.resolve(this.promise, value);
  3909. };
  3910. QueueItem.prototype.otherCallFulfilled = function (value) {
  3911. unwrap(this.promise, this.onFulfilled, value);
  3912. };
  3913. QueueItem.prototype.callRejected = function (value) {
  3914. handlers.reject(this.promise, value);
  3915. };
  3916. QueueItem.prototype.otherCallRejected = function (value) {
  3917. unwrap(this.promise, this.onRejected, value);
  3918. };
  3919. function unwrap(promise, func, value) {
  3920. immediate(function () {
  3921. var returnValue;
  3922. try {
  3923. returnValue = func(value);
  3924. } catch (e) {
  3925. return handlers.reject(promise, e);
  3926. }
  3927. if (returnValue === promise) {
  3928. handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  3929. } else {
  3930. handlers.resolve(promise, returnValue);
  3931. }
  3932. });
  3933. }
  3934. handlers.resolve = function (self, value) {
  3935. var result = tryCatch(getThen, value);
  3936. if (result.status === 'error') {
  3937. return handlers.reject(self, result.value);
  3938. }
  3939. var thenable = result.value;
  3940. if (thenable) {
  3941. safelyResolveThenable(self, thenable);
  3942. } else {
  3943. self.state = FULFILLED;
  3944. self.outcome = value;
  3945. var i = -1;
  3946. var len = self.queue.length;
  3947. while (++i < len) {
  3948. self.queue[i].callFulfilled(value);
  3949. }
  3950. }
  3951. return self;
  3952. };
  3953. handlers.reject = function (self, error) {
  3954. self.state = REJECTED;
  3955. self.outcome = error;
  3956. var i = -1;
  3957. var len = self.queue.length;
  3958. while (++i < len) {
  3959. self.queue[i].callRejected(error);
  3960. }
  3961. return self;
  3962. };
  3963. function getThen(obj) {
  3964. // Make sure we only access the accessor once as required by the spec
  3965. var then = obj && obj.then;
  3966. if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
  3967. return function appyThen() {
  3968. then.apply(obj, arguments);
  3969. };
  3970. }
  3971. }
  3972. function safelyResolveThenable(self, thenable) {
  3973. // Either fulfill, reject or reject with error
  3974. var called = false;
  3975. function onError(value) {
  3976. if (called) {
  3977. return;
  3978. }
  3979. called = true;
  3980. handlers.reject(self, value);
  3981. }
  3982. function onSuccess(value) {
  3983. if (called) {
  3984. return;
  3985. }
  3986. called = true;
  3987. handlers.resolve(self, value);
  3988. }
  3989. function tryToUnwrap() {
  3990. thenable(onSuccess, onError);
  3991. }
  3992. var result = tryCatch(tryToUnwrap);
  3993. if (result.status === 'error') {
  3994. onError(result.value);
  3995. }
  3996. }
  3997. function tryCatch(func, value) {
  3998. var out = {};
  3999. try {
  4000. out.value = func(value);
  4001. out.status = 'success';
  4002. } catch (e) {
  4003. out.status = 'error';
  4004. out.value = e;
  4005. }
  4006. return out;
  4007. }
  4008. Promise.resolve = resolve;
  4009. function resolve(value) {
  4010. if (value instanceof this) {
  4011. return value;
  4012. }
  4013. return handlers.resolve(new this(INTERNAL), value);
  4014. }
  4015. Promise.reject = reject;
  4016. function reject(reason) {
  4017. var promise = new this(INTERNAL);
  4018. return handlers.reject(promise, reason);
  4019. }
  4020. Promise.all = all;
  4021. function all(iterable) {
  4022. var self = this;
  4023. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4024. return this.reject(new TypeError('must be an array'));
  4025. }
  4026. var len = iterable.length;
  4027. var called = false;
  4028. if (!len) {
  4029. return this.resolve([]);
  4030. }
  4031. var values = new Array(len);
  4032. var resolved = 0;
  4033. var i = -1;
  4034. var promise = new this(INTERNAL);
  4035. while (++i < len) {
  4036. allResolver(iterable[i], i);
  4037. }
  4038. return promise;
  4039. function allResolver(value, i) {
  4040. self.resolve(value).then(resolveFromAll, function (error) {
  4041. if (!called) {
  4042. called = true;
  4043. handlers.reject(promise, error);
  4044. }
  4045. });
  4046. function resolveFromAll(outValue) {
  4047. values[i] = outValue;
  4048. if (++resolved === len && !called) {
  4049. called = true;
  4050. handlers.resolve(promise, values);
  4051. }
  4052. }
  4053. }
  4054. }
  4055. Promise.race = race;
  4056. function race(iterable) {
  4057. var self = this;
  4058. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  4059. return this.reject(new TypeError('must be an array'));
  4060. }
  4061. var len = iterable.length;
  4062. var called = false;
  4063. if (!len) {
  4064. return this.resolve([]);
  4065. }
  4066. var i = -1;
  4067. var promise = new this(INTERNAL);
  4068. while (++i < len) {
  4069. resolver(iterable[i]);
  4070. }
  4071. return promise;
  4072. function resolver(value) {
  4073. self.resolve(value).then(function (response) {
  4074. if (!called) {
  4075. called = true;
  4076. handlers.resolve(promise, response);
  4077. }
  4078. }, function (error) {
  4079. if (!called) {
  4080. called = true;
  4081. handlers.reject(promise, error);
  4082. }
  4083. });
  4084. }
  4085. }
  4086. },{"immediate":36}],38:[function(require,module,exports){
  4087. // Top level file is just a mixin of submodules & constants
  4088. 'use strict';
  4089. var assign = require('./lib/utils/common').assign;
  4090. var deflate = require('./lib/deflate');
  4091. var inflate = require('./lib/inflate');
  4092. var constants = require('./lib/zlib/constants');
  4093. var pako = {};
  4094. assign(pako, deflate, inflate, constants);
  4095. module.exports = pako;
  4096. },{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(require,module,exports){
  4097. 'use strict';
  4098. var zlib_deflate = require('./zlib/deflate');
  4099. var utils = require('./utils/common');
  4100. var strings = require('./utils/strings');
  4101. var msg = require('./zlib/messages');
  4102. var ZStream = require('./zlib/zstream');
  4103. var toString = Object.prototype.toString;
  4104. /* Public constants ==========================================================*/
  4105. /* ===========================================================================*/
  4106. var Z_NO_FLUSH = 0;
  4107. var Z_FINISH = 4;
  4108. var Z_OK = 0;
  4109. var Z_STREAM_END = 1;
  4110. var Z_SYNC_FLUSH = 2;
  4111. var Z_DEFAULT_COMPRESSION = -1;
  4112. var Z_DEFAULT_STRATEGY = 0;
  4113. var Z_DEFLATED = 8;
  4114. /* ===========================================================================*/
  4115. /**
  4116. * class Deflate
  4117. *
  4118. * Generic JS-style wrapper for zlib calls. If you don't need
  4119. * streaming behaviour - use more simple functions: [[deflate]],
  4120. * [[deflateRaw]] and [[gzip]].
  4121. **/
  4122. /* internal
  4123. * Deflate.chunks -> Array
  4124. *
  4125. * Chunks of output data, if [[Deflate#onData]] not overriden.
  4126. **/
  4127. /**
  4128. * Deflate.result -> Uint8Array|Array
  4129. *
  4130. * Compressed result, generated by default [[Deflate#onData]]
  4131. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  4132. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  4133. * push a chunk with explicit flush (call [[Deflate#push]] with
  4134. * `Z_SYNC_FLUSH` param).
  4135. **/
  4136. /**
  4137. * Deflate.err -> Number
  4138. *
  4139. * Error code after deflate finished. 0 (Z_OK) on success.
  4140. * You will not need it in real life, because deflate errors
  4141. * are possible only on wrong options or bad `onData` / `onEnd`
  4142. * custom handlers.
  4143. **/
  4144. /**
  4145. * Deflate.msg -> String
  4146. *
  4147. * Error message, if [[Deflate.err]] != 0
  4148. **/
  4149. /**
  4150. * new Deflate(options)
  4151. * - options (Object): zlib deflate options.
  4152. *
  4153. * Creates new deflator instance with specified params. Throws exception
  4154. * on bad params. Supported options:
  4155. *
  4156. * - `level`
  4157. * - `windowBits`
  4158. * - `memLevel`
  4159. * - `strategy`
  4160. * - `dictionary`
  4161. *
  4162. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4163. * for more information on these.
  4164. *
  4165. * Additional options, for internal needs:
  4166. *
  4167. * - `chunkSize` - size of generated data chunks (16K by default)
  4168. * - `raw` (Boolean) - do raw deflate
  4169. * - `gzip` (Boolean) - create gzip wrapper
  4170. * - `to` (String) - if equal to 'string', then result will be "binary string"
  4171. * (each char code [0..255])
  4172. * - `header` (Object) - custom header for gzip
  4173. * - `text` (Boolean) - true if compressed data believed to be text
  4174. * - `time` (Number) - modification time, unix timestamp
  4175. * - `os` (Number) - operation system code
  4176. * - `extra` (Array) - array of bytes with extra data (max 65536)
  4177. * - `name` (String) - file name (binary string)
  4178. * - `comment` (String) - comment (binary string)
  4179. * - `hcrc` (Boolean) - true if header crc should be added
  4180. *
  4181. * ##### Example:
  4182. *
  4183. * ```javascript
  4184. * var pako = require('pako')
  4185. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  4186. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  4187. *
  4188. * var deflate = new pako.Deflate({ level: 3});
  4189. *
  4190. * deflate.push(chunk1, false);
  4191. * deflate.push(chunk2, true); // true -> last chunk
  4192. *
  4193. * if (deflate.err) { throw new Error(deflate.err); }
  4194. *
  4195. * console.log(deflate.result);
  4196. * ```
  4197. **/
  4198. function Deflate(options) {
  4199. if (!(this instanceof Deflate)) return new Deflate(options);
  4200. this.options = utils.assign({
  4201. level: Z_DEFAULT_COMPRESSION,
  4202. method: Z_DEFLATED,
  4203. chunkSize: 16384,
  4204. windowBits: 15,
  4205. memLevel: 8,
  4206. strategy: Z_DEFAULT_STRATEGY,
  4207. to: ''
  4208. }, options || {});
  4209. var opt = this.options;
  4210. if (opt.raw && (opt.windowBits > 0)) {
  4211. opt.windowBits = -opt.windowBits;
  4212. }
  4213. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  4214. opt.windowBits += 16;
  4215. }
  4216. this.err = 0; // error code, if happens (0 = Z_OK)
  4217. this.msg = ''; // error message
  4218. this.ended = false; // used to avoid multiple onEnd() calls
  4219. this.chunks = []; // chunks of compressed data
  4220. this.strm = new ZStream();
  4221. this.strm.avail_out = 0;
  4222. var status = zlib_deflate.deflateInit2(
  4223. this.strm,
  4224. opt.level,
  4225. opt.method,
  4226. opt.windowBits,
  4227. opt.memLevel,
  4228. opt.strategy
  4229. );
  4230. if (status !== Z_OK) {
  4231. throw new Error(msg[status]);
  4232. }
  4233. if (opt.header) {
  4234. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  4235. }
  4236. if (opt.dictionary) {
  4237. var dict;
  4238. // Convert data if needed
  4239. if (typeof opt.dictionary === 'string') {
  4240. // If we need to compress text, change encoding to utf8.
  4241. dict = strings.string2buf(opt.dictionary);
  4242. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  4243. dict = new Uint8Array(opt.dictionary);
  4244. } else {
  4245. dict = opt.dictionary;
  4246. }
  4247. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  4248. if (status !== Z_OK) {
  4249. throw new Error(msg[status]);
  4250. }
  4251. this._dict_set = true;
  4252. }
  4253. }
  4254. /**
  4255. * Deflate#push(data[, mode]) -> Boolean
  4256. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  4257. * converted to utf8 byte sequence.
  4258. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  4259. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  4260. *
  4261. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  4262. * new compressed chunks. Returns `true` on success. The last data block must have
  4263. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  4264. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  4265. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  4266. *
  4267. * On fail call [[Deflate#onEnd]] with error code and return false.
  4268. *
  4269. * We strongly recommend to use `Uint8Array` on input for best speed (output
  4270. * array format is detected automatically). Also, don't skip last param and always
  4271. * use the same type in your code (boolean or number). That will improve JS speed.
  4272. *
  4273. * For regular `Array`-s make sure all elements are [0..255].
  4274. *
  4275. * ##### Example
  4276. *
  4277. * ```javascript
  4278. * push(chunk, false); // push one of data chunks
  4279. * ...
  4280. * push(chunk, true); // push last chunk
  4281. * ```
  4282. **/
  4283. Deflate.prototype.push = function (data, mode) {
  4284. var strm = this.strm;
  4285. var chunkSize = this.options.chunkSize;
  4286. var status, _mode;
  4287. if (this.ended) { return false; }
  4288. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  4289. // Convert data if needed
  4290. if (typeof data === 'string') {
  4291. // If we need to compress text, change encoding to utf8.
  4292. strm.input = strings.string2buf(data);
  4293. } else if (toString.call(data) === '[object ArrayBuffer]') {
  4294. strm.input = new Uint8Array(data);
  4295. } else {
  4296. strm.input = data;
  4297. }
  4298. strm.next_in = 0;
  4299. strm.avail_in = strm.input.length;
  4300. do {
  4301. if (strm.avail_out === 0) {
  4302. strm.output = new utils.Buf8(chunkSize);
  4303. strm.next_out = 0;
  4304. strm.avail_out = chunkSize;
  4305. }
  4306. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  4307. if (status !== Z_STREAM_END && status !== Z_OK) {
  4308. this.onEnd(status);
  4309. this.ended = true;
  4310. return false;
  4311. }
  4312. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  4313. if (this.options.to === 'string') {
  4314. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  4315. } else {
  4316. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  4317. }
  4318. }
  4319. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  4320. // Finalize on the last chunk.
  4321. if (_mode === Z_FINISH) {
  4322. status = zlib_deflate.deflateEnd(this.strm);
  4323. this.onEnd(status);
  4324. this.ended = true;
  4325. return status === Z_OK;
  4326. }
  4327. // callback interim results if Z_SYNC_FLUSH.
  4328. if (_mode === Z_SYNC_FLUSH) {
  4329. this.onEnd(Z_OK);
  4330. strm.avail_out = 0;
  4331. return true;
  4332. }
  4333. return true;
  4334. };
  4335. /**
  4336. * Deflate#onData(chunk) -> Void
  4337. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  4338. * on js engine support. When string output requested, each chunk
  4339. * will be string.
  4340. *
  4341. * By default, stores data blocks in `chunks[]` property and glue
  4342. * those in `onEnd`. Override this handler, if you need another behaviour.
  4343. **/
  4344. Deflate.prototype.onData = function (chunk) {
  4345. this.chunks.push(chunk);
  4346. };
  4347. /**
  4348. * Deflate#onEnd(status) -> Void
  4349. * - status (Number): deflate status. 0 (Z_OK) on success,
  4350. * other if not.
  4351. *
  4352. * Called once after you tell deflate that the input stream is
  4353. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  4354. * or if an error happened. By default - join collected chunks,
  4355. * free memory and fill `results` / `err` properties.
  4356. **/
  4357. Deflate.prototype.onEnd = function (status) {
  4358. // On success - join
  4359. if (status === Z_OK) {
  4360. if (this.options.to === 'string') {
  4361. this.result = this.chunks.join('');
  4362. } else {
  4363. this.result = utils.flattenChunks(this.chunks);
  4364. }
  4365. }
  4366. this.chunks = [];
  4367. this.err = status;
  4368. this.msg = this.strm.msg;
  4369. };
  4370. /**
  4371. * deflate(data[, options]) -> Uint8Array|Array|String
  4372. * - data (Uint8Array|Array|String): input data to compress.
  4373. * - options (Object): zlib deflate options.
  4374. *
  4375. * Compress `data` with deflate algorithm and `options`.
  4376. *
  4377. * Supported options are:
  4378. *
  4379. * - level
  4380. * - windowBits
  4381. * - memLevel
  4382. * - strategy
  4383. * - dictionary
  4384. *
  4385. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4386. * for more information on these.
  4387. *
  4388. * Sugar (options):
  4389. *
  4390. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  4391. * negative windowBits implicitly.
  4392. * - `to` (String) - if equal to 'string', then result will be "binary string"
  4393. * (each char code [0..255])
  4394. *
  4395. * ##### Example:
  4396. *
  4397. * ```javascript
  4398. * var pako = require('pako')
  4399. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  4400. *
  4401. * console.log(pako.deflate(data));
  4402. * ```
  4403. **/
  4404. function deflate(input, options) {
  4405. var deflator = new Deflate(options);
  4406. deflator.push(input, true);
  4407. // That will never happens, if you don't cheat with options :)
  4408. if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
  4409. return deflator.result;
  4410. }
  4411. /**
  4412. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  4413. * - data (Uint8Array|Array|String): input data to compress.
  4414. * - options (Object): zlib deflate options.
  4415. *
  4416. * The same as [[deflate]], but creates raw data, without wrapper
  4417. * (header and adler32 crc).
  4418. **/
  4419. function deflateRaw(input, options) {
  4420. options = options || {};
  4421. options.raw = true;
  4422. return deflate(input, options);
  4423. }
  4424. /**
  4425. * gzip(data[, options]) -> Uint8Array|Array|String
  4426. * - data (Uint8Array|Array|String): input data to compress.
  4427. * - options (Object): zlib deflate options.
  4428. *
  4429. * The same as [[deflate]], but create gzip wrapper instead of
  4430. * deflate one.
  4431. **/
  4432. function gzip(input, options) {
  4433. options = options || {};
  4434. options.gzip = true;
  4435. return deflate(input, options);
  4436. }
  4437. exports.Deflate = Deflate;
  4438. exports.deflate = deflate;
  4439. exports.deflateRaw = deflateRaw;
  4440. exports.gzip = gzip;
  4441. },{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(require,module,exports){
  4442. 'use strict';
  4443. var zlib_inflate = require('./zlib/inflate');
  4444. var utils = require('./utils/common');
  4445. var strings = require('./utils/strings');
  4446. var c = require('./zlib/constants');
  4447. var msg = require('./zlib/messages');
  4448. var ZStream = require('./zlib/zstream');
  4449. var GZheader = require('./zlib/gzheader');
  4450. var toString = Object.prototype.toString;
  4451. /**
  4452. * class Inflate
  4453. *
  4454. * Generic JS-style wrapper for zlib calls. If you don't need
  4455. * streaming behaviour - use more simple functions: [[inflate]]
  4456. * and [[inflateRaw]].
  4457. **/
  4458. /* internal
  4459. * inflate.chunks -> Array
  4460. *
  4461. * Chunks of output data, if [[Inflate#onData]] not overriden.
  4462. **/
  4463. /**
  4464. * Inflate.result -> Uint8Array|Array|String
  4465. *
  4466. * Uncompressed result, generated by default [[Inflate#onData]]
  4467. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  4468. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  4469. * push a chunk with explicit flush (call [[Inflate#push]] with
  4470. * `Z_SYNC_FLUSH` param).
  4471. **/
  4472. /**
  4473. * Inflate.err -> Number
  4474. *
  4475. * Error code after inflate finished. 0 (Z_OK) on success.
  4476. * Should be checked if broken data possible.
  4477. **/
  4478. /**
  4479. * Inflate.msg -> String
  4480. *
  4481. * Error message, if [[Inflate.err]] != 0
  4482. **/
  4483. /**
  4484. * new Inflate(options)
  4485. * - options (Object): zlib inflate options.
  4486. *
  4487. * Creates new inflator instance with specified params. Throws exception
  4488. * on bad params. Supported options:
  4489. *
  4490. * - `windowBits`
  4491. * - `dictionary`
  4492. *
  4493. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4494. * for more information on these.
  4495. *
  4496. * Additional options, for internal needs:
  4497. *
  4498. * - `chunkSize` - size of generated data chunks (16K by default)
  4499. * - `raw` (Boolean) - do raw inflate
  4500. * - `to` (String) - if equal to 'string', then result will be converted
  4501. * from utf8 to utf16 (javascript) string. When string output requested,
  4502. * chunk length can differ from `chunkSize`, depending on content.
  4503. *
  4504. * By default, when no options set, autodetect deflate/gzip data format via
  4505. * wrapper header.
  4506. *
  4507. * ##### Example:
  4508. *
  4509. * ```javascript
  4510. * var pako = require('pako')
  4511. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  4512. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  4513. *
  4514. * var inflate = new pako.Inflate({ level: 3});
  4515. *
  4516. * inflate.push(chunk1, false);
  4517. * inflate.push(chunk2, true); // true -> last chunk
  4518. *
  4519. * if (inflate.err) { throw new Error(inflate.err); }
  4520. *
  4521. * console.log(inflate.result);
  4522. * ```
  4523. **/
  4524. function Inflate(options) {
  4525. if (!(this instanceof Inflate)) return new Inflate(options);
  4526. this.options = utils.assign({
  4527. chunkSize: 16384,
  4528. windowBits: 0,
  4529. to: ''
  4530. }, options || {});
  4531. var opt = this.options;
  4532. // Force window size for `raw` data, if not set directly,
  4533. // because we have no header for autodetect.
  4534. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  4535. opt.windowBits = -opt.windowBits;
  4536. if (opt.windowBits === 0) { opt.windowBits = -15; }
  4537. }
  4538. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  4539. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  4540. !(options && options.windowBits)) {
  4541. opt.windowBits += 32;
  4542. }
  4543. // Gzip header has no info about windows size, we can do autodetect only
  4544. // for deflate. So, if window size not set, force it to max when gzip possible
  4545. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  4546. // bit 3 (16) -> gzipped data
  4547. // bit 4 (32) -> autodetect gzip/deflate
  4548. if ((opt.windowBits & 15) === 0) {
  4549. opt.windowBits |= 15;
  4550. }
  4551. }
  4552. this.err = 0; // error code, if happens (0 = Z_OK)
  4553. this.msg = ''; // error message
  4554. this.ended = false; // used to avoid multiple onEnd() calls
  4555. this.chunks = []; // chunks of compressed data
  4556. this.strm = new ZStream();
  4557. this.strm.avail_out = 0;
  4558. var status = zlib_inflate.inflateInit2(
  4559. this.strm,
  4560. opt.windowBits
  4561. );
  4562. if (status !== c.Z_OK) {
  4563. throw new Error(msg[status]);
  4564. }
  4565. this.header = new GZheader();
  4566. zlib_inflate.inflateGetHeader(this.strm, this.header);
  4567. }
  4568. /**
  4569. * Inflate#push(data[, mode]) -> Boolean
  4570. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  4571. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  4572. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  4573. *
  4574. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  4575. * new output chunks. Returns `true` on success. The last data block must have
  4576. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  4577. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  4578. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  4579. *
  4580. * On fail call [[Inflate#onEnd]] with error code and return false.
  4581. *
  4582. * We strongly recommend to use `Uint8Array` on input for best speed (output
  4583. * format is detected automatically). Also, don't skip last param and always
  4584. * use the same type in your code (boolean or number). That will improve JS speed.
  4585. *
  4586. * For regular `Array`-s make sure all elements are [0..255].
  4587. *
  4588. * ##### Example
  4589. *
  4590. * ```javascript
  4591. * push(chunk, false); // push one of data chunks
  4592. * ...
  4593. * push(chunk, true); // push last chunk
  4594. * ```
  4595. **/
  4596. Inflate.prototype.push = function (data, mode) {
  4597. var strm = this.strm;
  4598. var chunkSize = this.options.chunkSize;
  4599. var dictionary = this.options.dictionary;
  4600. var status, _mode;
  4601. var next_out_utf8, tail, utf8str;
  4602. var dict;
  4603. // Flag to properly process Z_BUF_ERROR on testing inflate call
  4604. // when we check that all output data was flushed.
  4605. var allowBufError = false;
  4606. if (this.ended) { return false; }
  4607. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  4608. // Convert data if needed
  4609. if (typeof data === 'string') {
  4610. // Only binary strings can be decompressed on practice
  4611. strm.input = strings.binstring2buf(data);
  4612. } else if (toString.call(data) === '[object ArrayBuffer]') {
  4613. strm.input = new Uint8Array(data);
  4614. } else {
  4615. strm.input = data;
  4616. }
  4617. strm.next_in = 0;
  4618. strm.avail_in = strm.input.length;
  4619. do {
  4620. if (strm.avail_out === 0) {
  4621. strm.output = new utils.Buf8(chunkSize);
  4622. strm.next_out = 0;
  4623. strm.avail_out = chunkSize;
  4624. }
  4625. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  4626. if (status === c.Z_NEED_DICT && dictionary) {
  4627. // Convert data if needed
  4628. if (typeof dictionary === 'string') {
  4629. dict = strings.string2buf(dictionary);
  4630. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  4631. dict = new Uint8Array(dictionary);
  4632. } else {
  4633. dict = dictionary;
  4634. }
  4635. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  4636. }
  4637. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  4638. status = c.Z_OK;
  4639. allowBufError = false;
  4640. }
  4641. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  4642. this.onEnd(status);
  4643. this.ended = true;
  4644. return false;
  4645. }
  4646. if (strm.next_out) {
  4647. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  4648. if (this.options.to === 'string') {
  4649. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  4650. tail = strm.next_out - next_out_utf8;
  4651. utf8str = strings.buf2string(strm.output, next_out_utf8);
  4652. // move tail
  4653. strm.next_out = tail;
  4654. strm.avail_out = chunkSize - tail;
  4655. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  4656. this.onData(utf8str);
  4657. } else {
  4658. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  4659. }
  4660. }
  4661. }
  4662. // When no more input data, we should check that internal inflate buffers
  4663. // are flushed. The only way to do it when avail_out = 0 - run one more
  4664. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  4665. // Here we set flag to process this error properly.
  4666. //
  4667. // NOTE. Deflate does not return error in this case and does not needs such
  4668. // logic.
  4669. if (strm.avail_in === 0 && strm.avail_out === 0) {
  4670. allowBufError = true;
  4671. }
  4672. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  4673. if (status === c.Z_STREAM_END) {
  4674. _mode = c.Z_FINISH;
  4675. }
  4676. // Finalize on the last chunk.
  4677. if (_mode === c.Z_FINISH) {
  4678. status = zlib_inflate.inflateEnd(this.strm);
  4679. this.onEnd(status);
  4680. this.ended = true;
  4681. return status === c.Z_OK;
  4682. }
  4683. // callback interim results if Z_SYNC_FLUSH.
  4684. if (_mode === c.Z_SYNC_FLUSH) {
  4685. this.onEnd(c.Z_OK);
  4686. strm.avail_out = 0;
  4687. return true;
  4688. }
  4689. return true;
  4690. };
  4691. /**
  4692. * Inflate#onData(chunk) -> Void
  4693. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  4694. * on js engine support. When string output requested, each chunk
  4695. * will be string.
  4696. *
  4697. * By default, stores data blocks in `chunks[]` property and glue
  4698. * those in `onEnd`. Override this handler, if you need another behaviour.
  4699. **/
  4700. Inflate.prototype.onData = function (chunk) {
  4701. this.chunks.push(chunk);
  4702. };
  4703. /**
  4704. * Inflate#onEnd(status) -> Void
  4705. * - status (Number): inflate status. 0 (Z_OK) on success,
  4706. * other if not.
  4707. *
  4708. * Called either after you tell inflate that the input stream is
  4709. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  4710. * or if an error happened. By default - join collected chunks,
  4711. * free memory and fill `results` / `err` properties.
  4712. **/
  4713. Inflate.prototype.onEnd = function (status) {
  4714. // On success - join
  4715. if (status === c.Z_OK) {
  4716. if (this.options.to === 'string') {
  4717. // Glue & convert here, until we teach pako to send
  4718. // utf8 alligned strings to onData
  4719. this.result = this.chunks.join('');
  4720. } else {
  4721. this.result = utils.flattenChunks(this.chunks);
  4722. }
  4723. }
  4724. this.chunks = [];
  4725. this.err = status;
  4726. this.msg = this.strm.msg;
  4727. };
  4728. /**
  4729. * inflate(data[, options]) -> Uint8Array|Array|String
  4730. * - data (Uint8Array|Array|String): input data to decompress.
  4731. * - options (Object): zlib inflate options.
  4732. *
  4733. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  4734. * format via wrapper header by default. That's why we don't provide
  4735. * separate `ungzip` method.
  4736. *
  4737. * Supported options are:
  4738. *
  4739. * - windowBits
  4740. *
  4741. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4742. * for more information.
  4743. *
  4744. * Sugar (options):
  4745. *
  4746. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  4747. * negative windowBits implicitly.
  4748. * - `to` (String) - if equal to 'string', then result will be converted
  4749. * from utf8 to utf16 (javascript) string. When string output requested,
  4750. * chunk length can differ from `chunkSize`, depending on content.
  4751. *
  4752. *
  4753. * ##### Example:
  4754. *
  4755. * ```javascript
  4756. * var pako = require('pako')
  4757. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  4758. * , output;
  4759. *
  4760. * try {
  4761. * output = pako.inflate(input);
  4762. * } catch (err)
  4763. * console.log(err);
  4764. * }
  4765. * ```
  4766. **/
  4767. function inflate(input, options) {
  4768. var inflator = new Inflate(options);
  4769. inflator.push(input, true);
  4770. // That will never happens, if you don't cheat with options :)
  4771. if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
  4772. return inflator.result;
  4773. }
  4774. /**
  4775. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  4776. * - data (Uint8Array|Array|String): input data to decompress.
  4777. * - options (Object): zlib inflate options.
  4778. *
  4779. * The same as [[inflate]], but creates raw data, without wrapper
  4780. * (header and adler32 crc).
  4781. **/
  4782. function inflateRaw(input, options) {
  4783. options = options || {};
  4784. options.raw = true;
  4785. return inflate(input, options);
  4786. }
  4787. /**
  4788. * ungzip(data[, options]) -> Uint8Array|Array|String
  4789. * - data (Uint8Array|Array|String): input data to decompress.
  4790. * - options (Object): zlib inflate options.
  4791. *
  4792. * Just shortcut to [[inflate]], because it autodetects format
  4793. * by header.content. Done for convenience.
  4794. **/
  4795. exports.Inflate = Inflate;
  4796. exports.inflate = inflate;
  4797. exports.inflateRaw = inflateRaw;
  4798. exports.ungzip = inflate;
  4799. },{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(require,module,exports){
  4800. 'use strict';
  4801. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  4802. (typeof Uint16Array !== 'undefined') &&
  4803. (typeof Int32Array !== 'undefined');
  4804. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  4805. var sources = Array.prototype.slice.call(arguments, 1);
  4806. while (sources.length) {
  4807. var source = sources.shift();
  4808. if (!source) { continue; }
  4809. if (typeof source !== 'object') {
  4810. throw new TypeError(source + 'must be non-object');
  4811. }
  4812. for (var p in source) {
  4813. if (source.hasOwnProperty(p)) {
  4814. obj[p] = source[p];
  4815. }
  4816. }
  4817. }
  4818. return obj;
  4819. };
  4820. // reduce buffer size, avoiding mem copy
  4821. exports.shrinkBuf = function (buf, size) {
  4822. if (buf.length === size) { return buf; }
  4823. if (buf.subarray) { return buf.subarray(0, size); }
  4824. buf.length = size;
  4825. return buf;
  4826. };
  4827. var fnTyped = {
  4828. arraySet: function (dest, src, src_offs, len, dest_offs) {
  4829. if (src.subarray && dest.subarray) {
  4830. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  4831. return;
  4832. }
  4833. // Fallback to ordinary array
  4834. for (var i = 0; i < len; i++) {
  4835. dest[dest_offs + i] = src[src_offs + i];
  4836. }
  4837. },
  4838. // Join array of chunks to single array.
  4839. flattenChunks: function (chunks) {
  4840. var i, l, len, pos, chunk, result;
  4841. // calculate data length
  4842. len = 0;
  4843. for (i = 0, l = chunks.length; i < l; i++) {
  4844. len += chunks[i].length;
  4845. }
  4846. // join chunks
  4847. result = new Uint8Array(len);
  4848. pos = 0;
  4849. for (i = 0, l = chunks.length; i < l; i++) {
  4850. chunk = chunks[i];
  4851. result.set(chunk, pos);
  4852. pos += chunk.length;
  4853. }
  4854. return result;
  4855. }
  4856. };
  4857. var fnUntyped = {
  4858. arraySet: function (dest, src, src_offs, len, dest_offs) {
  4859. for (var i = 0; i < len; i++) {
  4860. dest[dest_offs + i] = src[src_offs + i];
  4861. }
  4862. },
  4863. // Join array of chunks to single array.
  4864. flattenChunks: function (chunks) {
  4865. return [].concat.apply([], chunks);
  4866. }
  4867. };
  4868. // Enable/Disable typed arrays use, for testing
  4869. //
  4870. exports.setTyped = function (on) {
  4871. if (on) {
  4872. exports.Buf8 = Uint8Array;
  4873. exports.Buf16 = Uint16Array;
  4874. exports.Buf32 = Int32Array;
  4875. exports.assign(exports, fnTyped);
  4876. } else {
  4877. exports.Buf8 = Array;
  4878. exports.Buf16 = Array;
  4879. exports.Buf32 = Array;
  4880. exports.assign(exports, fnUntyped);
  4881. }
  4882. };
  4883. exports.setTyped(TYPED_OK);
  4884. },{}],42:[function(require,module,exports){
  4885. // String encode/decode helpers
  4886. 'use strict';
  4887. var utils = require('./common');
  4888. // Quick check if we can use fast array to bin string conversion
  4889. //
  4890. // - apply(Array) can fail on Android 2.2
  4891. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  4892. //
  4893. var STR_APPLY_OK = true;
  4894. var STR_APPLY_UIA_OK = true;
  4895. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  4896. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  4897. // Table with utf8 lengths (calculated by first byte of sequence)
  4898. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  4899. // because max possible codepoint is 0x10ffff
  4900. var _utf8len = new utils.Buf8(256);
  4901. for (var q = 0; q < 256; q++) {
  4902. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  4903. }
  4904. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  4905. // convert string to array (typed, when possible)
  4906. exports.string2buf = function (str) {
  4907. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  4908. // count binary size
  4909. for (m_pos = 0; m_pos < str_len; m_pos++) {
  4910. c = str.charCodeAt(m_pos);
  4911. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  4912. c2 = str.charCodeAt(m_pos + 1);
  4913. if ((c2 & 0xfc00) === 0xdc00) {
  4914. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4915. m_pos++;
  4916. }
  4917. }
  4918. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  4919. }
  4920. // allocate buffer
  4921. buf = new utils.Buf8(buf_len);
  4922. // convert
  4923. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  4924. c = str.charCodeAt(m_pos);
  4925. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  4926. c2 = str.charCodeAt(m_pos + 1);
  4927. if ((c2 & 0xfc00) === 0xdc00) {
  4928. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4929. m_pos++;
  4930. }
  4931. }
  4932. if (c < 0x80) {
  4933. /* one byte */
  4934. buf[i++] = c;
  4935. } else if (c < 0x800) {
  4936. /* two bytes */
  4937. buf[i++] = 0xC0 | (c >>> 6);
  4938. buf[i++] = 0x80 | (c & 0x3f);
  4939. } else if (c < 0x10000) {
  4940. /* three bytes */
  4941. buf[i++] = 0xE0 | (c >>> 12);
  4942. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  4943. buf[i++] = 0x80 | (c & 0x3f);
  4944. } else {
  4945. /* four bytes */
  4946. buf[i++] = 0xf0 | (c >>> 18);
  4947. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  4948. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  4949. buf[i++] = 0x80 | (c & 0x3f);
  4950. }
  4951. }
  4952. return buf;
  4953. };
  4954. // Helper (used in 2 places)
  4955. function buf2binstring(buf, len) {
  4956. // use fallback for big arrays to avoid stack overflow
  4957. if (len < 65537) {
  4958. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  4959. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  4960. }
  4961. }
  4962. var result = '';
  4963. for (var i = 0; i < len; i++) {
  4964. result += String.fromCharCode(buf[i]);
  4965. }
  4966. return result;
  4967. }
  4968. // Convert byte array to binary string
  4969. exports.buf2binstring = function (buf) {
  4970. return buf2binstring(buf, buf.length);
  4971. };
  4972. // Convert binary string (typed, when possible)
  4973. exports.binstring2buf = function (str) {
  4974. var buf = new utils.Buf8(str.length);
  4975. for (var i = 0, len = buf.length; i < len; i++) {
  4976. buf[i] = str.charCodeAt(i);
  4977. }
  4978. return buf;
  4979. };
  4980. // convert array to string
  4981. exports.buf2string = function (buf, max) {
  4982. var i, out, c, c_len;
  4983. var len = max || buf.length;
  4984. // Reserve max possible length (2 words per char)
  4985. // NB: by unknown reasons, Array is significantly faster for
  4986. // String.fromCharCode.apply than Uint16Array.
  4987. var utf16buf = new Array(len * 2);
  4988. for (out = 0, i = 0; i < len;) {
  4989. c = buf[i++];
  4990. // quick process ascii
  4991. if (c < 0x80) { utf16buf[out++] = c; continue; }
  4992. c_len = _utf8len[c];
  4993. // skip 5 & 6 byte codes
  4994. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  4995. // apply mask on first byte
  4996. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  4997. // join the rest
  4998. while (c_len > 1 && i < len) {
  4999. c = (c << 6) | (buf[i++] & 0x3f);
  5000. c_len--;
  5001. }
  5002. // terminated by end of string?
  5003. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  5004. if (c < 0x10000) {
  5005. utf16buf[out++] = c;
  5006. } else {
  5007. c -= 0x10000;
  5008. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  5009. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  5010. }
  5011. }
  5012. return buf2binstring(utf16buf, out);
  5013. };
  5014. // Calculate max possible position in utf8 buffer,
  5015. // that will not break sequence. If that's not possible
  5016. // - (very small limits) return max size as is.
  5017. //
  5018. // buf[] - utf8 bytes array
  5019. // max - length limit (mandatory);
  5020. exports.utf8border = function (buf, max) {
  5021. var pos;
  5022. max = max || buf.length;
  5023. if (max > buf.length) { max = buf.length; }
  5024. // go back from last position, until start of sequence found
  5025. pos = max - 1;
  5026. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  5027. // Fuckup - very small and broken sequence,
  5028. // return max, because we should return something anyway.
  5029. if (pos < 0) { return max; }
  5030. // If we came to start of buffer - that means vuffer is too small,
  5031. // return max too.
  5032. if (pos === 0) { return max; }
  5033. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  5034. };
  5035. },{"./common":41}],43:[function(require,module,exports){
  5036. 'use strict';
  5037. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  5038. // It doesn't worth to make additional optimizationa as in original.
  5039. // Small size is preferable.
  5040. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5041. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5042. //
  5043. // This software is provided 'as-is', without any express or implied
  5044. // warranty. In no event will the authors be held liable for any damages
  5045. // arising from the use of this software.
  5046. //
  5047. // Permission is granted to anyone to use this software for any purpose,
  5048. // including commercial applications, and to alter it and redistribute it
  5049. // freely, subject to the following restrictions:
  5050. //
  5051. // 1. The origin of this software must not be misrepresented; you must not
  5052. // claim that you wrote the original software. If you use this software
  5053. // in a product, an acknowledgment in the product documentation would be
  5054. // appreciated but is not required.
  5055. // 2. Altered source versions must be plainly marked as such, and must not be
  5056. // misrepresented as being the original software.
  5057. // 3. This notice may not be removed or altered from any source distribution.
  5058. function adler32(adler, buf, len, pos) {
  5059. var s1 = (adler & 0xffff) |0,
  5060. s2 = ((adler >>> 16) & 0xffff) |0,
  5061. n = 0;
  5062. while (len !== 0) {
  5063. // Set limit ~ twice less than 5552, to keep
  5064. // s2 in 31-bits, because we force signed ints.
  5065. // in other case %= will fail.
  5066. n = len > 2000 ? 2000 : len;
  5067. len -= n;
  5068. do {
  5069. s1 = (s1 + buf[pos++]) |0;
  5070. s2 = (s2 + s1) |0;
  5071. } while (--n);
  5072. s1 %= 65521;
  5073. s2 %= 65521;
  5074. }
  5075. return (s1 | (s2 << 16)) |0;
  5076. }
  5077. module.exports = adler32;
  5078. },{}],44:[function(require,module,exports){
  5079. 'use strict';
  5080. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5081. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5082. //
  5083. // This software is provided 'as-is', without any express or implied
  5084. // warranty. In no event will the authors be held liable for any damages
  5085. // arising from the use of this software.
  5086. //
  5087. // Permission is granted to anyone to use this software for any purpose,
  5088. // including commercial applications, and to alter it and redistribute it
  5089. // freely, subject to the following restrictions:
  5090. //
  5091. // 1. The origin of this software must not be misrepresented; you must not
  5092. // claim that you wrote the original software. If you use this software
  5093. // in a product, an acknowledgment in the product documentation would be
  5094. // appreciated but is not required.
  5095. // 2. Altered source versions must be plainly marked as such, and must not be
  5096. // misrepresented as being the original software.
  5097. // 3. This notice may not be removed or altered from any source distribution.
  5098. module.exports = {
  5099. /* Allowed flush values; see deflate() and inflate() below for details */
  5100. Z_NO_FLUSH: 0,
  5101. Z_PARTIAL_FLUSH: 1,
  5102. Z_SYNC_FLUSH: 2,
  5103. Z_FULL_FLUSH: 3,
  5104. Z_FINISH: 4,
  5105. Z_BLOCK: 5,
  5106. Z_TREES: 6,
  5107. /* Return codes for the compression/decompression functions. Negative values
  5108. * are errors, positive values are used for special but normal events.
  5109. */
  5110. Z_OK: 0,
  5111. Z_STREAM_END: 1,
  5112. Z_NEED_DICT: 2,
  5113. Z_ERRNO: -1,
  5114. Z_STREAM_ERROR: -2,
  5115. Z_DATA_ERROR: -3,
  5116. //Z_MEM_ERROR: -4,
  5117. Z_BUF_ERROR: -5,
  5118. //Z_VERSION_ERROR: -6,
  5119. /* compression levels */
  5120. Z_NO_COMPRESSION: 0,
  5121. Z_BEST_SPEED: 1,
  5122. Z_BEST_COMPRESSION: 9,
  5123. Z_DEFAULT_COMPRESSION: -1,
  5124. Z_FILTERED: 1,
  5125. Z_HUFFMAN_ONLY: 2,
  5126. Z_RLE: 3,
  5127. Z_FIXED: 4,
  5128. Z_DEFAULT_STRATEGY: 0,
  5129. /* Possible values of the data_type field (though see inflate()) */
  5130. Z_BINARY: 0,
  5131. Z_TEXT: 1,
  5132. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  5133. Z_UNKNOWN: 2,
  5134. /* The deflate compression method */
  5135. Z_DEFLATED: 8
  5136. //Z_NULL: null // Use -1 or null inline, depending on var type
  5137. };
  5138. },{}],45:[function(require,module,exports){
  5139. 'use strict';
  5140. // Note: we can't get significant speed boost here.
  5141. // So write code to minimize size - no pregenerated tables
  5142. // and array tools dependencies.
  5143. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5144. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5145. //
  5146. // This software is provided 'as-is', without any express or implied
  5147. // warranty. In no event will the authors be held liable for any damages
  5148. // arising from the use of this software.
  5149. //
  5150. // Permission is granted to anyone to use this software for any purpose,
  5151. // including commercial applications, and to alter it and redistribute it
  5152. // freely, subject to the following restrictions:
  5153. //
  5154. // 1. The origin of this software must not be misrepresented; you must not
  5155. // claim that you wrote the original software. If you use this software
  5156. // in a product, an acknowledgment in the product documentation would be
  5157. // appreciated but is not required.
  5158. // 2. Altered source versions must be plainly marked as such, and must not be
  5159. // misrepresented as being the original software.
  5160. // 3. This notice may not be removed or altered from any source distribution.
  5161. // Use ordinary array, since untyped makes no boost here
  5162. function makeTable() {
  5163. var c, table = [];
  5164. for (var n = 0; n < 256; n++) {
  5165. c = n;
  5166. for (var k = 0; k < 8; k++) {
  5167. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  5168. }
  5169. table[n] = c;
  5170. }
  5171. return table;
  5172. }
  5173. // Create table on load. Just 255 signed longs. Not a problem.
  5174. var crcTable = makeTable();
  5175. function crc32(crc, buf, len, pos) {
  5176. var t = crcTable,
  5177. end = pos + len;
  5178. crc ^= -1;
  5179. for (var i = pos; i < end; i++) {
  5180. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  5181. }
  5182. return (crc ^ (-1)); // >>> 0;
  5183. }
  5184. module.exports = crc32;
  5185. },{}],46:[function(require,module,exports){
  5186. 'use strict';
  5187. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  5188. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  5189. //
  5190. // This software is provided 'as-is', without any express or implied
  5191. // warranty. In no event will the authors be held liable for any damages
  5192. // arising from the use of this software.
  5193. //
  5194. // Permission is granted to anyone to use this software for any purpose,
  5195. // including commercial applications, and to alter it and redistribute it
  5196. // freely, subject to the following restrictions:
  5197. //
  5198. // 1. The origin of this software must not be misrepresented; you must not
  5199. // claim that you wrote the original software. If you use this software
  5200. // in a product, an acknowledgment in the product documentation would be
  5201. // appreciated but is not required.
  5202. // 2. Altered source versions must be plainly marked as such, and must not be
  5203. // misrepresented as being the original software.
  5204. // 3. This notice may not be removed or altered from any source distribution.
  5205. var utils = require('../utils/common');
  5206. var trees = require('./trees');
  5207. var adler32 = require('./adler32');
  5208. var crc32 = require('./crc32');
  5209. var msg = require('./messages');
  5210. /* Public constants ==========================================================*/
  5211. /* ===========================================================================*/
  5212. /* Allowed flush values; see deflate() and inflate() below for details */
  5213. var Z_NO_FLUSH = 0;
  5214. var Z_PARTIAL_FLUSH = 1;
  5215. //var Z_SYNC_FLUSH = 2;
  5216. var Z_FULL_FLUSH = 3;
  5217. var Z_FINISH = 4;
  5218. var Z_BLOCK = 5;
  5219. //var Z_TREES = 6;
  5220. /* Return codes for the compression/decompression functions. Negative values
  5221. * are errors, positive values are used for special but normal events.
  5222. */
  5223. var Z_OK = 0;
  5224. var Z_STREAM_END = 1;
  5225. //var Z_NEED_DICT = 2;
  5226. //var Z_ERRNO = -1;
  5227. var Z_STREAM_ERROR = -2;
  5228. var Z_DATA_ERROR = -3;
  5229. //var Z_MEM_ERROR = -4;
  5230. var Z_BUF_ERROR = -5;
  5231. //var Z_VERSION_ERROR = -6;
  5232. /* compression levels */
  5233. //var Z_NO_COMPRESSION = 0;
  5234. //var Z_BEST_SPEED = 1;
  5235. //var Z_BEST_COMPRESSION = 9;
  5236. var Z_DEFAULT_COMPRESSION = -1;
  5237. var Z_FILTERED = 1;
  5238. var Z_HUFFMAN_ONLY = 2;
  5239. var Z_RLE = 3;
  5240. var Z_FIXED = 4;
  5241. var Z_DEFAULT_STRATEGY = 0;
  5242. /* Possible values of the data_type field (though see inflate()) */
  5243. //var Z_BINARY = 0;
  5244. //var Z_TEXT = 1;
  5245. //var Z_ASCII = 1; // = Z_TEXT
  5246. var Z_UNKNOWN = 2;
  5247. /* The deflate compression method */
  5248. var Z_DEFLATED = 8;
  5249. /*============================================================================*/
  5250. var MAX_MEM_LEVEL = 9;
  5251. /* Maximum value for memLevel in deflateInit2 */
  5252. var MAX_WBITS = 15;
  5253. /* 32K LZ77 window */
  5254. var DEF_MEM_LEVEL = 8;
  5255. var LENGTH_CODES = 29;
  5256. /* number of length codes, not counting the special END_BLOCK code */
  5257. var LITERALS = 256;
  5258. /* number of literal bytes 0..255 */
  5259. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  5260. /* number of Literal or Length codes, including the END_BLOCK code */
  5261. var D_CODES = 30;
  5262. /* number of distance codes */
  5263. var BL_CODES = 19;
  5264. /* number of codes used to transfer the bit lengths */
  5265. var HEAP_SIZE = 2 * L_CODES + 1;
  5266. /* maximum heap size */
  5267. var MAX_BITS = 15;
  5268. /* All codes must not exceed MAX_BITS bits */
  5269. var MIN_MATCH = 3;
  5270. var MAX_MATCH = 258;
  5271. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  5272. var PRESET_DICT = 0x20;
  5273. var INIT_STATE = 42;
  5274. var EXTRA_STATE = 69;
  5275. var NAME_STATE = 73;
  5276. var COMMENT_STATE = 91;
  5277. var HCRC_STATE = 103;
  5278. var BUSY_STATE = 113;
  5279. var FINISH_STATE = 666;
  5280. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  5281. var BS_BLOCK_DONE = 2; /* block flush performed */
  5282. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  5283. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  5284. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  5285. function err(strm, errorCode) {
  5286. strm.msg = msg[errorCode];
  5287. return errorCode;
  5288. }
  5289. function rank(f) {
  5290. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  5291. }
  5292. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  5293. /* =========================================================================
  5294. * Flush as much pending output as possible. All deflate() output goes
  5295. * through this function so some applications may wish to modify it
  5296. * to avoid allocating a large strm->output buffer and copying into it.
  5297. * (See also read_buf()).
  5298. */
  5299. function flush_pending(strm) {
  5300. var s = strm.state;
  5301. //_tr_flush_bits(s);
  5302. var len = s.pending;
  5303. if (len > strm.avail_out) {
  5304. len = strm.avail_out;
  5305. }
  5306. if (len === 0) { return; }
  5307. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  5308. strm.next_out += len;
  5309. s.pending_out += len;
  5310. strm.total_out += len;
  5311. strm.avail_out -= len;
  5312. s.pending -= len;
  5313. if (s.pending === 0) {
  5314. s.pending_out = 0;
  5315. }
  5316. }
  5317. function flush_block_only(s, last) {
  5318. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  5319. s.block_start = s.strstart;
  5320. flush_pending(s.strm);
  5321. }
  5322. function put_byte(s, b) {
  5323. s.pending_buf[s.pending++] = b;
  5324. }
  5325. /* =========================================================================
  5326. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  5327. * IN assertion: the stream state is correct and there is enough room in
  5328. * pending_buf.
  5329. */
  5330. function putShortMSB(s, b) {
  5331. // put_byte(s, (Byte)(b >> 8));
  5332. // put_byte(s, (Byte)(b & 0xff));
  5333. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  5334. s.pending_buf[s.pending++] = b & 0xff;
  5335. }
  5336. /* ===========================================================================
  5337. * Read a new buffer from the current input stream, update the adler32
  5338. * and total number of bytes read. All deflate() input goes through
  5339. * this function so some applications may wish to modify it to avoid
  5340. * allocating a large strm->input buffer and copying from it.
  5341. * (See also flush_pending()).
  5342. */
  5343. function read_buf(strm, buf, start, size) {
  5344. var len = strm.avail_in;
  5345. if (len > size) { len = size; }
  5346. if (len === 0) { return 0; }
  5347. strm.avail_in -= len;
  5348. // zmemcpy(buf, strm->next_in, len);
  5349. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  5350. if (strm.state.wrap === 1) {
  5351. strm.adler = adler32(strm.adler, buf, len, start);
  5352. }
  5353. else if (strm.state.wrap === 2) {
  5354. strm.adler = crc32(strm.adler, buf, len, start);
  5355. }
  5356. strm.next_in += len;
  5357. strm.total_in += len;
  5358. return len;
  5359. }
  5360. /* ===========================================================================
  5361. * Set match_start to the longest match starting at the given string and
  5362. * return its length. Matches shorter or equal to prev_length are discarded,
  5363. * in which case the result is equal to prev_length and match_start is
  5364. * garbage.
  5365. * IN assertions: cur_match is the head of the hash chain for the current
  5366. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  5367. * OUT assertion: the match length is not greater than s->lookahead.
  5368. */
  5369. function longest_match(s, cur_match) {
  5370. var chain_length = s.max_chain_length; /* max hash chain length */
  5371. var scan = s.strstart; /* current string */
  5372. var match; /* matched string */
  5373. var len; /* length of current match */
  5374. var best_len = s.prev_length; /* best match length so far */
  5375. var nice_match = s.nice_match; /* stop if match long enough */
  5376. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  5377. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  5378. var _win = s.window; // shortcut
  5379. var wmask = s.w_mask;
  5380. var prev = s.prev;
  5381. /* Stop when cur_match becomes <= limit. To simplify the code,
  5382. * we prevent matches with the string of window index 0.
  5383. */
  5384. var strend = s.strstart + MAX_MATCH;
  5385. var scan_end1 = _win[scan + best_len - 1];
  5386. var scan_end = _win[scan + best_len];
  5387. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  5388. * It is easy to get rid of this optimization if necessary.
  5389. */
  5390. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  5391. /* Do not waste too much time if we already have a good match: */
  5392. if (s.prev_length >= s.good_match) {
  5393. chain_length >>= 2;
  5394. }
  5395. /* Do not look for matches beyond the end of the input. This is necessary
  5396. * to make deflate deterministic.
  5397. */
  5398. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  5399. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  5400. do {
  5401. // Assert(cur_match < s->strstart, "no future");
  5402. match = cur_match;
  5403. /* Skip to next match if the match length cannot increase
  5404. * or if the match length is less than 2. Note that the checks below
  5405. * for insufficient lookahead only occur occasionally for performance
  5406. * reasons. Therefore uninitialized memory will be accessed, and
  5407. * conditional jumps will be made that depend on those values.
  5408. * However the length of the match is limited to the lookahead, so
  5409. * the output of deflate is not affected by the uninitialized values.
  5410. */
  5411. if (_win[match + best_len] !== scan_end ||
  5412. _win[match + best_len - 1] !== scan_end1 ||
  5413. _win[match] !== _win[scan] ||
  5414. _win[++match] !== _win[scan + 1]) {
  5415. continue;
  5416. }
  5417. /* The check at best_len-1 can be removed because it will be made
  5418. * again later. (This heuristic is not always a win.)
  5419. * It is not necessary to compare scan[2] and match[2] since they
  5420. * are always equal when the other bytes match, given that
  5421. * the hash keys are equal and that HASH_BITS >= 8.
  5422. */
  5423. scan += 2;
  5424. match++;
  5425. // Assert(*scan == *match, "match[2]?");
  5426. /* We check for insufficient lookahead only every 8th comparison;
  5427. * the 256th check will be made at strstart+258.
  5428. */
  5429. do {
  5430. /*jshint noempty:false*/
  5431. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  5432. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  5433. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  5434. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  5435. scan < strend);
  5436. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  5437. len = MAX_MATCH - (strend - scan);
  5438. scan = strend - MAX_MATCH;
  5439. if (len > best_len) {
  5440. s.match_start = cur_match;
  5441. best_len = len;
  5442. if (len >= nice_match) {
  5443. break;
  5444. }
  5445. scan_end1 = _win[scan + best_len - 1];
  5446. scan_end = _win[scan + best_len];
  5447. }
  5448. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  5449. if (best_len <= s.lookahead) {
  5450. return best_len;
  5451. }
  5452. return s.lookahead;
  5453. }
  5454. /* ===========================================================================
  5455. * Fill the window when the lookahead becomes insufficient.
  5456. * Updates strstart and lookahead.
  5457. *
  5458. * IN assertion: lookahead < MIN_LOOKAHEAD
  5459. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  5460. * At least one byte has been read, or avail_in == 0; reads are
  5461. * performed for at least two bytes (required for the zip translate_eol
  5462. * option -- not supported here).
  5463. */
  5464. function fill_window(s) {
  5465. var _w_size = s.w_size;
  5466. var p, n, m, more, str;
  5467. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  5468. do {
  5469. more = s.window_size - s.lookahead - s.strstart;
  5470. // JS ints have 32 bit, block below not needed
  5471. /* Deal with !@#$% 64K limit: */
  5472. //if (sizeof(int) <= 2) {
  5473. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  5474. // more = wsize;
  5475. //
  5476. // } else if (more == (unsigned)(-1)) {
  5477. // /* Very unlikely, but possible on 16 bit machine if
  5478. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  5479. // */
  5480. // more--;
  5481. // }
  5482. //}
  5483. /* If the window is almost full and there is insufficient lookahead,
  5484. * move the upper half to the lower one to make room in the upper half.
  5485. */
  5486. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  5487. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  5488. s.match_start -= _w_size;
  5489. s.strstart -= _w_size;
  5490. /* we now have strstart >= MAX_DIST */
  5491. s.block_start -= _w_size;
  5492. /* Slide the hash table (could be avoided with 32 bit values
  5493. at the expense of memory usage). We slide even when level == 0
  5494. to keep the hash table consistent if we switch back to level > 0
  5495. later. (Using level 0 permanently is not an optimal usage of
  5496. zlib, so we don't care about this pathological case.)
  5497. */
  5498. n = s.hash_size;
  5499. p = n;
  5500. do {
  5501. m = s.head[--p];
  5502. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  5503. } while (--n);
  5504. n = _w_size;
  5505. p = n;
  5506. do {
  5507. m = s.prev[--p];
  5508. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  5509. /* If n is not on any hash chain, prev[n] is garbage but
  5510. * its value will never be used.
  5511. */
  5512. } while (--n);
  5513. more += _w_size;
  5514. }
  5515. if (s.strm.avail_in === 0) {
  5516. break;
  5517. }
  5518. /* If there was no sliding:
  5519. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  5520. * more == window_size - lookahead - strstart
  5521. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  5522. * => more >= window_size - 2*WSIZE + 2
  5523. * In the BIG_MEM or MMAP case (not yet supported),
  5524. * window_size == input_size + MIN_LOOKAHEAD &&
  5525. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  5526. * Otherwise, window_size == 2*WSIZE so more >= 2.
  5527. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  5528. */
  5529. //Assert(more >= 2, "more < 2");
  5530. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  5531. s.lookahead += n;
  5532. /* Initialize the hash value now that we have some input: */
  5533. if (s.lookahead + s.insert >= MIN_MATCH) {
  5534. str = s.strstart - s.insert;
  5535. s.ins_h = s.window[str];
  5536. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  5537. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  5538. //#if MIN_MATCH != 3
  5539. // Call update_hash() MIN_MATCH-3 more times
  5540. //#endif
  5541. while (s.insert) {
  5542. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  5543. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  5544. s.prev[str & s.w_mask] = s.head[s.ins_h];
  5545. s.head[s.ins_h] = str;
  5546. str++;
  5547. s.insert--;
  5548. if (s.lookahead + s.insert < MIN_MATCH) {
  5549. break;
  5550. }
  5551. }
  5552. }
  5553. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  5554. * but this is not important since only literal bytes will be emitted.
  5555. */
  5556. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  5557. /* If the WIN_INIT bytes after the end of the current data have never been
  5558. * written, then zero those bytes in order to avoid memory check reports of
  5559. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  5560. * the longest match routines. Update the high water mark for the next
  5561. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  5562. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  5563. */
  5564. // if (s.high_water < s.window_size) {
  5565. // var curr = s.strstart + s.lookahead;
  5566. // var init = 0;
  5567. //
  5568. // if (s.high_water < curr) {
  5569. // /* Previous high water mark below current data -- zero WIN_INIT
  5570. // * bytes or up to end of window, whichever is less.
  5571. // */
  5572. // init = s.window_size - curr;
  5573. // if (init > WIN_INIT)
  5574. // init = WIN_INIT;
  5575. // zmemzero(s->window + curr, (unsigned)init);
  5576. // s->high_water = curr + init;
  5577. // }
  5578. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  5579. // /* High water mark at or above current data, but below current data
  5580. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  5581. // * to end of window, whichever is less.
  5582. // */
  5583. // init = (ulg)curr + WIN_INIT - s->high_water;
  5584. // if (init > s->window_size - s->high_water)
  5585. // init = s->window_size - s->high_water;
  5586. // zmemzero(s->window + s->high_water, (unsigned)init);
  5587. // s->high_water += init;
  5588. // }
  5589. // }
  5590. //
  5591. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  5592. // "not enough room for search");
  5593. }
  5594. /* ===========================================================================
  5595. * Copy without compression as much as possible from the input stream, return
  5596. * the current block state.
  5597. * This function does not insert new strings in the dictionary since
  5598. * uncompressible data is probably not useful. This function is used
  5599. * only for the level=0 compression option.
  5600. * NOTE: this function should be optimized to avoid extra copying from
  5601. * window to pending_buf.
  5602. */
  5603. function deflate_stored(s, flush) {
  5604. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  5605. * to pending_buf_size, and each stored block has a 5 byte header:
  5606. */
  5607. var max_block_size = 0xffff;
  5608. if (max_block_size > s.pending_buf_size - 5) {
  5609. max_block_size = s.pending_buf_size - 5;
  5610. }
  5611. /* Copy as much as possible from input to output: */
  5612. for (;;) {
  5613. /* Fill the window as much as possible: */
  5614. if (s.lookahead <= 1) {
  5615. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  5616. // s->block_start >= (long)s->w_size, "slide too late");
  5617. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  5618. // s.block_start >= s.w_size)) {
  5619. // throw new Error("slide too late");
  5620. // }
  5621. fill_window(s);
  5622. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  5623. return BS_NEED_MORE;
  5624. }
  5625. if (s.lookahead === 0) {
  5626. break;
  5627. }
  5628. /* flush the current block */
  5629. }
  5630. //Assert(s->block_start >= 0L, "block gone");
  5631. // if (s.block_start < 0) throw new Error("block gone");
  5632. s.strstart += s.lookahead;
  5633. s.lookahead = 0;
  5634. /* Emit a stored block if pending_buf will be full: */
  5635. var max_start = s.block_start + max_block_size;
  5636. if (s.strstart === 0 || s.strstart >= max_start) {
  5637. /* strstart == 0 is possible when wraparound on 16-bit machine */
  5638. s.lookahead = s.strstart - max_start;
  5639. s.strstart = max_start;
  5640. /*** FLUSH_BLOCK(s, 0); ***/
  5641. flush_block_only(s, false);
  5642. if (s.strm.avail_out === 0) {
  5643. return BS_NEED_MORE;
  5644. }
  5645. /***/
  5646. }
  5647. /* Flush if we may have to slide, otherwise block_start may become
  5648. * negative and the data will be gone:
  5649. */
  5650. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  5651. /*** FLUSH_BLOCK(s, 0); ***/
  5652. flush_block_only(s, false);
  5653. if (s.strm.avail_out === 0) {
  5654. return BS_NEED_MORE;
  5655. }
  5656. /***/
  5657. }
  5658. }
  5659. s.insert = 0;
  5660. if (flush === Z_FINISH) {
  5661. /*** FLUSH_BLOCK(s, 1); ***/
  5662. flush_block_only(s, true);
  5663. if (s.strm.avail_out === 0) {
  5664. return BS_FINISH_STARTED;
  5665. }
  5666. /***/
  5667. return BS_FINISH_DONE;
  5668. }
  5669. if (s.strstart > s.block_start) {
  5670. /*** FLUSH_BLOCK(s, 0); ***/
  5671. flush_block_only(s, false);
  5672. if (s.strm.avail_out === 0) {
  5673. return BS_NEED_MORE;
  5674. }
  5675. /***/
  5676. }
  5677. return BS_NEED_MORE;
  5678. }
  5679. /* ===========================================================================
  5680. * Compress as much as possible from the input stream, return the current
  5681. * block state.
  5682. * This function does not perform lazy evaluation of matches and inserts
  5683. * new strings in the dictionary only for unmatched strings or for short
  5684. * matches. It is used only for the fast compression options.
  5685. */
  5686. function deflate_fast(s, flush) {
  5687. var hash_head; /* head of the hash chain */
  5688. var bflush; /* set if current block must be flushed */
  5689. for (;;) {
  5690. /* Make sure that we always have enough lookahead, except
  5691. * at the end of the input file. We need MAX_MATCH bytes
  5692. * for the next match, plus MIN_MATCH bytes to insert the
  5693. * string following the next match.
  5694. */
  5695. if (s.lookahead < MIN_LOOKAHEAD) {
  5696. fill_window(s);
  5697. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  5698. return BS_NEED_MORE;
  5699. }
  5700. if (s.lookahead === 0) {
  5701. break; /* flush the current block */
  5702. }
  5703. }
  5704. /* Insert the string window[strstart .. strstart+2] in the
  5705. * dictionary, and set hash_head to the head of the hash chain:
  5706. */
  5707. hash_head = 0/*NIL*/;
  5708. if (s.lookahead >= MIN_MATCH) {
  5709. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  5710. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  5711. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  5712. s.head[s.ins_h] = s.strstart;
  5713. /***/
  5714. }
  5715. /* Find the longest match, discarding those <= prev_length.
  5716. * At this point we have always match_length < MIN_MATCH
  5717. */
  5718. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  5719. /* To simplify the code, we prevent matches with the string
  5720. * of window index 0 (in particular we have to avoid a match
  5721. * of the string with itself at the start of the input file).
  5722. */
  5723. s.match_length = longest_match(s, hash_head);
  5724. /* longest_match() sets match_start */
  5725. }
  5726. if (s.match_length >= MIN_MATCH) {
  5727. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  5728. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  5729. s.match_length - MIN_MATCH, bflush); ***/
  5730. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  5731. s.lookahead -= s.match_length;
  5732. /* Insert new strings in the hash table only if the match length
  5733. * is not too large. This saves time but degrades compression.
  5734. */
  5735. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  5736. s.match_length--; /* string at strstart already in table */
  5737. do {
  5738. s.strstart++;
  5739. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  5740. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  5741. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  5742. s.head[s.ins_h] = s.strstart;
  5743. /***/
  5744. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  5745. * always MIN_MATCH bytes ahead.
  5746. */
  5747. } while (--s.match_length !== 0);
  5748. s.strstart++;
  5749. } else
  5750. {
  5751. s.strstart += s.match_length;
  5752. s.match_length = 0;
  5753. s.ins_h = s.window[s.strstart];
  5754. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  5755. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  5756. //#if MIN_MATCH != 3
  5757. // Call UPDATE_HASH() MIN_MATCH-3 more times
  5758. //#endif
  5759. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  5760. * matter since it will be recomputed at next deflate call.
  5761. */
  5762. }
  5763. } else {
  5764. /* No match, output a literal byte */
  5765. //Tracevv((stderr,"%c", s.window[s.strstart]));
  5766. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  5767. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  5768. s.lookahead--;
  5769. s.strstart++;
  5770. }
  5771. if (bflush) {
  5772. /*** FLUSH_BLOCK(s, 0); ***/
  5773. flush_block_only(s, false);
  5774. if (s.strm.avail_out === 0) {
  5775. return BS_NEED_MORE;
  5776. }
  5777. /***/
  5778. }
  5779. }
  5780. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  5781. if (flush === Z_FINISH) {
  5782. /*** FLUSH_BLOCK(s, 1); ***/
  5783. flush_block_only(s, true);
  5784. if (s.strm.avail_out === 0) {
  5785. return BS_FINISH_STARTED;
  5786. }
  5787. /***/
  5788. return BS_FINISH_DONE;
  5789. }
  5790. if (s.last_lit) {
  5791. /*** FLUSH_BLOCK(s, 0); ***/
  5792. flush_block_only(s, false);
  5793. if (s.strm.avail_out === 0) {
  5794. return BS_NEED_MORE;
  5795. }
  5796. /***/
  5797. }
  5798. return BS_BLOCK_DONE;
  5799. }
  5800. /* ===========================================================================
  5801. * Same as above, but achieves better compression. We use a lazy
  5802. * evaluation for matches: a match is finally adopted only if there is
  5803. * no better match at the next window position.
  5804. */
  5805. function deflate_slow(s, flush) {
  5806. var hash_head; /* head of hash chain */
  5807. var bflush; /* set if current block must be flushed */
  5808. var max_insert;
  5809. /* Process the input block. */
  5810. for (;;) {
  5811. /* Make sure that we always have enough lookahead, except
  5812. * at the end of the input file. We need MAX_MATCH bytes
  5813. * for the next match, plus MIN_MATCH bytes to insert the
  5814. * string following the next match.
  5815. */
  5816. if (s.lookahead < MIN_LOOKAHEAD) {
  5817. fill_window(s);
  5818. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  5819. return BS_NEED_MORE;
  5820. }
  5821. if (s.lookahead === 0) { break; } /* flush the current block */
  5822. }
  5823. /* Insert the string window[strstart .. strstart+2] in the
  5824. * dictionary, and set hash_head to the head of the hash chain:
  5825. */
  5826. hash_head = 0/*NIL*/;
  5827. if (s.lookahead >= MIN_MATCH) {
  5828. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  5829. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  5830. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  5831. s.head[s.ins_h] = s.strstart;
  5832. /***/
  5833. }
  5834. /* Find the longest match, discarding those <= prev_length.
  5835. */
  5836. s.prev_length = s.match_length;
  5837. s.prev_match = s.match_start;
  5838. s.match_length = MIN_MATCH - 1;
  5839. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  5840. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  5841. /* To simplify the code, we prevent matches with the string
  5842. * of window index 0 (in particular we have to avoid a match
  5843. * of the string with itself at the start of the input file).
  5844. */
  5845. s.match_length = longest_match(s, hash_head);
  5846. /* longest_match() sets match_start */
  5847. if (s.match_length <= 5 &&
  5848. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  5849. /* If prev_match is also MIN_MATCH, match_start is garbage
  5850. * but we will ignore the current match anyway.
  5851. */
  5852. s.match_length = MIN_MATCH - 1;
  5853. }
  5854. }
  5855. /* If there was a match at the previous step and the current
  5856. * match is not better, output the previous match:
  5857. */
  5858. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  5859. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  5860. /* Do not insert strings in hash table beyond this. */
  5861. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  5862. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  5863. s.prev_length - MIN_MATCH, bflush);***/
  5864. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  5865. /* Insert in hash table all strings up to the end of the match.
  5866. * strstart-1 and strstart are already inserted. If there is not
  5867. * enough lookahead, the last two strings are not inserted in
  5868. * the hash table.
  5869. */
  5870. s.lookahead -= s.prev_length - 1;
  5871. s.prev_length -= 2;
  5872. do {
  5873. if (++s.strstart <= max_insert) {
  5874. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  5875. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  5876. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  5877. s.head[s.ins_h] = s.strstart;
  5878. /***/
  5879. }
  5880. } while (--s.prev_length !== 0);
  5881. s.match_available = 0;
  5882. s.match_length = MIN_MATCH - 1;
  5883. s.strstart++;
  5884. if (bflush) {
  5885. /*** FLUSH_BLOCK(s, 0); ***/
  5886. flush_block_only(s, false);
  5887. if (s.strm.avail_out === 0) {
  5888. return BS_NEED_MORE;
  5889. }
  5890. /***/
  5891. }
  5892. } else if (s.match_available) {
  5893. /* If there was no match at the previous position, output a
  5894. * single literal. If there was a match but the current match
  5895. * is longer, truncate the previous match to a single literal.
  5896. */
  5897. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  5898. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  5899. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  5900. if (bflush) {
  5901. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  5902. flush_block_only(s, false);
  5903. /***/
  5904. }
  5905. s.strstart++;
  5906. s.lookahead--;
  5907. if (s.strm.avail_out === 0) {
  5908. return BS_NEED_MORE;
  5909. }
  5910. } else {
  5911. /* There is no previous match to compare with, wait for
  5912. * the next step to decide.
  5913. */
  5914. s.match_available = 1;
  5915. s.strstart++;
  5916. s.lookahead--;
  5917. }
  5918. }
  5919. //Assert (flush != Z_NO_FLUSH, "no flush?");
  5920. if (s.match_available) {
  5921. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  5922. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  5923. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  5924. s.match_available = 0;
  5925. }
  5926. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  5927. if (flush === Z_FINISH) {
  5928. /*** FLUSH_BLOCK(s, 1); ***/
  5929. flush_block_only(s, true);
  5930. if (s.strm.avail_out === 0) {
  5931. return BS_FINISH_STARTED;
  5932. }
  5933. /***/
  5934. return BS_FINISH_DONE;
  5935. }
  5936. if (s.last_lit) {
  5937. /*** FLUSH_BLOCK(s, 0); ***/
  5938. flush_block_only(s, false);
  5939. if (s.strm.avail_out === 0) {
  5940. return BS_NEED_MORE;
  5941. }
  5942. /***/
  5943. }
  5944. return BS_BLOCK_DONE;
  5945. }
  5946. /* ===========================================================================
  5947. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  5948. * one. Do not maintain a hash table. (It will be regenerated if this run of
  5949. * deflate switches away from Z_RLE.)
  5950. */
  5951. function deflate_rle(s, flush) {
  5952. var bflush; /* set if current block must be flushed */
  5953. var prev; /* byte at distance one to match */
  5954. var scan, strend; /* scan goes up to strend for length of run */
  5955. var _win = s.window;
  5956. for (;;) {
  5957. /* Make sure that we always have enough lookahead, except
  5958. * at the end of the input file. We need MAX_MATCH bytes
  5959. * for the longest run, plus one for the unrolled loop.
  5960. */
  5961. if (s.lookahead <= MAX_MATCH) {
  5962. fill_window(s);
  5963. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  5964. return BS_NEED_MORE;
  5965. }
  5966. if (s.lookahead === 0) { break; } /* flush the current block */
  5967. }
  5968. /* See how many times the previous byte repeats */
  5969. s.match_length = 0;
  5970. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  5971. scan = s.strstart - 1;
  5972. prev = _win[scan];
  5973. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  5974. strend = s.strstart + MAX_MATCH;
  5975. do {
  5976. /*jshint noempty:false*/
  5977. } while (prev === _win[++scan] && prev === _win[++scan] &&
  5978. prev === _win[++scan] && prev === _win[++scan] &&
  5979. prev === _win[++scan] && prev === _win[++scan] &&
  5980. prev === _win[++scan] && prev === _win[++scan] &&
  5981. scan < strend);
  5982. s.match_length = MAX_MATCH - (strend - scan);
  5983. if (s.match_length > s.lookahead) {
  5984. s.match_length = s.lookahead;
  5985. }
  5986. }
  5987. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  5988. }
  5989. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  5990. if (s.match_length >= MIN_MATCH) {
  5991. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  5992. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  5993. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  5994. s.lookahead -= s.match_length;
  5995. s.strstart += s.match_length;
  5996. s.match_length = 0;
  5997. } else {
  5998. /* No match, output a literal byte */
  5999. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6000. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6001. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6002. s.lookahead--;
  6003. s.strstart++;
  6004. }
  6005. if (bflush) {
  6006. /*** FLUSH_BLOCK(s, 0); ***/
  6007. flush_block_only(s, false);
  6008. if (s.strm.avail_out === 0) {
  6009. return BS_NEED_MORE;
  6010. }
  6011. /***/
  6012. }
  6013. }
  6014. s.insert = 0;
  6015. if (flush === Z_FINISH) {
  6016. /*** FLUSH_BLOCK(s, 1); ***/
  6017. flush_block_only(s, true);
  6018. if (s.strm.avail_out === 0) {
  6019. return BS_FINISH_STARTED;
  6020. }
  6021. /***/
  6022. return BS_FINISH_DONE;
  6023. }
  6024. if (s.last_lit) {
  6025. /*** FLUSH_BLOCK(s, 0); ***/
  6026. flush_block_only(s, false);
  6027. if (s.strm.avail_out === 0) {
  6028. return BS_NEED_MORE;
  6029. }
  6030. /***/
  6031. }
  6032. return BS_BLOCK_DONE;
  6033. }
  6034. /* ===========================================================================
  6035. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  6036. * (It will be regenerated if this run of deflate switches away from Huffman.)
  6037. */
  6038. function deflate_huff(s, flush) {
  6039. var bflush; /* set if current block must be flushed */
  6040. for (;;) {
  6041. /* Make sure that we have a literal to write. */
  6042. if (s.lookahead === 0) {
  6043. fill_window(s);
  6044. if (s.lookahead === 0) {
  6045. if (flush === Z_NO_FLUSH) {
  6046. return BS_NEED_MORE;
  6047. }
  6048. break; /* flush the current block */
  6049. }
  6050. }
  6051. /* Output a literal byte */
  6052. s.match_length = 0;
  6053. //Tracevv((stderr,"%c", s->window[s->strstart]));
  6054. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  6055. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  6056. s.lookahead--;
  6057. s.strstart++;
  6058. if (bflush) {
  6059. /*** FLUSH_BLOCK(s, 0); ***/
  6060. flush_block_only(s, false);
  6061. if (s.strm.avail_out === 0) {
  6062. return BS_NEED_MORE;
  6063. }
  6064. /***/
  6065. }
  6066. }
  6067. s.insert = 0;
  6068. if (flush === Z_FINISH) {
  6069. /*** FLUSH_BLOCK(s, 1); ***/
  6070. flush_block_only(s, true);
  6071. if (s.strm.avail_out === 0) {
  6072. return BS_FINISH_STARTED;
  6073. }
  6074. /***/
  6075. return BS_FINISH_DONE;
  6076. }
  6077. if (s.last_lit) {
  6078. /*** FLUSH_BLOCK(s, 0); ***/
  6079. flush_block_only(s, false);
  6080. if (s.strm.avail_out === 0) {
  6081. return BS_NEED_MORE;
  6082. }
  6083. /***/
  6084. }
  6085. return BS_BLOCK_DONE;
  6086. }
  6087. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  6088. * the desired pack level (0..9). The values given below have been tuned to
  6089. * exclude worst case performance for pathological files. Better values may be
  6090. * found for specific files.
  6091. */
  6092. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  6093. this.good_length = good_length;
  6094. this.max_lazy = max_lazy;
  6095. this.nice_length = nice_length;
  6096. this.max_chain = max_chain;
  6097. this.func = func;
  6098. }
  6099. var configuration_table;
  6100. configuration_table = [
  6101. /* good lazy nice chain */
  6102. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  6103. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  6104. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  6105. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  6106. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  6107. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  6108. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  6109. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  6110. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  6111. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  6112. ];
  6113. /* ===========================================================================
  6114. * Initialize the "longest match" routines for a new zlib stream
  6115. */
  6116. function lm_init(s) {
  6117. s.window_size = 2 * s.w_size;
  6118. /*** CLEAR_HASH(s); ***/
  6119. zero(s.head); // Fill with NIL (= 0);
  6120. /* Set the default configuration parameters:
  6121. */
  6122. s.max_lazy_match = configuration_table[s.level].max_lazy;
  6123. s.good_match = configuration_table[s.level].good_length;
  6124. s.nice_match = configuration_table[s.level].nice_length;
  6125. s.max_chain_length = configuration_table[s.level].max_chain;
  6126. s.strstart = 0;
  6127. s.block_start = 0;
  6128. s.lookahead = 0;
  6129. s.insert = 0;
  6130. s.match_length = s.prev_length = MIN_MATCH - 1;
  6131. s.match_available = 0;
  6132. s.ins_h = 0;
  6133. }
  6134. function DeflateState() {
  6135. this.strm = null; /* pointer back to this zlib stream */
  6136. this.status = 0; /* as the name implies */
  6137. this.pending_buf = null; /* output still pending */
  6138. this.pending_buf_size = 0; /* size of pending_buf */
  6139. this.pending_out = 0; /* next pending byte to output to the stream */
  6140. this.pending = 0; /* nb of bytes in the pending buffer */
  6141. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  6142. this.gzhead = null; /* gzip header information to write */
  6143. this.gzindex = 0; /* where in extra, name, or comment */
  6144. this.method = Z_DEFLATED; /* can only be DEFLATED */
  6145. this.last_flush = -1; /* value of flush param for previous deflate call */
  6146. this.w_size = 0; /* LZ77 window size (32K by default) */
  6147. this.w_bits = 0; /* log2(w_size) (8..16) */
  6148. this.w_mask = 0; /* w_size - 1 */
  6149. this.window = null;
  6150. /* Sliding window. Input bytes are read into the second half of the window,
  6151. * and move to the first half later to keep a dictionary of at least wSize
  6152. * bytes. With this organization, matches are limited to a distance of
  6153. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  6154. * performed with a length multiple of the block size.
  6155. */
  6156. this.window_size = 0;
  6157. /* Actual size of window: 2*wSize, except when the user input buffer
  6158. * is directly used as sliding window.
  6159. */
  6160. this.prev = null;
  6161. /* Link to older string with same hash index. To limit the size of this
  6162. * array to 64K, this link is maintained only for the last 32K strings.
  6163. * An index in this array is thus a window index modulo 32K.
  6164. */
  6165. this.head = null; /* Heads of the hash chains or NIL. */
  6166. this.ins_h = 0; /* hash index of string to be inserted */
  6167. this.hash_size = 0; /* number of elements in hash table */
  6168. this.hash_bits = 0; /* log2(hash_size) */
  6169. this.hash_mask = 0; /* hash_size-1 */
  6170. this.hash_shift = 0;
  6171. /* Number of bits by which ins_h must be shifted at each input
  6172. * step. It must be such that after MIN_MATCH steps, the oldest
  6173. * byte no longer takes part in the hash key, that is:
  6174. * hash_shift * MIN_MATCH >= hash_bits
  6175. */
  6176. this.block_start = 0;
  6177. /* Window position at the beginning of the current output block. Gets
  6178. * negative when the window is moved backwards.
  6179. */
  6180. this.match_length = 0; /* length of best match */
  6181. this.prev_match = 0; /* previous match */
  6182. this.match_available = 0; /* set if previous match exists */
  6183. this.strstart = 0; /* start of string to insert */
  6184. this.match_start = 0; /* start of matching string */
  6185. this.lookahead = 0; /* number of valid bytes ahead in window */
  6186. this.prev_length = 0;
  6187. /* Length of the best match at previous step. Matches not greater than this
  6188. * are discarded. This is used in the lazy match evaluation.
  6189. */
  6190. this.max_chain_length = 0;
  6191. /* To speed up deflation, hash chains are never searched beyond this
  6192. * length. A higher limit improves compression ratio but degrades the
  6193. * speed.
  6194. */
  6195. this.max_lazy_match = 0;
  6196. /* Attempt to find a better match only when the current match is strictly
  6197. * smaller than this value. This mechanism is used only for compression
  6198. * levels >= 4.
  6199. */
  6200. // That's alias to max_lazy_match, don't use directly
  6201. //this.max_insert_length = 0;
  6202. /* Insert new strings in the hash table only if the match length is not
  6203. * greater than this length. This saves time but degrades compression.
  6204. * max_insert_length is used only for compression levels <= 3.
  6205. */
  6206. this.level = 0; /* compression level (1..9) */
  6207. this.strategy = 0; /* favor or force Huffman coding*/
  6208. this.good_match = 0;
  6209. /* Use a faster search when the previous match is longer than this */
  6210. this.nice_match = 0; /* Stop searching when current match exceeds this */
  6211. /* used by trees.c: */
  6212. /* Didn't use ct_data typedef below to suppress compiler warning */
  6213. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  6214. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  6215. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  6216. // Use flat array of DOUBLE size, with interleaved fata,
  6217. // because JS does not support effective
  6218. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  6219. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  6220. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  6221. zero(this.dyn_ltree);
  6222. zero(this.dyn_dtree);
  6223. zero(this.bl_tree);
  6224. this.l_desc = null; /* desc. for literal tree */
  6225. this.d_desc = null; /* desc. for distance tree */
  6226. this.bl_desc = null; /* desc. for bit length tree */
  6227. //ush bl_count[MAX_BITS+1];
  6228. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  6229. /* number of codes at each bit length for an optimal tree */
  6230. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  6231. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  6232. zero(this.heap);
  6233. this.heap_len = 0; /* number of elements in the heap */
  6234. this.heap_max = 0; /* element of largest frequency */
  6235. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  6236. * The same heap array is used to build all trees.
  6237. */
  6238. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  6239. zero(this.depth);
  6240. /* Depth of each subtree used as tie breaker for trees of equal frequency
  6241. */
  6242. this.l_buf = 0; /* buffer index for literals or lengths */
  6243. this.lit_bufsize = 0;
  6244. /* Size of match buffer for literals/lengths. There are 4 reasons for
  6245. * limiting lit_bufsize to 64K:
  6246. * - frequencies can be kept in 16 bit counters
  6247. * - if compression is not successful for the first block, all input
  6248. * data is still in the window so we can still emit a stored block even
  6249. * when input comes from standard input. (This can also be done for
  6250. * all blocks if lit_bufsize is not greater than 32K.)
  6251. * - if compression is not successful for a file smaller than 64K, we can
  6252. * even emit a stored file instead of a stored block (saving 5 bytes).
  6253. * This is applicable only for zip (not gzip or zlib).
  6254. * - creating new Huffman trees less frequently may not provide fast
  6255. * adaptation to changes in the input data statistics. (Take for
  6256. * example a binary file with poorly compressible code followed by
  6257. * a highly compressible string table.) Smaller buffer sizes give
  6258. * fast adaptation but have of course the overhead of transmitting
  6259. * trees more frequently.
  6260. * - I can't count above 4
  6261. */
  6262. this.last_lit = 0; /* running index in l_buf */
  6263. this.d_buf = 0;
  6264. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  6265. * the same number of elements. To use different lengths, an extra flag
  6266. * array would be necessary.
  6267. */
  6268. this.opt_len = 0; /* bit length of current block with optimal trees */
  6269. this.static_len = 0; /* bit length of current block with static trees */
  6270. this.matches = 0; /* number of string matches in current block */
  6271. this.insert = 0; /* bytes at end of window left to insert */
  6272. this.bi_buf = 0;
  6273. /* Output buffer. bits are inserted starting at the bottom (least
  6274. * significant bits).
  6275. */
  6276. this.bi_valid = 0;
  6277. /* Number of valid bits in bi_buf. All bits above the last valid bit
  6278. * are always zero.
  6279. */
  6280. // Used for window memory init. We safely ignore it for JS. That makes
  6281. // sense only for pointers and memory check tools.
  6282. //this.high_water = 0;
  6283. /* High water mark offset in window for initialized bytes -- bytes above
  6284. * this are set to zero in order to avoid memory check warnings when
  6285. * longest match routines access bytes past the input. This is then
  6286. * updated to the new high water mark.
  6287. */
  6288. }
  6289. function deflateResetKeep(strm) {
  6290. var s;
  6291. if (!strm || !strm.state) {
  6292. return err(strm, Z_STREAM_ERROR);
  6293. }
  6294. strm.total_in = strm.total_out = 0;
  6295. strm.data_type = Z_UNKNOWN;
  6296. s = strm.state;
  6297. s.pending = 0;
  6298. s.pending_out = 0;
  6299. if (s.wrap < 0) {
  6300. s.wrap = -s.wrap;
  6301. /* was made negative by deflate(..., Z_FINISH); */
  6302. }
  6303. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  6304. strm.adler = (s.wrap === 2) ?
  6305. 0 // crc32(0, Z_NULL, 0)
  6306. :
  6307. 1; // adler32(0, Z_NULL, 0)
  6308. s.last_flush = Z_NO_FLUSH;
  6309. trees._tr_init(s);
  6310. return Z_OK;
  6311. }
  6312. function deflateReset(strm) {
  6313. var ret = deflateResetKeep(strm);
  6314. if (ret === Z_OK) {
  6315. lm_init(strm.state);
  6316. }
  6317. return ret;
  6318. }
  6319. function deflateSetHeader(strm, head) {
  6320. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  6321. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  6322. strm.state.gzhead = head;
  6323. return Z_OK;
  6324. }
  6325. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  6326. if (!strm) { // === Z_NULL
  6327. return Z_STREAM_ERROR;
  6328. }
  6329. var wrap = 1;
  6330. if (level === Z_DEFAULT_COMPRESSION) {
  6331. level = 6;
  6332. }
  6333. if (windowBits < 0) { /* suppress zlib wrapper */
  6334. wrap = 0;
  6335. windowBits = -windowBits;
  6336. }
  6337. else if (windowBits > 15) {
  6338. wrap = 2; /* write gzip wrapper instead */
  6339. windowBits -= 16;
  6340. }
  6341. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  6342. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  6343. strategy < 0 || strategy > Z_FIXED) {
  6344. return err(strm, Z_STREAM_ERROR);
  6345. }
  6346. if (windowBits === 8) {
  6347. windowBits = 9;
  6348. }
  6349. /* until 256-byte window bug fixed */
  6350. var s = new DeflateState();
  6351. strm.state = s;
  6352. s.strm = strm;
  6353. s.wrap = wrap;
  6354. s.gzhead = null;
  6355. s.w_bits = windowBits;
  6356. s.w_size = 1 << s.w_bits;
  6357. s.w_mask = s.w_size - 1;
  6358. s.hash_bits = memLevel + 7;
  6359. s.hash_size = 1 << s.hash_bits;
  6360. s.hash_mask = s.hash_size - 1;
  6361. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  6362. s.window = new utils.Buf8(s.w_size * 2);
  6363. s.head = new utils.Buf16(s.hash_size);
  6364. s.prev = new utils.Buf16(s.w_size);
  6365. // Don't need mem init magic for JS.
  6366. //s.high_water = 0; /* nothing written to s->window yet */
  6367. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  6368. s.pending_buf_size = s.lit_bufsize * 4;
  6369. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  6370. //s->pending_buf = (uchf *) overlay;
  6371. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  6372. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  6373. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  6374. s.d_buf = 1 * s.lit_bufsize;
  6375. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  6376. s.l_buf = (1 + 2) * s.lit_bufsize;
  6377. s.level = level;
  6378. s.strategy = strategy;
  6379. s.method = method;
  6380. return deflateReset(strm);
  6381. }
  6382. function deflateInit(strm, level) {
  6383. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  6384. }
  6385. function deflate(strm, flush) {
  6386. var old_flush, s;
  6387. var beg, val; // for gzip header write only
  6388. if (!strm || !strm.state ||
  6389. flush > Z_BLOCK || flush < 0) {
  6390. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  6391. }
  6392. s = strm.state;
  6393. if (!strm.output ||
  6394. (!strm.input && strm.avail_in !== 0) ||
  6395. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  6396. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  6397. }
  6398. s.strm = strm; /* just in case */
  6399. old_flush = s.last_flush;
  6400. s.last_flush = flush;
  6401. /* Write the header */
  6402. if (s.status === INIT_STATE) {
  6403. if (s.wrap === 2) { // GZIP header
  6404. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  6405. put_byte(s, 31);
  6406. put_byte(s, 139);
  6407. put_byte(s, 8);
  6408. if (!s.gzhead) { // s->gzhead == Z_NULL
  6409. put_byte(s, 0);
  6410. put_byte(s, 0);
  6411. put_byte(s, 0);
  6412. put_byte(s, 0);
  6413. put_byte(s, 0);
  6414. put_byte(s, s.level === 9 ? 2 :
  6415. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  6416. 4 : 0));
  6417. put_byte(s, OS_CODE);
  6418. s.status = BUSY_STATE;
  6419. }
  6420. else {
  6421. put_byte(s, (s.gzhead.text ? 1 : 0) +
  6422. (s.gzhead.hcrc ? 2 : 0) +
  6423. (!s.gzhead.extra ? 0 : 4) +
  6424. (!s.gzhead.name ? 0 : 8) +
  6425. (!s.gzhead.comment ? 0 : 16)
  6426. );
  6427. put_byte(s, s.gzhead.time & 0xff);
  6428. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  6429. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  6430. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  6431. put_byte(s, s.level === 9 ? 2 :
  6432. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  6433. 4 : 0));
  6434. put_byte(s, s.gzhead.os & 0xff);
  6435. if (s.gzhead.extra && s.gzhead.extra.length) {
  6436. put_byte(s, s.gzhead.extra.length & 0xff);
  6437. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  6438. }
  6439. if (s.gzhead.hcrc) {
  6440. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  6441. }
  6442. s.gzindex = 0;
  6443. s.status = EXTRA_STATE;
  6444. }
  6445. }
  6446. else // DEFLATE header
  6447. {
  6448. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  6449. var level_flags = -1;
  6450. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  6451. level_flags = 0;
  6452. } else if (s.level < 6) {
  6453. level_flags = 1;
  6454. } else if (s.level === 6) {
  6455. level_flags = 2;
  6456. } else {
  6457. level_flags = 3;
  6458. }
  6459. header |= (level_flags << 6);
  6460. if (s.strstart !== 0) { header |= PRESET_DICT; }
  6461. header += 31 - (header % 31);
  6462. s.status = BUSY_STATE;
  6463. putShortMSB(s, header);
  6464. /* Save the adler32 of the preset dictionary: */
  6465. if (s.strstart !== 0) {
  6466. putShortMSB(s, strm.adler >>> 16);
  6467. putShortMSB(s, strm.adler & 0xffff);
  6468. }
  6469. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  6470. }
  6471. }
  6472. //#ifdef GZIP
  6473. if (s.status === EXTRA_STATE) {
  6474. if (s.gzhead.extra/* != Z_NULL*/) {
  6475. beg = s.pending; /* start of bytes to update crc */
  6476. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  6477. if (s.pending === s.pending_buf_size) {
  6478. if (s.gzhead.hcrc && s.pending > beg) {
  6479. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6480. }
  6481. flush_pending(strm);
  6482. beg = s.pending;
  6483. if (s.pending === s.pending_buf_size) {
  6484. break;
  6485. }
  6486. }
  6487. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  6488. s.gzindex++;
  6489. }
  6490. if (s.gzhead.hcrc && s.pending > beg) {
  6491. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6492. }
  6493. if (s.gzindex === s.gzhead.extra.length) {
  6494. s.gzindex = 0;
  6495. s.status = NAME_STATE;
  6496. }
  6497. }
  6498. else {
  6499. s.status = NAME_STATE;
  6500. }
  6501. }
  6502. if (s.status === NAME_STATE) {
  6503. if (s.gzhead.name/* != Z_NULL*/) {
  6504. beg = s.pending; /* start of bytes to update crc */
  6505. //int val;
  6506. do {
  6507. if (s.pending === s.pending_buf_size) {
  6508. if (s.gzhead.hcrc && s.pending > beg) {
  6509. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6510. }
  6511. flush_pending(strm);
  6512. beg = s.pending;
  6513. if (s.pending === s.pending_buf_size) {
  6514. val = 1;
  6515. break;
  6516. }
  6517. }
  6518. // JS specific: little magic to add zero terminator to end of string
  6519. if (s.gzindex < s.gzhead.name.length) {
  6520. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  6521. } else {
  6522. val = 0;
  6523. }
  6524. put_byte(s, val);
  6525. } while (val !== 0);
  6526. if (s.gzhead.hcrc && s.pending > beg) {
  6527. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6528. }
  6529. if (val === 0) {
  6530. s.gzindex = 0;
  6531. s.status = COMMENT_STATE;
  6532. }
  6533. }
  6534. else {
  6535. s.status = COMMENT_STATE;
  6536. }
  6537. }
  6538. if (s.status === COMMENT_STATE) {
  6539. if (s.gzhead.comment/* != Z_NULL*/) {
  6540. beg = s.pending; /* start of bytes to update crc */
  6541. //int val;
  6542. do {
  6543. if (s.pending === s.pending_buf_size) {
  6544. if (s.gzhead.hcrc && s.pending > beg) {
  6545. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6546. }
  6547. flush_pending(strm);
  6548. beg = s.pending;
  6549. if (s.pending === s.pending_buf_size) {
  6550. val = 1;
  6551. break;
  6552. }
  6553. }
  6554. // JS specific: little magic to add zero terminator to end of string
  6555. if (s.gzindex < s.gzhead.comment.length) {
  6556. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  6557. } else {
  6558. val = 0;
  6559. }
  6560. put_byte(s, val);
  6561. } while (val !== 0);
  6562. if (s.gzhead.hcrc && s.pending > beg) {
  6563. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  6564. }
  6565. if (val === 0) {
  6566. s.status = HCRC_STATE;
  6567. }
  6568. }
  6569. else {
  6570. s.status = HCRC_STATE;
  6571. }
  6572. }
  6573. if (s.status === HCRC_STATE) {
  6574. if (s.gzhead.hcrc) {
  6575. if (s.pending + 2 > s.pending_buf_size) {
  6576. flush_pending(strm);
  6577. }
  6578. if (s.pending + 2 <= s.pending_buf_size) {
  6579. put_byte(s, strm.adler & 0xff);
  6580. put_byte(s, (strm.adler >> 8) & 0xff);
  6581. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  6582. s.status = BUSY_STATE;
  6583. }
  6584. }
  6585. else {
  6586. s.status = BUSY_STATE;
  6587. }
  6588. }
  6589. //#endif
  6590. /* Flush as much pending output as possible */
  6591. if (s.pending !== 0) {
  6592. flush_pending(strm);
  6593. if (strm.avail_out === 0) {
  6594. /* Since avail_out is 0, deflate will be called again with
  6595. * more output space, but possibly with both pending and
  6596. * avail_in equal to zero. There won't be anything to do,
  6597. * but this is not an error situation so make sure we
  6598. * return OK instead of BUF_ERROR at next call of deflate:
  6599. */
  6600. s.last_flush = -1;
  6601. return Z_OK;
  6602. }
  6603. /* Make sure there is something to do and avoid duplicate consecutive
  6604. * flushes. For repeated and useless calls with Z_FINISH, we keep
  6605. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  6606. */
  6607. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  6608. flush !== Z_FINISH) {
  6609. return err(strm, Z_BUF_ERROR);
  6610. }
  6611. /* User must not provide more input after the first FINISH: */
  6612. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  6613. return err(strm, Z_BUF_ERROR);
  6614. }
  6615. /* Start a new block or continue the current one.
  6616. */
  6617. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  6618. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  6619. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  6620. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  6621. configuration_table[s.level].func(s, flush));
  6622. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  6623. s.status = FINISH_STATE;
  6624. }
  6625. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  6626. if (strm.avail_out === 0) {
  6627. s.last_flush = -1;
  6628. /* avoid BUF_ERROR next call, see above */
  6629. }
  6630. return Z_OK;
  6631. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  6632. * of deflate should use the same flush parameter to make sure
  6633. * that the flush is complete. So we don't have to output an
  6634. * empty block here, this will be done at next call. This also
  6635. * ensures that for a very small output buffer, we emit at most
  6636. * one empty block.
  6637. */
  6638. }
  6639. if (bstate === BS_BLOCK_DONE) {
  6640. if (flush === Z_PARTIAL_FLUSH) {
  6641. trees._tr_align(s);
  6642. }
  6643. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  6644. trees._tr_stored_block(s, 0, 0, false);
  6645. /* For a full flush, this empty block will be recognized
  6646. * as a special marker by inflate_sync().
  6647. */
  6648. if (flush === Z_FULL_FLUSH) {
  6649. /*** CLEAR_HASH(s); ***/ /* forget history */
  6650. zero(s.head); // Fill with NIL (= 0);
  6651. if (s.lookahead === 0) {
  6652. s.strstart = 0;
  6653. s.block_start = 0;
  6654. s.insert = 0;
  6655. }
  6656. }
  6657. }
  6658. flush_pending(strm);
  6659. if (strm.avail_out === 0) {
  6660. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  6661. return Z_OK;
  6662. }
  6663. }
  6664. }
  6665. //Assert(strm->avail_out > 0, "bug2");
  6666. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  6667. if (flush !== Z_FINISH) { return Z_OK; }
  6668. if (s.wrap <= 0) { return Z_STREAM_END; }
  6669. /* Write the trailer */
  6670. if (s.wrap === 2) {
  6671. put_byte(s, strm.adler & 0xff);
  6672. put_byte(s, (strm.adler >> 8) & 0xff);
  6673. put_byte(s, (strm.adler >> 16) & 0xff);
  6674. put_byte(s, (strm.adler >> 24) & 0xff);
  6675. put_byte(s, strm.total_in & 0xff);
  6676. put_byte(s, (strm.total_in >> 8) & 0xff);
  6677. put_byte(s, (strm.total_in >> 16) & 0xff);
  6678. put_byte(s, (strm.total_in >> 24) & 0xff);
  6679. }
  6680. else
  6681. {
  6682. putShortMSB(s, strm.adler >>> 16);
  6683. putShortMSB(s, strm.adler & 0xffff);
  6684. }
  6685. flush_pending(strm);
  6686. /* If avail_out is zero, the application will call deflate again
  6687. * to flush the rest.
  6688. */
  6689. if (s.wrap > 0) { s.wrap = -s.wrap; }
  6690. /* write the trailer only once! */
  6691. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  6692. }
  6693. function deflateEnd(strm) {
  6694. var status;
  6695. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  6696. return Z_STREAM_ERROR;
  6697. }
  6698. status = strm.state.status;
  6699. if (status !== INIT_STATE &&
  6700. status !== EXTRA_STATE &&
  6701. status !== NAME_STATE &&
  6702. status !== COMMENT_STATE &&
  6703. status !== HCRC_STATE &&
  6704. status !== BUSY_STATE &&
  6705. status !== FINISH_STATE
  6706. ) {
  6707. return err(strm, Z_STREAM_ERROR);
  6708. }
  6709. strm.state = null;
  6710. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  6711. }
  6712. /* =========================================================================
  6713. * Initializes the compression dictionary from the given byte
  6714. * sequence without producing any compressed output.
  6715. */
  6716. function deflateSetDictionary(strm, dictionary) {
  6717. var dictLength = dictionary.length;
  6718. var s;
  6719. var str, n;
  6720. var wrap;
  6721. var avail;
  6722. var next;
  6723. var input;
  6724. var tmpDict;
  6725. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  6726. return Z_STREAM_ERROR;
  6727. }
  6728. s = strm.state;
  6729. wrap = s.wrap;
  6730. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  6731. return Z_STREAM_ERROR;
  6732. }
  6733. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  6734. if (wrap === 1) {
  6735. /* adler32(strm->adler, dictionary, dictLength); */
  6736. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  6737. }
  6738. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  6739. /* if dictionary would fill window, just replace the history */
  6740. if (dictLength >= s.w_size) {
  6741. if (wrap === 0) { /* already empty otherwise */
  6742. /*** CLEAR_HASH(s); ***/
  6743. zero(s.head); // Fill with NIL (= 0);
  6744. s.strstart = 0;
  6745. s.block_start = 0;
  6746. s.insert = 0;
  6747. }
  6748. /* use the tail */
  6749. // dictionary = dictionary.slice(dictLength - s.w_size);
  6750. tmpDict = new utils.Buf8(s.w_size);
  6751. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  6752. dictionary = tmpDict;
  6753. dictLength = s.w_size;
  6754. }
  6755. /* insert dictionary into window and hash */
  6756. avail = strm.avail_in;
  6757. next = strm.next_in;
  6758. input = strm.input;
  6759. strm.avail_in = dictLength;
  6760. strm.next_in = 0;
  6761. strm.input = dictionary;
  6762. fill_window(s);
  6763. while (s.lookahead >= MIN_MATCH) {
  6764. str = s.strstart;
  6765. n = s.lookahead - (MIN_MATCH - 1);
  6766. do {
  6767. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  6768. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  6769. s.prev[str & s.w_mask] = s.head[s.ins_h];
  6770. s.head[s.ins_h] = str;
  6771. str++;
  6772. } while (--n);
  6773. s.strstart = str;
  6774. s.lookahead = MIN_MATCH - 1;
  6775. fill_window(s);
  6776. }
  6777. s.strstart += s.lookahead;
  6778. s.block_start = s.strstart;
  6779. s.insert = s.lookahead;
  6780. s.lookahead = 0;
  6781. s.match_length = s.prev_length = MIN_MATCH - 1;
  6782. s.match_available = 0;
  6783. strm.next_in = next;
  6784. strm.input = input;
  6785. strm.avail_in = avail;
  6786. s.wrap = wrap;
  6787. return Z_OK;
  6788. }
  6789. exports.deflateInit = deflateInit;
  6790. exports.deflateInit2 = deflateInit2;
  6791. exports.deflateReset = deflateReset;
  6792. exports.deflateResetKeep = deflateResetKeep;
  6793. exports.deflateSetHeader = deflateSetHeader;
  6794. exports.deflate = deflate;
  6795. exports.deflateEnd = deflateEnd;
  6796. exports.deflateSetDictionary = deflateSetDictionary;
  6797. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  6798. /* Not implemented
  6799. exports.deflateBound = deflateBound;
  6800. exports.deflateCopy = deflateCopy;
  6801. exports.deflateParams = deflateParams;
  6802. exports.deflatePending = deflatePending;
  6803. exports.deflatePrime = deflatePrime;
  6804. exports.deflateTune = deflateTune;
  6805. */
  6806. },{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(require,module,exports){
  6807. 'use strict';
  6808. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6809. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6810. //
  6811. // This software is provided 'as-is', without any express or implied
  6812. // warranty. In no event will the authors be held liable for any damages
  6813. // arising from the use of this software.
  6814. //
  6815. // Permission is granted to anyone to use this software for any purpose,
  6816. // including commercial applications, and to alter it and redistribute it
  6817. // freely, subject to the following restrictions:
  6818. //
  6819. // 1. The origin of this software must not be misrepresented; you must not
  6820. // claim that you wrote the original software. If you use this software
  6821. // in a product, an acknowledgment in the product documentation would be
  6822. // appreciated but is not required.
  6823. // 2. Altered source versions must be plainly marked as such, and must not be
  6824. // misrepresented as being the original software.
  6825. // 3. This notice may not be removed or altered from any source distribution.
  6826. function GZheader() {
  6827. /* true if compressed data believed to be text */
  6828. this.text = 0;
  6829. /* modification time */
  6830. this.time = 0;
  6831. /* extra flags (not used when writing a gzip file) */
  6832. this.xflags = 0;
  6833. /* operating system */
  6834. this.os = 0;
  6835. /* pointer to extra field or Z_NULL if none */
  6836. this.extra = null;
  6837. /* extra field length (valid if extra != Z_NULL) */
  6838. this.extra_len = 0; // Actually, we don't need it in JS,
  6839. // but leave for few code modifications
  6840. //
  6841. // Setup limits is not necessary because in js we should not preallocate memory
  6842. // for inflate use constant limit in 65536 bytes
  6843. //
  6844. /* space at extra (only when reading header) */
  6845. // this.extra_max = 0;
  6846. /* pointer to zero-terminated file name or Z_NULL */
  6847. this.name = '';
  6848. /* space at name (only when reading header) */
  6849. // this.name_max = 0;
  6850. /* pointer to zero-terminated comment or Z_NULL */
  6851. this.comment = '';
  6852. /* space at comment (only when reading header) */
  6853. // this.comm_max = 0;
  6854. /* true if there was or will be a header crc */
  6855. this.hcrc = 0;
  6856. /* true when done reading gzip header (not used when writing a gzip file) */
  6857. this.done = false;
  6858. }
  6859. module.exports = GZheader;
  6860. },{}],48:[function(require,module,exports){
  6861. 'use strict';
  6862. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  6863. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  6864. //
  6865. // This software is provided 'as-is', without any express or implied
  6866. // warranty. In no event will the authors be held liable for any damages
  6867. // arising from the use of this software.
  6868. //
  6869. // Permission is granted to anyone to use this software for any purpose,
  6870. // including commercial applications, and to alter it and redistribute it
  6871. // freely, subject to the following restrictions:
  6872. //
  6873. // 1. The origin of this software must not be misrepresented; you must not
  6874. // claim that you wrote the original software. If you use this software
  6875. // in a product, an acknowledgment in the product documentation would be
  6876. // appreciated but is not required.
  6877. // 2. Altered source versions must be plainly marked as such, and must not be
  6878. // misrepresented as being the original software.
  6879. // 3. This notice may not be removed or altered from any source distribution.
  6880. // See state defs from inflate.js
  6881. var BAD = 30; /* got a data error -- remain here until reset */
  6882. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  6883. /*
  6884. Decode literal, length, and distance codes and write out the resulting
  6885. literal and match bytes until either not enough input or output is
  6886. available, an end-of-block is encountered, or a data error is encountered.
  6887. When large enough input and output buffers are supplied to inflate(), for
  6888. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  6889. inflate execution time is spent in this routine.
  6890. Entry assumptions:
  6891. state.mode === LEN
  6892. strm.avail_in >= 6
  6893. strm.avail_out >= 258
  6894. start >= strm.avail_out
  6895. state.bits < 8
  6896. On return, state.mode is one of:
  6897. LEN -- ran out of enough output space or enough available input
  6898. TYPE -- reached end of block code, inflate() to interpret next block
  6899. BAD -- error in block data
  6900. Notes:
  6901. - The maximum input bits used by a length/distance pair is 15 bits for the
  6902. length code, 5 bits for the length extra, 15 bits for the distance code,
  6903. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  6904. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  6905. checking for available input while decoding.
  6906. - The maximum bytes that a single length/distance pair can output is 258
  6907. bytes, which is the maximum length that can be coded. inflate_fast()
  6908. requires strm.avail_out >= 258 for each loop to avoid checking for
  6909. output space.
  6910. */
  6911. module.exports = function inflate_fast(strm, start) {
  6912. var state;
  6913. var _in; /* local strm.input */
  6914. var last; /* have enough input while in < last */
  6915. var _out; /* local strm.output */
  6916. var beg; /* inflate()'s initial strm.output */
  6917. var end; /* while out < end, enough space available */
  6918. //#ifdef INFLATE_STRICT
  6919. var dmax; /* maximum distance from zlib header */
  6920. //#endif
  6921. var wsize; /* window size or zero if not using window */
  6922. var whave; /* valid bytes in the window */
  6923. var wnext; /* window write index */
  6924. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  6925. var s_window; /* allocated sliding window, if wsize != 0 */
  6926. var hold; /* local strm.hold */
  6927. var bits; /* local strm.bits */
  6928. var lcode; /* local strm.lencode */
  6929. var dcode; /* local strm.distcode */
  6930. var lmask; /* mask for first level of length codes */
  6931. var dmask; /* mask for first level of distance codes */
  6932. var here; /* retrieved table entry */
  6933. var op; /* code bits, operation, extra bits, or */
  6934. /* window position, window bytes to copy */
  6935. var len; /* match length, unused bytes */
  6936. var dist; /* match distance */
  6937. var from; /* where to copy match from */
  6938. var from_source;
  6939. var input, output; // JS specific, because we have no pointers
  6940. /* copy state to local variables */
  6941. state = strm.state;
  6942. //here = state.here;
  6943. _in = strm.next_in;
  6944. input = strm.input;
  6945. last = _in + (strm.avail_in - 5);
  6946. _out = strm.next_out;
  6947. output = strm.output;
  6948. beg = _out - (start - strm.avail_out);
  6949. end = _out + (strm.avail_out - 257);
  6950. //#ifdef INFLATE_STRICT
  6951. dmax = state.dmax;
  6952. //#endif
  6953. wsize = state.wsize;
  6954. whave = state.whave;
  6955. wnext = state.wnext;
  6956. s_window = state.window;
  6957. hold = state.hold;
  6958. bits = state.bits;
  6959. lcode = state.lencode;
  6960. dcode = state.distcode;
  6961. lmask = (1 << state.lenbits) - 1;
  6962. dmask = (1 << state.distbits) - 1;
  6963. /* decode literals and length/distances until end-of-block or not enough
  6964. input data or output space */
  6965. top:
  6966. do {
  6967. if (bits < 15) {
  6968. hold += input[_in++] << bits;
  6969. bits += 8;
  6970. hold += input[_in++] << bits;
  6971. bits += 8;
  6972. }
  6973. here = lcode[hold & lmask];
  6974. dolen:
  6975. for (;;) { // Goto emulation
  6976. op = here >>> 24/*here.bits*/;
  6977. hold >>>= op;
  6978. bits -= op;
  6979. op = (here >>> 16) & 0xff/*here.op*/;
  6980. if (op === 0) { /* literal */
  6981. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  6982. // "inflate: literal '%c'\n" :
  6983. // "inflate: literal 0x%02x\n", here.val));
  6984. output[_out++] = here & 0xffff/*here.val*/;
  6985. }
  6986. else if (op & 16) { /* length base */
  6987. len = here & 0xffff/*here.val*/;
  6988. op &= 15; /* number of extra bits */
  6989. if (op) {
  6990. if (bits < op) {
  6991. hold += input[_in++] << bits;
  6992. bits += 8;
  6993. }
  6994. len += hold & ((1 << op) - 1);
  6995. hold >>>= op;
  6996. bits -= op;
  6997. }
  6998. //Tracevv((stderr, "inflate: length %u\n", len));
  6999. if (bits < 15) {
  7000. hold += input[_in++] << bits;
  7001. bits += 8;
  7002. hold += input[_in++] << bits;
  7003. bits += 8;
  7004. }
  7005. here = dcode[hold & dmask];
  7006. dodist:
  7007. for (;;) { // goto emulation
  7008. op = here >>> 24/*here.bits*/;
  7009. hold >>>= op;
  7010. bits -= op;
  7011. op = (here >>> 16) & 0xff/*here.op*/;
  7012. if (op & 16) { /* distance base */
  7013. dist = here & 0xffff/*here.val*/;
  7014. op &= 15; /* number of extra bits */
  7015. if (bits < op) {
  7016. hold += input[_in++] << bits;
  7017. bits += 8;
  7018. if (bits < op) {
  7019. hold += input[_in++] << bits;
  7020. bits += 8;
  7021. }
  7022. }
  7023. dist += hold & ((1 << op) - 1);
  7024. //#ifdef INFLATE_STRICT
  7025. if (dist > dmax) {
  7026. strm.msg = 'invalid distance too far back';
  7027. state.mode = BAD;
  7028. break top;
  7029. }
  7030. //#endif
  7031. hold >>>= op;
  7032. bits -= op;
  7033. //Tracevv((stderr, "inflate: distance %u\n", dist));
  7034. op = _out - beg; /* max distance in output */
  7035. if (dist > op) { /* see if copy from window */
  7036. op = dist - op; /* distance back in window */
  7037. if (op > whave) {
  7038. if (state.sane) {
  7039. strm.msg = 'invalid distance too far back';
  7040. state.mode = BAD;
  7041. break top;
  7042. }
  7043. // (!) This block is disabled in zlib defailts,
  7044. // don't enable it for binary compatibility
  7045. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  7046. // if (len <= op - whave) {
  7047. // do {
  7048. // output[_out++] = 0;
  7049. // } while (--len);
  7050. // continue top;
  7051. // }
  7052. // len -= op - whave;
  7053. // do {
  7054. // output[_out++] = 0;
  7055. // } while (--op > whave);
  7056. // if (op === 0) {
  7057. // from = _out - dist;
  7058. // do {
  7059. // output[_out++] = output[from++];
  7060. // } while (--len);
  7061. // continue top;
  7062. // }
  7063. //#endif
  7064. }
  7065. from = 0; // window index
  7066. from_source = s_window;
  7067. if (wnext === 0) { /* very common case */
  7068. from += wsize - op;
  7069. if (op < len) { /* some from window */
  7070. len -= op;
  7071. do {
  7072. output[_out++] = s_window[from++];
  7073. } while (--op);
  7074. from = _out - dist; /* rest from output */
  7075. from_source = output;
  7076. }
  7077. }
  7078. else if (wnext < op) { /* wrap around window */
  7079. from += wsize + wnext - op;
  7080. op -= wnext;
  7081. if (op < len) { /* some from end of window */
  7082. len -= op;
  7083. do {
  7084. output[_out++] = s_window[from++];
  7085. } while (--op);
  7086. from = 0;
  7087. if (wnext < len) { /* some from start of window */
  7088. op = wnext;
  7089. len -= op;
  7090. do {
  7091. output[_out++] = s_window[from++];
  7092. } while (--op);
  7093. from = _out - dist; /* rest from output */
  7094. from_source = output;
  7095. }
  7096. }
  7097. }
  7098. else { /* contiguous in window */
  7099. from += wnext - op;
  7100. if (op < len) { /* some from window */
  7101. len -= op;
  7102. do {
  7103. output[_out++] = s_window[from++];
  7104. } while (--op);
  7105. from = _out - dist; /* rest from output */
  7106. from_source = output;
  7107. }
  7108. }
  7109. while (len > 2) {
  7110. output[_out++] = from_source[from++];
  7111. output[_out++] = from_source[from++];
  7112. output[_out++] = from_source[from++];
  7113. len -= 3;
  7114. }
  7115. if (len) {
  7116. output[_out++] = from_source[from++];
  7117. if (len > 1) {
  7118. output[_out++] = from_source[from++];
  7119. }
  7120. }
  7121. }
  7122. else {
  7123. from = _out - dist; /* copy direct from output */
  7124. do { /* minimum length is three */
  7125. output[_out++] = output[from++];
  7126. output[_out++] = output[from++];
  7127. output[_out++] = output[from++];
  7128. len -= 3;
  7129. } while (len > 2);
  7130. if (len) {
  7131. output[_out++] = output[from++];
  7132. if (len > 1) {
  7133. output[_out++] = output[from++];
  7134. }
  7135. }
  7136. }
  7137. }
  7138. else if ((op & 64) === 0) { /* 2nd level distance code */
  7139. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  7140. continue dodist;
  7141. }
  7142. else {
  7143. strm.msg = 'invalid distance code';
  7144. state.mode = BAD;
  7145. break top;
  7146. }
  7147. break; // need to emulate goto via "continue"
  7148. }
  7149. }
  7150. else if ((op & 64) === 0) { /* 2nd level length code */
  7151. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  7152. continue dolen;
  7153. }
  7154. else if (op & 32) { /* end-of-block */
  7155. //Tracevv((stderr, "inflate: end of block\n"));
  7156. state.mode = TYPE;
  7157. break top;
  7158. }
  7159. else {
  7160. strm.msg = 'invalid literal/length code';
  7161. state.mode = BAD;
  7162. break top;
  7163. }
  7164. break; // need to emulate goto via "continue"
  7165. }
  7166. } while (_in < last && _out < end);
  7167. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  7168. len = bits >> 3;
  7169. _in -= len;
  7170. bits -= len << 3;
  7171. hold &= (1 << bits) - 1;
  7172. /* update state and return */
  7173. strm.next_in = _in;
  7174. strm.next_out = _out;
  7175. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  7176. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  7177. state.hold = hold;
  7178. state.bits = bits;
  7179. return;
  7180. };
  7181. },{}],49:[function(require,module,exports){
  7182. 'use strict';
  7183. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  7184. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  7185. //
  7186. // This software is provided 'as-is', without any express or implied
  7187. // warranty. In no event will the authors be held liable for any damages
  7188. // arising from the use of this software.
  7189. //
  7190. // Permission is granted to anyone to use this software for any purpose,
  7191. // including commercial applications, and to alter it and redistribute it
  7192. // freely, subject to the following restrictions:
  7193. //
  7194. // 1. The origin of this software must not be misrepresented; you must not
  7195. // claim that you wrote the original software. If you use this software
  7196. // in a product, an acknowledgment in the product documentation would be
  7197. // appreciated but is not required.
  7198. // 2. Altered source versions must be plainly marked as such, and must not be
  7199. // misrepresented as being the original software.
  7200. // 3. This notice may not be removed or altered from any source distribution.
  7201. var utils = require('../utils/common');
  7202. var adler32 = require('./adler32');
  7203. var crc32 = require('./crc32');
  7204. var inflate_fast = require('./inffast');
  7205. var inflate_table = require('./inftrees');
  7206. var CODES = 0;
  7207. var LENS = 1;
  7208. var DISTS = 2;
  7209. /* Public constants ==========================================================*/
  7210. /* ===========================================================================*/
  7211. /* Allowed flush values; see deflate() and inflate() below for details */
  7212. //var Z_NO_FLUSH = 0;
  7213. //var Z_PARTIAL_FLUSH = 1;
  7214. //var Z_SYNC_FLUSH = 2;
  7215. //var Z_FULL_FLUSH = 3;
  7216. var Z_FINISH = 4;
  7217. var Z_BLOCK = 5;
  7218. var Z_TREES = 6;
  7219. /* Return codes for the compression/decompression functions. Negative values
  7220. * are errors, positive values are used for special but normal events.
  7221. */
  7222. var Z_OK = 0;
  7223. var Z_STREAM_END = 1;
  7224. var Z_NEED_DICT = 2;
  7225. //var Z_ERRNO = -1;
  7226. var Z_STREAM_ERROR = -2;
  7227. var Z_DATA_ERROR = -3;
  7228. var Z_MEM_ERROR = -4;
  7229. var Z_BUF_ERROR = -5;
  7230. //var Z_VERSION_ERROR = -6;
  7231. /* The deflate compression method */
  7232. var Z_DEFLATED = 8;
  7233. /* STATES ====================================================================*/
  7234. /* ===========================================================================*/
  7235. var HEAD = 1; /* i: waiting for magic header */
  7236. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  7237. var TIME = 3; /* i: waiting for modification time (gzip) */
  7238. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  7239. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  7240. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  7241. var NAME = 7; /* i: waiting for end of file name (gzip) */
  7242. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  7243. var HCRC = 9; /* i: waiting for header crc (gzip) */
  7244. var DICTID = 10; /* i: waiting for dictionary check value */
  7245. var DICT = 11; /* waiting for inflateSetDictionary() call */
  7246. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  7247. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  7248. var STORED = 14; /* i: waiting for stored size (length and complement) */
  7249. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  7250. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  7251. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  7252. var LENLENS = 18; /* i: waiting for code length code lengths */
  7253. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  7254. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  7255. var LEN = 21; /* i: waiting for length/lit/eob code */
  7256. var LENEXT = 22; /* i: waiting for length extra bits */
  7257. var DIST = 23; /* i: waiting for distance code */
  7258. var DISTEXT = 24; /* i: waiting for distance extra bits */
  7259. var MATCH = 25; /* o: waiting for output space to copy string */
  7260. var LIT = 26; /* o: waiting for output space to write literal */
  7261. var CHECK = 27; /* i: waiting for 32-bit check value */
  7262. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  7263. var DONE = 29; /* finished check, done -- remain here until reset */
  7264. var BAD = 30; /* got a data error -- remain here until reset */
  7265. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  7266. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  7267. /* ===========================================================================*/
  7268. var ENOUGH_LENS = 852;
  7269. var ENOUGH_DISTS = 592;
  7270. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  7271. var MAX_WBITS = 15;
  7272. /* 32K LZ77 window */
  7273. var DEF_WBITS = MAX_WBITS;
  7274. function zswap32(q) {
  7275. return (((q >>> 24) & 0xff) +
  7276. ((q >>> 8) & 0xff00) +
  7277. ((q & 0xff00) << 8) +
  7278. ((q & 0xff) << 24));
  7279. }
  7280. function InflateState() {
  7281. this.mode = 0; /* current inflate mode */
  7282. this.last = false; /* true if processing last block */
  7283. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  7284. this.havedict = false; /* true if dictionary provided */
  7285. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  7286. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  7287. this.check = 0; /* protected copy of check value */
  7288. this.total = 0; /* protected copy of output count */
  7289. // TODO: may be {}
  7290. this.head = null; /* where to save gzip header information */
  7291. /* sliding window */
  7292. this.wbits = 0; /* log base 2 of requested window size */
  7293. this.wsize = 0; /* window size or zero if not using window */
  7294. this.whave = 0; /* valid bytes in the window */
  7295. this.wnext = 0; /* window write index */
  7296. this.window = null; /* allocated sliding window, if needed */
  7297. /* bit accumulator */
  7298. this.hold = 0; /* input bit accumulator */
  7299. this.bits = 0; /* number of bits in "in" */
  7300. /* for string and stored block copying */
  7301. this.length = 0; /* literal or length of data to copy */
  7302. this.offset = 0; /* distance back to copy string from */
  7303. /* for table and code decoding */
  7304. this.extra = 0; /* extra bits needed */
  7305. /* fixed and dynamic code tables */
  7306. this.lencode = null; /* starting table for length/literal codes */
  7307. this.distcode = null; /* starting table for distance codes */
  7308. this.lenbits = 0; /* index bits for lencode */
  7309. this.distbits = 0; /* index bits for distcode */
  7310. /* dynamic table building */
  7311. this.ncode = 0; /* number of code length code lengths */
  7312. this.nlen = 0; /* number of length code lengths */
  7313. this.ndist = 0; /* number of distance code lengths */
  7314. this.have = 0; /* number of code lengths in lens[] */
  7315. this.next = null; /* next available space in codes[] */
  7316. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  7317. this.work = new utils.Buf16(288); /* work area for code table building */
  7318. /*
  7319. because we don't have pointers in js, we use lencode and distcode directly
  7320. as buffers so we don't need codes
  7321. */
  7322. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  7323. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  7324. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  7325. this.sane = 0; /* if false, allow invalid distance too far */
  7326. this.back = 0; /* bits back of last unprocessed length/lit */
  7327. this.was = 0; /* initial length of match */
  7328. }
  7329. function inflateResetKeep(strm) {
  7330. var state;
  7331. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7332. state = strm.state;
  7333. strm.total_in = strm.total_out = state.total = 0;
  7334. strm.msg = ''; /*Z_NULL*/
  7335. if (state.wrap) { /* to support ill-conceived Java test suite */
  7336. strm.adler = state.wrap & 1;
  7337. }
  7338. state.mode = HEAD;
  7339. state.last = 0;
  7340. state.havedict = 0;
  7341. state.dmax = 32768;
  7342. state.head = null/*Z_NULL*/;
  7343. state.hold = 0;
  7344. state.bits = 0;
  7345. //state.lencode = state.distcode = state.next = state.codes;
  7346. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  7347. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  7348. state.sane = 1;
  7349. state.back = -1;
  7350. //Tracev((stderr, "inflate: reset\n"));
  7351. return Z_OK;
  7352. }
  7353. function inflateReset(strm) {
  7354. var state;
  7355. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7356. state = strm.state;
  7357. state.wsize = 0;
  7358. state.whave = 0;
  7359. state.wnext = 0;
  7360. return inflateResetKeep(strm);
  7361. }
  7362. function inflateReset2(strm, windowBits) {
  7363. var wrap;
  7364. var state;
  7365. /* get the state */
  7366. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7367. state = strm.state;
  7368. /* extract wrap request from windowBits parameter */
  7369. if (windowBits < 0) {
  7370. wrap = 0;
  7371. windowBits = -windowBits;
  7372. }
  7373. else {
  7374. wrap = (windowBits >> 4) + 1;
  7375. if (windowBits < 48) {
  7376. windowBits &= 15;
  7377. }
  7378. }
  7379. /* set number of window bits, free window if different */
  7380. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  7381. return Z_STREAM_ERROR;
  7382. }
  7383. if (state.window !== null && state.wbits !== windowBits) {
  7384. state.window = null;
  7385. }
  7386. /* update state and reset the rest of it */
  7387. state.wrap = wrap;
  7388. state.wbits = windowBits;
  7389. return inflateReset(strm);
  7390. }
  7391. function inflateInit2(strm, windowBits) {
  7392. var ret;
  7393. var state;
  7394. if (!strm) { return Z_STREAM_ERROR; }
  7395. //strm.msg = Z_NULL; /* in case we return an error */
  7396. state = new InflateState();
  7397. //if (state === Z_NULL) return Z_MEM_ERROR;
  7398. //Tracev((stderr, "inflate: allocated\n"));
  7399. strm.state = state;
  7400. state.window = null/*Z_NULL*/;
  7401. ret = inflateReset2(strm, windowBits);
  7402. if (ret !== Z_OK) {
  7403. strm.state = null/*Z_NULL*/;
  7404. }
  7405. return ret;
  7406. }
  7407. function inflateInit(strm) {
  7408. return inflateInit2(strm, DEF_WBITS);
  7409. }
  7410. /*
  7411. Return state with length and distance decoding tables and index sizes set to
  7412. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  7413. If BUILDFIXED is defined, then instead this routine builds the tables the
  7414. first time it's called, and returns those tables the first time and
  7415. thereafter. This reduces the size of the code by about 2K bytes, in
  7416. exchange for a little execution time. However, BUILDFIXED should not be
  7417. used for threaded applications, since the rewriting of the tables and virgin
  7418. may not be thread-safe.
  7419. */
  7420. var virgin = true;
  7421. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  7422. function fixedtables(state) {
  7423. /* build fixed huffman tables if first call (may not be thread safe) */
  7424. if (virgin) {
  7425. var sym;
  7426. lenfix = new utils.Buf32(512);
  7427. distfix = new utils.Buf32(32);
  7428. /* literal/length table */
  7429. sym = 0;
  7430. while (sym < 144) { state.lens[sym++] = 8; }
  7431. while (sym < 256) { state.lens[sym++] = 9; }
  7432. while (sym < 280) { state.lens[sym++] = 7; }
  7433. while (sym < 288) { state.lens[sym++] = 8; }
  7434. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  7435. /* distance table */
  7436. sym = 0;
  7437. while (sym < 32) { state.lens[sym++] = 5; }
  7438. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  7439. /* do this just once */
  7440. virgin = false;
  7441. }
  7442. state.lencode = lenfix;
  7443. state.lenbits = 9;
  7444. state.distcode = distfix;
  7445. state.distbits = 5;
  7446. }
  7447. /*
  7448. Update the window with the last wsize (normally 32K) bytes written before
  7449. returning. If window does not exist yet, create it. This is only called
  7450. when a window is already in use, or when output has been written during this
  7451. inflate call, but the end of the deflate stream has not been reached yet.
  7452. It is also called to create a window for dictionary data when a dictionary
  7453. is loaded.
  7454. Providing output buffers larger than 32K to inflate() should provide a speed
  7455. advantage, since only the last 32K of output is copied to the sliding window
  7456. upon return from inflate(), and since all distances after the first 32K of
  7457. output will fall in the output data, making match copies simpler and faster.
  7458. The advantage may be dependent on the size of the processor's data caches.
  7459. */
  7460. function updatewindow(strm, src, end, copy) {
  7461. var dist;
  7462. var state = strm.state;
  7463. /* if it hasn't been done already, allocate space for the window */
  7464. if (state.window === null) {
  7465. state.wsize = 1 << state.wbits;
  7466. state.wnext = 0;
  7467. state.whave = 0;
  7468. state.window = new utils.Buf8(state.wsize);
  7469. }
  7470. /* copy state->wsize or less output bytes into the circular window */
  7471. if (copy >= state.wsize) {
  7472. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  7473. state.wnext = 0;
  7474. state.whave = state.wsize;
  7475. }
  7476. else {
  7477. dist = state.wsize - state.wnext;
  7478. if (dist > copy) {
  7479. dist = copy;
  7480. }
  7481. //zmemcpy(state->window + state->wnext, end - copy, dist);
  7482. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  7483. copy -= dist;
  7484. if (copy) {
  7485. //zmemcpy(state->window, end - copy, copy);
  7486. utils.arraySet(state.window, src, end - copy, copy, 0);
  7487. state.wnext = copy;
  7488. state.whave = state.wsize;
  7489. }
  7490. else {
  7491. state.wnext += dist;
  7492. if (state.wnext === state.wsize) { state.wnext = 0; }
  7493. if (state.whave < state.wsize) { state.whave += dist; }
  7494. }
  7495. }
  7496. return 0;
  7497. }
  7498. function inflate(strm, flush) {
  7499. var state;
  7500. var input, output; // input/output buffers
  7501. var next; /* next input INDEX */
  7502. var put; /* next output INDEX */
  7503. var have, left; /* available input and output */
  7504. var hold; /* bit buffer */
  7505. var bits; /* bits in bit buffer */
  7506. var _in, _out; /* save starting available input and output */
  7507. var copy; /* number of stored or match bytes to copy */
  7508. var from; /* where to copy match bytes from */
  7509. var from_source;
  7510. var here = 0; /* current decoding table entry */
  7511. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  7512. //var last; /* parent table entry */
  7513. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  7514. var len; /* length to copy for repeats, bits to drop */
  7515. var ret; /* return code */
  7516. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  7517. var opts;
  7518. var n; // temporary var for NEED_BITS
  7519. var order = /* permutation of code lengths */
  7520. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  7521. if (!strm || !strm.state || !strm.output ||
  7522. (!strm.input && strm.avail_in !== 0)) {
  7523. return Z_STREAM_ERROR;
  7524. }
  7525. state = strm.state;
  7526. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  7527. //--- LOAD() ---
  7528. put = strm.next_out;
  7529. output = strm.output;
  7530. left = strm.avail_out;
  7531. next = strm.next_in;
  7532. input = strm.input;
  7533. have = strm.avail_in;
  7534. hold = state.hold;
  7535. bits = state.bits;
  7536. //---
  7537. _in = have;
  7538. _out = left;
  7539. ret = Z_OK;
  7540. inf_leave: // goto emulation
  7541. for (;;) {
  7542. switch (state.mode) {
  7543. case HEAD:
  7544. if (state.wrap === 0) {
  7545. state.mode = TYPEDO;
  7546. break;
  7547. }
  7548. //=== NEEDBITS(16);
  7549. while (bits < 16) {
  7550. if (have === 0) { break inf_leave; }
  7551. have--;
  7552. hold += input[next++] << bits;
  7553. bits += 8;
  7554. }
  7555. //===//
  7556. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  7557. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  7558. //=== CRC2(state.check, hold);
  7559. hbuf[0] = hold & 0xff;
  7560. hbuf[1] = (hold >>> 8) & 0xff;
  7561. state.check = crc32(state.check, hbuf, 2, 0);
  7562. //===//
  7563. //=== INITBITS();
  7564. hold = 0;
  7565. bits = 0;
  7566. //===//
  7567. state.mode = FLAGS;
  7568. break;
  7569. }
  7570. state.flags = 0; /* expect zlib header */
  7571. if (state.head) {
  7572. state.head.done = false;
  7573. }
  7574. if (!(state.wrap & 1) || /* check if zlib header allowed */
  7575. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  7576. strm.msg = 'incorrect header check';
  7577. state.mode = BAD;
  7578. break;
  7579. }
  7580. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  7581. strm.msg = 'unknown compression method';
  7582. state.mode = BAD;
  7583. break;
  7584. }
  7585. //--- DROPBITS(4) ---//
  7586. hold >>>= 4;
  7587. bits -= 4;
  7588. //---//
  7589. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  7590. if (state.wbits === 0) {
  7591. state.wbits = len;
  7592. }
  7593. else if (len > state.wbits) {
  7594. strm.msg = 'invalid window size';
  7595. state.mode = BAD;
  7596. break;
  7597. }
  7598. state.dmax = 1 << len;
  7599. //Tracev((stderr, "inflate: zlib header ok\n"));
  7600. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  7601. state.mode = hold & 0x200 ? DICTID : TYPE;
  7602. //=== INITBITS();
  7603. hold = 0;
  7604. bits = 0;
  7605. //===//
  7606. break;
  7607. case FLAGS:
  7608. //=== NEEDBITS(16); */
  7609. while (bits < 16) {
  7610. if (have === 0) { break inf_leave; }
  7611. have--;
  7612. hold += input[next++] << bits;
  7613. bits += 8;
  7614. }
  7615. //===//
  7616. state.flags = hold;
  7617. if ((state.flags & 0xff) !== Z_DEFLATED) {
  7618. strm.msg = 'unknown compression method';
  7619. state.mode = BAD;
  7620. break;
  7621. }
  7622. if (state.flags & 0xe000) {
  7623. strm.msg = 'unknown header flags set';
  7624. state.mode = BAD;
  7625. break;
  7626. }
  7627. if (state.head) {
  7628. state.head.text = ((hold >> 8) & 1);
  7629. }
  7630. if (state.flags & 0x0200) {
  7631. //=== CRC2(state.check, hold);
  7632. hbuf[0] = hold & 0xff;
  7633. hbuf[1] = (hold >>> 8) & 0xff;
  7634. state.check = crc32(state.check, hbuf, 2, 0);
  7635. //===//
  7636. }
  7637. //=== INITBITS();
  7638. hold = 0;
  7639. bits = 0;
  7640. //===//
  7641. state.mode = TIME;
  7642. /* falls through */
  7643. case TIME:
  7644. //=== NEEDBITS(32); */
  7645. while (bits < 32) {
  7646. if (have === 0) { break inf_leave; }
  7647. have--;
  7648. hold += input[next++] << bits;
  7649. bits += 8;
  7650. }
  7651. //===//
  7652. if (state.head) {
  7653. state.head.time = hold;
  7654. }
  7655. if (state.flags & 0x0200) {
  7656. //=== CRC4(state.check, hold)
  7657. hbuf[0] = hold & 0xff;
  7658. hbuf[1] = (hold >>> 8) & 0xff;
  7659. hbuf[2] = (hold >>> 16) & 0xff;
  7660. hbuf[3] = (hold >>> 24) & 0xff;
  7661. state.check = crc32(state.check, hbuf, 4, 0);
  7662. //===
  7663. }
  7664. //=== INITBITS();
  7665. hold = 0;
  7666. bits = 0;
  7667. //===//
  7668. state.mode = OS;
  7669. /* falls through */
  7670. case OS:
  7671. //=== NEEDBITS(16); */
  7672. while (bits < 16) {
  7673. if (have === 0) { break inf_leave; }
  7674. have--;
  7675. hold += input[next++] << bits;
  7676. bits += 8;
  7677. }
  7678. //===//
  7679. if (state.head) {
  7680. state.head.xflags = (hold & 0xff);
  7681. state.head.os = (hold >> 8);
  7682. }
  7683. if (state.flags & 0x0200) {
  7684. //=== CRC2(state.check, hold);
  7685. hbuf[0] = hold & 0xff;
  7686. hbuf[1] = (hold >>> 8) & 0xff;
  7687. state.check = crc32(state.check, hbuf, 2, 0);
  7688. //===//
  7689. }
  7690. //=== INITBITS();
  7691. hold = 0;
  7692. bits = 0;
  7693. //===//
  7694. state.mode = EXLEN;
  7695. /* falls through */
  7696. case EXLEN:
  7697. if (state.flags & 0x0400) {
  7698. //=== NEEDBITS(16); */
  7699. while (bits < 16) {
  7700. if (have === 0) { break inf_leave; }
  7701. have--;
  7702. hold += input[next++] << bits;
  7703. bits += 8;
  7704. }
  7705. //===//
  7706. state.length = hold;
  7707. if (state.head) {
  7708. state.head.extra_len = hold;
  7709. }
  7710. if (state.flags & 0x0200) {
  7711. //=== CRC2(state.check, hold);
  7712. hbuf[0] = hold & 0xff;
  7713. hbuf[1] = (hold >>> 8) & 0xff;
  7714. state.check = crc32(state.check, hbuf, 2, 0);
  7715. //===//
  7716. }
  7717. //=== INITBITS();
  7718. hold = 0;
  7719. bits = 0;
  7720. //===//
  7721. }
  7722. else if (state.head) {
  7723. state.head.extra = null/*Z_NULL*/;
  7724. }
  7725. state.mode = EXTRA;
  7726. /* falls through */
  7727. case EXTRA:
  7728. if (state.flags & 0x0400) {
  7729. copy = state.length;
  7730. if (copy > have) { copy = have; }
  7731. if (copy) {
  7732. if (state.head) {
  7733. len = state.head.extra_len - state.length;
  7734. if (!state.head.extra) {
  7735. // Use untyped array for more conveniend processing later
  7736. state.head.extra = new Array(state.head.extra_len);
  7737. }
  7738. utils.arraySet(
  7739. state.head.extra,
  7740. input,
  7741. next,
  7742. // extra field is limited to 65536 bytes
  7743. // - no need for additional size check
  7744. copy,
  7745. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  7746. len
  7747. );
  7748. //zmemcpy(state.head.extra + len, next,
  7749. // len + copy > state.head.extra_max ?
  7750. // state.head.extra_max - len : copy);
  7751. }
  7752. if (state.flags & 0x0200) {
  7753. state.check = crc32(state.check, input, copy, next);
  7754. }
  7755. have -= copy;
  7756. next += copy;
  7757. state.length -= copy;
  7758. }
  7759. if (state.length) { break inf_leave; }
  7760. }
  7761. state.length = 0;
  7762. state.mode = NAME;
  7763. /* falls through */
  7764. case NAME:
  7765. if (state.flags & 0x0800) {
  7766. if (have === 0) { break inf_leave; }
  7767. copy = 0;
  7768. do {
  7769. // TODO: 2 or 1 bytes?
  7770. len = input[next + copy++];
  7771. /* use constant limit because in js we should not preallocate memory */
  7772. if (state.head && len &&
  7773. (state.length < 65536 /*state.head.name_max*/)) {
  7774. state.head.name += String.fromCharCode(len);
  7775. }
  7776. } while (len && copy < have);
  7777. if (state.flags & 0x0200) {
  7778. state.check = crc32(state.check, input, copy, next);
  7779. }
  7780. have -= copy;
  7781. next += copy;
  7782. if (len) { break inf_leave; }
  7783. }
  7784. else if (state.head) {
  7785. state.head.name = null;
  7786. }
  7787. state.length = 0;
  7788. state.mode = COMMENT;
  7789. /* falls through */
  7790. case COMMENT:
  7791. if (state.flags & 0x1000) {
  7792. if (have === 0) { break inf_leave; }
  7793. copy = 0;
  7794. do {
  7795. len = input[next + copy++];
  7796. /* use constant limit because in js we should not preallocate memory */
  7797. if (state.head && len &&
  7798. (state.length < 65536 /*state.head.comm_max*/)) {
  7799. state.head.comment += String.fromCharCode(len);
  7800. }
  7801. } while (len && copy < have);
  7802. if (state.flags & 0x0200) {
  7803. state.check = crc32(state.check, input, copy, next);
  7804. }
  7805. have -= copy;
  7806. next += copy;
  7807. if (len) { break inf_leave; }
  7808. }
  7809. else if (state.head) {
  7810. state.head.comment = null;
  7811. }
  7812. state.mode = HCRC;
  7813. /* falls through */
  7814. case HCRC:
  7815. if (state.flags & 0x0200) {
  7816. //=== NEEDBITS(16); */
  7817. while (bits < 16) {
  7818. if (have === 0) { break inf_leave; }
  7819. have--;
  7820. hold += input[next++] << bits;
  7821. bits += 8;
  7822. }
  7823. //===//
  7824. if (hold !== (state.check & 0xffff)) {
  7825. strm.msg = 'header crc mismatch';
  7826. state.mode = BAD;
  7827. break;
  7828. }
  7829. //=== INITBITS();
  7830. hold = 0;
  7831. bits = 0;
  7832. //===//
  7833. }
  7834. if (state.head) {
  7835. state.head.hcrc = ((state.flags >> 9) & 1);
  7836. state.head.done = true;
  7837. }
  7838. strm.adler = state.check = 0;
  7839. state.mode = TYPE;
  7840. break;
  7841. case DICTID:
  7842. //=== NEEDBITS(32); */
  7843. while (bits < 32) {
  7844. if (have === 0) { break inf_leave; }
  7845. have--;
  7846. hold += input[next++] << bits;
  7847. bits += 8;
  7848. }
  7849. //===//
  7850. strm.adler = state.check = zswap32(hold);
  7851. //=== INITBITS();
  7852. hold = 0;
  7853. bits = 0;
  7854. //===//
  7855. state.mode = DICT;
  7856. /* falls through */
  7857. case DICT:
  7858. if (state.havedict === 0) {
  7859. //--- RESTORE() ---
  7860. strm.next_out = put;
  7861. strm.avail_out = left;
  7862. strm.next_in = next;
  7863. strm.avail_in = have;
  7864. state.hold = hold;
  7865. state.bits = bits;
  7866. //---
  7867. return Z_NEED_DICT;
  7868. }
  7869. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  7870. state.mode = TYPE;
  7871. /* falls through */
  7872. case TYPE:
  7873. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  7874. /* falls through */
  7875. case TYPEDO:
  7876. if (state.last) {
  7877. //--- BYTEBITS() ---//
  7878. hold >>>= bits & 7;
  7879. bits -= bits & 7;
  7880. //---//
  7881. state.mode = CHECK;
  7882. break;
  7883. }
  7884. //=== NEEDBITS(3); */
  7885. while (bits < 3) {
  7886. if (have === 0) { break inf_leave; }
  7887. have--;
  7888. hold += input[next++] << bits;
  7889. bits += 8;
  7890. }
  7891. //===//
  7892. state.last = (hold & 0x01)/*BITS(1)*/;
  7893. //--- DROPBITS(1) ---//
  7894. hold >>>= 1;
  7895. bits -= 1;
  7896. //---//
  7897. switch ((hold & 0x03)/*BITS(2)*/) {
  7898. case 0: /* stored block */
  7899. //Tracev((stderr, "inflate: stored block%s\n",
  7900. // state.last ? " (last)" : ""));
  7901. state.mode = STORED;
  7902. break;
  7903. case 1: /* fixed block */
  7904. fixedtables(state);
  7905. //Tracev((stderr, "inflate: fixed codes block%s\n",
  7906. // state.last ? " (last)" : ""));
  7907. state.mode = LEN_; /* decode codes */
  7908. if (flush === Z_TREES) {
  7909. //--- DROPBITS(2) ---//
  7910. hold >>>= 2;
  7911. bits -= 2;
  7912. //---//
  7913. break inf_leave;
  7914. }
  7915. break;
  7916. case 2: /* dynamic block */
  7917. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  7918. // state.last ? " (last)" : ""));
  7919. state.mode = TABLE;
  7920. break;
  7921. case 3:
  7922. strm.msg = 'invalid block type';
  7923. state.mode = BAD;
  7924. }
  7925. //--- DROPBITS(2) ---//
  7926. hold >>>= 2;
  7927. bits -= 2;
  7928. //---//
  7929. break;
  7930. case STORED:
  7931. //--- BYTEBITS() ---// /* go to byte boundary */
  7932. hold >>>= bits & 7;
  7933. bits -= bits & 7;
  7934. //---//
  7935. //=== NEEDBITS(32); */
  7936. while (bits < 32) {
  7937. if (have === 0) { break inf_leave; }
  7938. have--;
  7939. hold += input[next++] << bits;
  7940. bits += 8;
  7941. }
  7942. //===//
  7943. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  7944. strm.msg = 'invalid stored block lengths';
  7945. state.mode = BAD;
  7946. break;
  7947. }
  7948. state.length = hold & 0xffff;
  7949. //Tracev((stderr, "inflate: stored length %u\n",
  7950. // state.length));
  7951. //=== INITBITS();
  7952. hold = 0;
  7953. bits = 0;
  7954. //===//
  7955. state.mode = COPY_;
  7956. if (flush === Z_TREES) { break inf_leave; }
  7957. /* falls through */
  7958. case COPY_:
  7959. state.mode = COPY;
  7960. /* falls through */
  7961. case COPY:
  7962. copy = state.length;
  7963. if (copy) {
  7964. if (copy > have) { copy = have; }
  7965. if (copy > left) { copy = left; }
  7966. if (copy === 0) { break inf_leave; }
  7967. //--- zmemcpy(put, next, copy); ---
  7968. utils.arraySet(output, input, next, copy, put);
  7969. //---//
  7970. have -= copy;
  7971. next += copy;
  7972. left -= copy;
  7973. put += copy;
  7974. state.length -= copy;
  7975. break;
  7976. }
  7977. //Tracev((stderr, "inflate: stored end\n"));
  7978. state.mode = TYPE;
  7979. break;
  7980. case TABLE:
  7981. //=== NEEDBITS(14); */
  7982. while (bits < 14) {
  7983. if (have === 0) { break inf_leave; }
  7984. have--;
  7985. hold += input[next++] << bits;
  7986. bits += 8;
  7987. }
  7988. //===//
  7989. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  7990. //--- DROPBITS(5) ---//
  7991. hold >>>= 5;
  7992. bits -= 5;
  7993. //---//
  7994. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  7995. //--- DROPBITS(5) ---//
  7996. hold >>>= 5;
  7997. bits -= 5;
  7998. //---//
  7999. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  8000. //--- DROPBITS(4) ---//
  8001. hold >>>= 4;
  8002. bits -= 4;
  8003. //---//
  8004. //#ifndef PKZIP_BUG_WORKAROUND
  8005. if (state.nlen > 286 || state.ndist > 30) {
  8006. strm.msg = 'too many length or distance symbols';
  8007. state.mode = BAD;
  8008. break;
  8009. }
  8010. //#endif
  8011. //Tracev((stderr, "inflate: table sizes ok\n"));
  8012. state.have = 0;
  8013. state.mode = LENLENS;
  8014. /* falls through */
  8015. case LENLENS:
  8016. while (state.have < state.ncode) {
  8017. //=== NEEDBITS(3);
  8018. while (bits < 3) {
  8019. if (have === 0) { break inf_leave; }
  8020. have--;
  8021. hold += input[next++] << bits;
  8022. bits += 8;
  8023. }
  8024. //===//
  8025. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  8026. //--- DROPBITS(3) ---//
  8027. hold >>>= 3;
  8028. bits -= 3;
  8029. //---//
  8030. }
  8031. while (state.have < 19) {
  8032. state.lens[order[state.have++]] = 0;
  8033. }
  8034. // We have separate tables & no pointers. 2 commented lines below not needed.
  8035. //state.next = state.codes;
  8036. //state.lencode = state.next;
  8037. // Switch to use dynamic table
  8038. state.lencode = state.lendyn;
  8039. state.lenbits = 7;
  8040. opts = { bits: state.lenbits };
  8041. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  8042. state.lenbits = opts.bits;
  8043. if (ret) {
  8044. strm.msg = 'invalid code lengths set';
  8045. state.mode = BAD;
  8046. break;
  8047. }
  8048. //Tracev((stderr, "inflate: code lengths ok\n"));
  8049. state.have = 0;
  8050. state.mode = CODELENS;
  8051. /* falls through */
  8052. case CODELENS:
  8053. while (state.have < state.nlen + state.ndist) {
  8054. for (;;) {
  8055. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  8056. here_bits = here >>> 24;
  8057. here_op = (here >>> 16) & 0xff;
  8058. here_val = here & 0xffff;
  8059. if ((here_bits) <= bits) { break; }
  8060. //--- PULLBYTE() ---//
  8061. if (have === 0) { break inf_leave; }
  8062. have--;
  8063. hold += input[next++] << bits;
  8064. bits += 8;
  8065. //---//
  8066. }
  8067. if (here_val < 16) {
  8068. //--- DROPBITS(here.bits) ---//
  8069. hold >>>= here_bits;
  8070. bits -= here_bits;
  8071. //---//
  8072. state.lens[state.have++] = here_val;
  8073. }
  8074. else {
  8075. if (here_val === 16) {
  8076. //=== NEEDBITS(here.bits + 2);
  8077. n = here_bits + 2;
  8078. while (bits < n) {
  8079. if (have === 0) { break inf_leave; }
  8080. have--;
  8081. hold += input[next++] << bits;
  8082. bits += 8;
  8083. }
  8084. //===//
  8085. //--- DROPBITS(here.bits) ---//
  8086. hold >>>= here_bits;
  8087. bits -= here_bits;
  8088. //---//
  8089. if (state.have === 0) {
  8090. strm.msg = 'invalid bit length repeat';
  8091. state.mode = BAD;
  8092. break;
  8093. }
  8094. len = state.lens[state.have - 1];
  8095. copy = 3 + (hold & 0x03);//BITS(2);
  8096. //--- DROPBITS(2) ---//
  8097. hold >>>= 2;
  8098. bits -= 2;
  8099. //---//
  8100. }
  8101. else if (here_val === 17) {
  8102. //=== NEEDBITS(here.bits + 3);
  8103. n = here_bits + 3;
  8104. while (bits < n) {
  8105. if (have === 0) { break inf_leave; }
  8106. have--;
  8107. hold += input[next++] << bits;
  8108. bits += 8;
  8109. }
  8110. //===//
  8111. //--- DROPBITS(here.bits) ---//
  8112. hold >>>= here_bits;
  8113. bits -= here_bits;
  8114. //---//
  8115. len = 0;
  8116. copy = 3 + (hold & 0x07);//BITS(3);
  8117. //--- DROPBITS(3) ---//
  8118. hold >>>= 3;
  8119. bits -= 3;
  8120. //---//
  8121. }
  8122. else {
  8123. //=== NEEDBITS(here.bits + 7);
  8124. n = here_bits + 7;
  8125. while (bits < n) {
  8126. if (have === 0) { break inf_leave; }
  8127. have--;
  8128. hold += input[next++] << bits;
  8129. bits += 8;
  8130. }
  8131. //===//
  8132. //--- DROPBITS(here.bits) ---//
  8133. hold >>>= here_bits;
  8134. bits -= here_bits;
  8135. //---//
  8136. len = 0;
  8137. copy = 11 + (hold & 0x7f);//BITS(7);
  8138. //--- DROPBITS(7) ---//
  8139. hold >>>= 7;
  8140. bits -= 7;
  8141. //---//
  8142. }
  8143. if (state.have + copy > state.nlen + state.ndist) {
  8144. strm.msg = 'invalid bit length repeat';
  8145. state.mode = BAD;
  8146. break;
  8147. }
  8148. while (copy--) {
  8149. state.lens[state.have++] = len;
  8150. }
  8151. }
  8152. }
  8153. /* handle error breaks in while */
  8154. if (state.mode === BAD) { break; }
  8155. /* check for end-of-block code (better have one) */
  8156. if (state.lens[256] === 0) {
  8157. strm.msg = 'invalid code -- missing end-of-block';
  8158. state.mode = BAD;
  8159. break;
  8160. }
  8161. /* build code tables -- note: do not change the lenbits or distbits
  8162. values here (9 and 6) without reading the comments in inftrees.h
  8163. concerning the ENOUGH constants, which depend on those values */
  8164. state.lenbits = 9;
  8165. opts = { bits: state.lenbits };
  8166. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  8167. // We have separate tables & no pointers. 2 commented lines below not needed.
  8168. // state.next_index = opts.table_index;
  8169. state.lenbits = opts.bits;
  8170. // state.lencode = state.next;
  8171. if (ret) {
  8172. strm.msg = 'invalid literal/lengths set';
  8173. state.mode = BAD;
  8174. break;
  8175. }
  8176. state.distbits = 6;
  8177. //state.distcode.copy(state.codes);
  8178. // Switch to use dynamic table
  8179. state.distcode = state.distdyn;
  8180. opts = { bits: state.distbits };
  8181. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  8182. // We have separate tables & no pointers. 2 commented lines below not needed.
  8183. // state.next_index = opts.table_index;
  8184. state.distbits = opts.bits;
  8185. // state.distcode = state.next;
  8186. if (ret) {
  8187. strm.msg = 'invalid distances set';
  8188. state.mode = BAD;
  8189. break;
  8190. }
  8191. //Tracev((stderr, 'inflate: codes ok\n'));
  8192. state.mode = LEN_;
  8193. if (flush === Z_TREES) { break inf_leave; }
  8194. /* falls through */
  8195. case LEN_:
  8196. state.mode = LEN;
  8197. /* falls through */
  8198. case LEN:
  8199. if (have >= 6 && left >= 258) {
  8200. //--- RESTORE() ---
  8201. strm.next_out = put;
  8202. strm.avail_out = left;
  8203. strm.next_in = next;
  8204. strm.avail_in = have;
  8205. state.hold = hold;
  8206. state.bits = bits;
  8207. //---
  8208. inflate_fast(strm, _out);
  8209. //--- LOAD() ---
  8210. put = strm.next_out;
  8211. output = strm.output;
  8212. left = strm.avail_out;
  8213. next = strm.next_in;
  8214. input = strm.input;
  8215. have = strm.avail_in;
  8216. hold = state.hold;
  8217. bits = state.bits;
  8218. //---
  8219. if (state.mode === TYPE) {
  8220. state.back = -1;
  8221. }
  8222. break;
  8223. }
  8224. state.back = 0;
  8225. for (;;) {
  8226. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  8227. here_bits = here >>> 24;
  8228. here_op = (here >>> 16) & 0xff;
  8229. here_val = here & 0xffff;
  8230. if (here_bits <= bits) { break; }
  8231. //--- PULLBYTE() ---//
  8232. if (have === 0) { break inf_leave; }
  8233. have--;
  8234. hold += input[next++] << bits;
  8235. bits += 8;
  8236. //---//
  8237. }
  8238. if (here_op && (here_op & 0xf0) === 0) {
  8239. last_bits = here_bits;
  8240. last_op = here_op;
  8241. last_val = here_val;
  8242. for (;;) {
  8243. here = state.lencode[last_val +
  8244. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  8245. here_bits = here >>> 24;
  8246. here_op = (here >>> 16) & 0xff;
  8247. here_val = here & 0xffff;
  8248. if ((last_bits + here_bits) <= bits) { break; }
  8249. //--- PULLBYTE() ---//
  8250. if (have === 0) { break inf_leave; }
  8251. have--;
  8252. hold += input[next++] << bits;
  8253. bits += 8;
  8254. //---//
  8255. }
  8256. //--- DROPBITS(last.bits) ---//
  8257. hold >>>= last_bits;
  8258. bits -= last_bits;
  8259. //---//
  8260. state.back += last_bits;
  8261. }
  8262. //--- DROPBITS(here.bits) ---//
  8263. hold >>>= here_bits;
  8264. bits -= here_bits;
  8265. //---//
  8266. state.back += here_bits;
  8267. state.length = here_val;
  8268. if (here_op === 0) {
  8269. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  8270. // "inflate: literal '%c'\n" :
  8271. // "inflate: literal 0x%02x\n", here.val));
  8272. state.mode = LIT;
  8273. break;
  8274. }
  8275. if (here_op & 32) {
  8276. //Tracevv((stderr, "inflate: end of block\n"));
  8277. state.back = -1;
  8278. state.mode = TYPE;
  8279. break;
  8280. }
  8281. if (here_op & 64) {
  8282. strm.msg = 'invalid literal/length code';
  8283. state.mode = BAD;
  8284. break;
  8285. }
  8286. state.extra = here_op & 15;
  8287. state.mode = LENEXT;
  8288. /* falls through */
  8289. case LENEXT:
  8290. if (state.extra) {
  8291. //=== NEEDBITS(state.extra);
  8292. n = state.extra;
  8293. while (bits < n) {
  8294. if (have === 0) { break inf_leave; }
  8295. have--;
  8296. hold += input[next++] << bits;
  8297. bits += 8;
  8298. }
  8299. //===//
  8300. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  8301. //--- DROPBITS(state.extra) ---//
  8302. hold >>>= state.extra;
  8303. bits -= state.extra;
  8304. //---//
  8305. state.back += state.extra;
  8306. }
  8307. //Tracevv((stderr, "inflate: length %u\n", state.length));
  8308. state.was = state.length;
  8309. state.mode = DIST;
  8310. /* falls through */
  8311. case DIST:
  8312. for (;;) {
  8313. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  8314. here_bits = here >>> 24;
  8315. here_op = (here >>> 16) & 0xff;
  8316. here_val = here & 0xffff;
  8317. if ((here_bits) <= bits) { break; }
  8318. //--- PULLBYTE() ---//
  8319. if (have === 0) { break inf_leave; }
  8320. have--;
  8321. hold += input[next++] << bits;
  8322. bits += 8;
  8323. //---//
  8324. }
  8325. if ((here_op & 0xf0) === 0) {
  8326. last_bits = here_bits;
  8327. last_op = here_op;
  8328. last_val = here_val;
  8329. for (;;) {
  8330. here = state.distcode[last_val +
  8331. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  8332. here_bits = here >>> 24;
  8333. here_op = (here >>> 16) & 0xff;
  8334. here_val = here & 0xffff;
  8335. if ((last_bits + here_bits) <= bits) { break; }
  8336. //--- PULLBYTE() ---//
  8337. if (have === 0) { break inf_leave; }
  8338. have--;
  8339. hold += input[next++] << bits;
  8340. bits += 8;
  8341. //---//
  8342. }
  8343. //--- DROPBITS(last.bits) ---//
  8344. hold >>>= last_bits;
  8345. bits -= last_bits;
  8346. //---//
  8347. state.back += last_bits;
  8348. }
  8349. //--- DROPBITS(here.bits) ---//
  8350. hold >>>= here_bits;
  8351. bits -= here_bits;
  8352. //---//
  8353. state.back += here_bits;
  8354. if (here_op & 64) {
  8355. strm.msg = 'invalid distance code';
  8356. state.mode = BAD;
  8357. break;
  8358. }
  8359. state.offset = here_val;
  8360. state.extra = (here_op) & 15;
  8361. state.mode = DISTEXT;
  8362. /* falls through */
  8363. case DISTEXT:
  8364. if (state.extra) {
  8365. //=== NEEDBITS(state.extra);
  8366. n = state.extra;
  8367. while (bits < n) {
  8368. if (have === 0) { break inf_leave; }
  8369. have--;
  8370. hold += input[next++] << bits;
  8371. bits += 8;
  8372. }
  8373. //===//
  8374. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  8375. //--- DROPBITS(state.extra) ---//
  8376. hold >>>= state.extra;
  8377. bits -= state.extra;
  8378. //---//
  8379. state.back += state.extra;
  8380. }
  8381. //#ifdef INFLATE_STRICT
  8382. if (state.offset > state.dmax) {
  8383. strm.msg = 'invalid distance too far back';
  8384. state.mode = BAD;
  8385. break;
  8386. }
  8387. //#endif
  8388. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  8389. state.mode = MATCH;
  8390. /* falls through */
  8391. case MATCH:
  8392. if (left === 0) { break inf_leave; }
  8393. copy = _out - left;
  8394. if (state.offset > copy) { /* copy from window */
  8395. copy = state.offset - copy;
  8396. if (copy > state.whave) {
  8397. if (state.sane) {
  8398. strm.msg = 'invalid distance too far back';
  8399. state.mode = BAD;
  8400. break;
  8401. }
  8402. // (!) This block is disabled in zlib defailts,
  8403. // don't enable it for binary compatibility
  8404. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  8405. // Trace((stderr, "inflate.c too far\n"));
  8406. // copy -= state.whave;
  8407. // if (copy > state.length) { copy = state.length; }
  8408. // if (copy > left) { copy = left; }
  8409. // left -= copy;
  8410. // state.length -= copy;
  8411. // do {
  8412. // output[put++] = 0;
  8413. // } while (--copy);
  8414. // if (state.length === 0) { state.mode = LEN; }
  8415. // break;
  8416. //#endif
  8417. }
  8418. if (copy > state.wnext) {
  8419. copy -= state.wnext;
  8420. from = state.wsize - copy;
  8421. }
  8422. else {
  8423. from = state.wnext - copy;
  8424. }
  8425. if (copy > state.length) { copy = state.length; }
  8426. from_source = state.window;
  8427. }
  8428. else { /* copy from output */
  8429. from_source = output;
  8430. from = put - state.offset;
  8431. copy = state.length;
  8432. }
  8433. if (copy > left) { copy = left; }
  8434. left -= copy;
  8435. state.length -= copy;
  8436. do {
  8437. output[put++] = from_source[from++];
  8438. } while (--copy);
  8439. if (state.length === 0) { state.mode = LEN; }
  8440. break;
  8441. case LIT:
  8442. if (left === 0) { break inf_leave; }
  8443. output[put++] = state.length;
  8444. left--;
  8445. state.mode = LEN;
  8446. break;
  8447. case CHECK:
  8448. if (state.wrap) {
  8449. //=== NEEDBITS(32);
  8450. while (bits < 32) {
  8451. if (have === 0) { break inf_leave; }
  8452. have--;
  8453. // Use '|' insdead of '+' to make sure that result is signed
  8454. hold |= input[next++] << bits;
  8455. bits += 8;
  8456. }
  8457. //===//
  8458. _out -= left;
  8459. strm.total_out += _out;
  8460. state.total += _out;
  8461. if (_out) {
  8462. strm.adler = state.check =
  8463. /*UPDATE(state.check, put - _out, _out);*/
  8464. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  8465. }
  8466. _out = left;
  8467. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  8468. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  8469. strm.msg = 'incorrect data check';
  8470. state.mode = BAD;
  8471. break;
  8472. }
  8473. //=== INITBITS();
  8474. hold = 0;
  8475. bits = 0;
  8476. //===//
  8477. //Tracev((stderr, "inflate: check matches trailer\n"));
  8478. }
  8479. state.mode = LENGTH;
  8480. /* falls through */
  8481. case LENGTH:
  8482. if (state.wrap && state.flags) {
  8483. //=== NEEDBITS(32);
  8484. while (bits < 32) {
  8485. if (have === 0) { break inf_leave; }
  8486. have--;
  8487. hold += input[next++] << bits;
  8488. bits += 8;
  8489. }
  8490. //===//
  8491. if (hold !== (state.total & 0xffffffff)) {
  8492. strm.msg = 'incorrect length check';
  8493. state.mode = BAD;
  8494. break;
  8495. }
  8496. //=== INITBITS();
  8497. hold = 0;
  8498. bits = 0;
  8499. //===//
  8500. //Tracev((stderr, "inflate: length matches trailer\n"));
  8501. }
  8502. state.mode = DONE;
  8503. /* falls through */
  8504. case DONE:
  8505. ret = Z_STREAM_END;
  8506. break inf_leave;
  8507. case BAD:
  8508. ret = Z_DATA_ERROR;
  8509. break inf_leave;
  8510. case MEM:
  8511. return Z_MEM_ERROR;
  8512. case SYNC:
  8513. /* falls through */
  8514. default:
  8515. return Z_STREAM_ERROR;
  8516. }
  8517. }
  8518. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  8519. /*
  8520. Return from inflate(), updating the total counts and the check value.
  8521. If there was no progress during the inflate() call, return a buffer
  8522. error. Call updatewindow() to create and/or update the window state.
  8523. Note: a memory error from inflate() is non-recoverable.
  8524. */
  8525. //--- RESTORE() ---
  8526. strm.next_out = put;
  8527. strm.avail_out = left;
  8528. strm.next_in = next;
  8529. strm.avail_in = have;
  8530. state.hold = hold;
  8531. state.bits = bits;
  8532. //---
  8533. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  8534. (state.mode < CHECK || flush !== Z_FINISH))) {
  8535. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  8536. state.mode = MEM;
  8537. return Z_MEM_ERROR;
  8538. }
  8539. }
  8540. _in -= strm.avail_in;
  8541. _out -= strm.avail_out;
  8542. strm.total_in += _in;
  8543. strm.total_out += _out;
  8544. state.total += _out;
  8545. if (state.wrap && _out) {
  8546. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  8547. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  8548. }
  8549. strm.data_type = state.bits + (state.last ? 64 : 0) +
  8550. (state.mode === TYPE ? 128 : 0) +
  8551. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  8552. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  8553. ret = Z_BUF_ERROR;
  8554. }
  8555. return ret;
  8556. }
  8557. function inflateEnd(strm) {
  8558. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  8559. return Z_STREAM_ERROR;
  8560. }
  8561. var state = strm.state;
  8562. if (state.window) {
  8563. state.window = null;
  8564. }
  8565. strm.state = null;
  8566. return Z_OK;
  8567. }
  8568. function inflateGetHeader(strm, head) {
  8569. var state;
  8570. /* check state */
  8571. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  8572. state = strm.state;
  8573. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  8574. /* save header structure */
  8575. state.head = head;
  8576. head.done = false;
  8577. return Z_OK;
  8578. }
  8579. function inflateSetDictionary(strm, dictionary) {
  8580. var dictLength = dictionary.length;
  8581. var state;
  8582. var dictid;
  8583. var ret;
  8584. /* check state */
  8585. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  8586. state = strm.state;
  8587. if (state.wrap !== 0 && state.mode !== DICT) {
  8588. return Z_STREAM_ERROR;
  8589. }
  8590. /* check for correct dictionary identifier */
  8591. if (state.mode === DICT) {
  8592. dictid = 1; /* adler32(0, null, 0)*/
  8593. /* dictid = adler32(dictid, dictionary, dictLength); */
  8594. dictid = adler32(dictid, dictionary, dictLength, 0);
  8595. if (dictid !== state.check) {
  8596. return Z_DATA_ERROR;
  8597. }
  8598. }
  8599. /* copy dictionary to window using updatewindow(), which will amend the
  8600. existing dictionary if appropriate */
  8601. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  8602. if (ret) {
  8603. state.mode = MEM;
  8604. return Z_MEM_ERROR;
  8605. }
  8606. state.havedict = 1;
  8607. // Tracev((stderr, "inflate: dictionary set\n"));
  8608. return Z_OK;
  8609. }
  8610. exports.inflateReset = inflateReset;
  8611. exports.inflateReset2 = inflateReset2;
  8612. exports.inflateResetKeep = inflateResetKeep;
  8613. exports.inflateInit = inflateInit;
  8614. exports.inflateInit2 = inflateInit2;
  8615. exports.inflate = inflate;
  8616. exports.inflateEnd = inflateEnd;
  8617. exports.inflateGetHeader = inflateGetHeader;
  8618. exports.inflateSetDictionary = inflateSetDictionary;
  8619. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  8620. /* Not implemented
  8621. exports.inflateCopy = inflateCopy;
  8622. exports.inflateGetDictionary = inflateGetDictionary;
  8623. exports.inflateMark = inflateMark;
  8624. exports.inflatePrime = inflatePrime;
  8625. exports.inflateSync = inflateSync;
  8626. exports.inflateSyncPoint = inflateSyncPoint;
  8627. exports.inflateUndermine = inflateUndermine;
  8628. */
  8629. },{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(require,module,exports){
  8630. 'use strict';
  8631. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8632. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8633. //
  8634. // This software is provided 'as-is', without any express or implied
  8635. // warranty. In no event will the authors be held liable for any damages
  8636. // arising from the use of this software.
  8637. //
  8638. // Permission is granted to anyone to use this software for any purpose,
  8639. // including commercial applications, and to alter it and redistribute it
  8640. // freely, subject to the following restrictions:
  8641. //
  8642. // 1. The origin of this software must not be misrepresented; you must not
  8643. // claim that you wrote the original software. If you use this software
  8644. // in a product, an acknowledgment in the product documentation would be
  8645. // appreciated but is not required.
  8646. // 2. Altered source versions must be plainly marked as such, and must not be
  8647. // misrepresented as being the original software.
  8648. // 3. This notice may not be removed or altered from any source distribution.
  8649. var utils = require('../utils/common');
  8650. var MAXBITS = 15;
  8651. var ENOUGH_LENS = 852;
  8652. var ENOUGH_DISTS = 592;
  8653. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  8654. var CODES = 0;
  8655. var LENS = 1;
  8656. var DISTS = 2;
  8657. var lbase = [ /* Length codes 257..285 base */
  8658. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  8659. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  8660. ];
  8661. var lext = [ /* Length codes 257..285 extra */
  8662. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  8663. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  8664. ];
  8665. var dbase = [ /* Distance codes 0..29 base */
  8666. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  8667. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  8668. 8193, 12289, 16385, 24577, 0, 0
  8669. ];
  8670. var dext = [ /* Distance codes 0..29 extra */
  8671. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  8672. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  8673. 28, 28, 29, 29, 64, 64
  8674. ];
  8675. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  8676. {
  8677. var bits = opts.bits;
  8678. //here = opts.here; /* table entry for duplication */
  8679. var len = 0; /* a code's length in bits */
  8680. var sym = 0; /* index of code symbols */
  8681. var min = 0, max = 0; /* minimum and maximum code lengths */
  8682. var root = 0; /* number of index bits for root table */
  8683. var curr = 0; /* number of index bits for current table */
  8684. var drop = 0; /* code bits to drop for sub-table */
  8685. var left = 0; /* number of prefix codes available */
  8686. var used = 0; /* code entries in table used */
  8687. var huff = 0; /* Huffman code */
  8688. var incr; /* for incrementing code, index */
  8689. var fill; /* index for replicating entries */
  8690. var low; /* low bits for current root entry */
  8691. var mask; /* mask for low root bits */
  8692. var next; /* next available space in table */
  8693. var base = null; /* base value table to use */
  8694. var base_index = 0;
  8695. // var shoextra; /* extra bits table to use */
  8696. var end; /* use base and extra for symbol > end */
  8697. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  8698. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  8699. var extra = null;
  8700. var extra_index = 0;
  8701. var here_bits, here_op, here_val;
  8702. /*
  8703. Process a set of code lengths to create a canonical Huffman code. The
  8704. code lengths are lens[0..codes-1]. Each length corresponds to the
  8705. symbols 0..codes-1. The Huffman code is generated by first sorting the
  8706. symbols by length from short to long, and retaining the symbol order
  8707. for codes with equal lengths. Then the code starts with all zero bits
  8708. for the first code of the shortest length, and the codes are integer
  8709. increments for the same length, and zeros are appended as the length
  8710. increases. For the deflate format, these bits are stored backwards
  8711. from their more natural integer increment ordering, and so when the
  8712. decoding tables are built in the large loop below, the integer codes
  8713. are incremented backwards.
  8714. This routine assumes, but does not check, that all of the entries in
  8715. lens[] are in the range 0..MAXBITS. The caller must assure this.
  8716. 1..MAXBITS is interpreted as that code length. zero means that that
  8717. symbol does not occur in this code.
  8718. The codes are sorted by computing a count of codes for each length,
  8719. creating from that a table of starting indices for each length in the
  8720. sorted table, and then entering the symbols in order in the sorted
  8721. table. The sorted table is work[], with that space being provided by
  8722. the caller.
  8723. The length counts are used for other purposes as well, i.e. finding
  8724. the minimum and maximum length codes, determining if there are any
  8725. codes at all, checking for a valid set of lengths, and looking ahead
  8726. at length counts to determine sub-table sizes when building the
  8727. decoding tables.
  8728. */
  8729. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  8730. for (len = 0; len <= MAXBITS; len++) {
  8731. count[len] = 0;
  8732. }
  8733. for (sym = 0; sym < codes; sym++) {
  8734. count[lens[lens_index + sym]]++;
  8735. }
  8736. /* bound code lengths, force root to be within code lengths */
  8737. root = bits;
  8738. for (max = MAXBITS; max >= 1; max--) {
  8739. if (count[max] !== 0) { break; }
  8740. }
  8741. if (root > max) {
  8742. root = max;
  8743. }
  8744. if (max === 0) { /* no symbols to code at all */
  8745. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  8746. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  8747. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  8748. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  8749. //table.op[opts.table_index] = 64;
  8750. //table.bits[opts.table_index] = 1;
  8751. //table.val[opts.table_index++] = 0;
  8752. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  8753. opts.bits = 1;
  8754. return 0; /* no symbols, but wait for decoding to report error */
  8755. }
  8756. for (min = 1; min < max; min++) {
  8757. if (count[min] !== 0) { break; }
  8758. }
  8759. if (root < min) {
  8760. root = min;
  8761. }
  8762. /* check for an over-subscribed or incomplete set of lengths */
  8763. left = 1;
  8764. for (len = 1; len <= MAXBITS; len++) {
  8765. left <<= 1;
  8766. left -= count[len];
  8767. if (left < 0) {
  8768. return -1;
  8769. } /* over-subscribed */
  8770. }
  8771. if (left > 0 && (type === CODES || max !== 1)) {
  8772. return -1; /* incomplete set */
  8773. }
  8774. /* generate offsets into symbol table for each length for sorting */
  8775. offs[1] = 0;
  8776. for (len = 1; len < MAXBITS; len++) {
  8777. offs[len + 1] = offs[len] + count[len];
  8778. }
  8779. /* sort symbols by length, by symbol order within each length */
  8780. for (sym = 0; sym < codes; sym++) {
  8781. if (lens[lens_index + sym] !== 0) {
  8782. work[offs[lens[lens_index + sym]]++] = sym;
  8783. }
  8784. }
  8785. /*
  8786. Create and fill in decoding tables. In this loop, the table being
  8787. filled is at next and has curr index bits. The code being used is huff
  8788. with length len. That code is converted to an index by dropping drop
  8789. bits off of the bottom. For codes where len is less than drop + curr,
  8790. those top drop + curr - len bits are incremented through all values to
  8791. fill the table with replicated entries.
  8792. root is the number of index bits for the root table. When len exceeds
  8793. root, sub-tables are created pointed to by the root entry with an index
  8794. of the low root bits of huff. This is saved in low to check for when a
  8795. new sub-table should be started. drop is zero when the root table is
  8796. being filled, and drop is root when sub-tables are being filled.
  8797. When a new sub-table is needed, it is necessary to look ahead in the
  8798. code lengths to determine what size sub-table is needed. The length
  8799. counts are used for this, and so count[] is decremented as codes are
  8800. entered in the tables.
  8801. used keeps track of how many table entries have been allocated from the
  8802. provided *table space. It is checked for LENS and DIST tables against
  8803. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  8804. the initial root table size constants. See the comments in inftrees.h
  8805. for more information.
  8806. sym increments through all symbols, and the loop terminates when
  8807. all codes of length max, i.e. all codes, have been processed. This
  8808. routine permits incomplete codes, so another loop after this one fills
  8809. in the rest of the decoding tables with invalid code markers.
  8810. */
  8811. /* set up for code type */
  8812. // poor man optimization - use if-else instead of switch,
  8813. // to avoid deopts in old v8
  8814. if (type === CODES) {
  8815. base = extra = work; /* dummy value--not used */
  8816. end = 19;
  8817. } else if (type === LENS) {
  8818. base = lbase;
  8819. base_index -= 257;
  8820. extra = lext;
  8821. extra_index -= 257;
  8822. end = 256;
  8823. } else { /* DISTS */
  8824. base = dbase;
  8825. extra = dext;
  8826. end = -1;
  8827. }
  8828. /* initialize opts for loop */
  8829. huff = 0; /* starting code */
  8830. sym = 0; /* starting code symbol */
  8831. len = min; /* starting code length */
  8832. next = table_index; /* current table to fill in */
  8833. curr = root; /* current table index bits */
  8834. drop = 0; /* current bits to drop from code for index */
  8835. low = -1; /* trigger new sub-table when len > root */
  8836. used = 1 << root; /* use root table entries */
  8837. mask = used - 1; /* mask for comparing low */
  8838. /* check available table space */
  8839. if ((type === LENS && used > ENOUGH_LENS) ||
  8840. (type === DISTS && used > ENOUGH_DISTS)) {
  8841. return 1;
  8842. }
  8843. /* process all codes and make table entries */
  8844. for (;;) {
  8845. /* create table entry */
  8846. here_bits = len - drop;
  8847. if (work[sym] < end) {
  8848. here_op = 0;
  8849. here_val = work[sym];
  8850. }
  8851. else if (work[sym] > end) {
  8852. here_op = extra[extra_index + work[sym]];
  8853. here_val = base[base_index + work[sym]];
  8854. }
  8855. else {
  8856. here_op = 32 + 64; /* end of block */
  8857. here_val = 0;
  8858. }
  8859. /* replicate for those indices with low len bits equal to huff */
  8860. incr = 1 << (len - drop);
  8861. fill = 1 << curr;
  8862. min = fill; /* save offset to next table */
  8863. do {
  8864. fill -= incr;
  8865. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  8866. } while (fill !== 0);
  8867. /* backwards increment the len-bit code huff */
  8868. incr = 1 << (len - 1);
  8869. while (huff & incr) {
  8870. incr >>= 1;
  8871. }
  8872. if (incr !== 0) {
  8873. huff &= incr - 1;
  8874. huff += incr;
  8875. } else {
  8876. huff = 0;
  8877. }
  8878. /* go to next symbol, update count, len */
  8879. sym++;
  8880. if (--count[len] === 0) {
  8881. if (len === max) { break; }
  8882. len = lens[lens_index + work[sym]];
  8883. }
  8884. /* create new sub-table if needed */
  8885. if (len > root && (huff & mask) !== low) {
  8886. /* if first time, transition to sub-tables */
  8887. if (drop === 0) {
  8888. drop = root;
  8889. }
  8890. /* increment past last table */
  8891. next += min; /* here min is 1 << curr */
  8892. /* determine length of next table */
  8893. curr = len - drop;
  8894. left = 1 << curr;
  8895. while (curr + drop < max) {
  8896. left -= count[curr + drop];
  8897. if (left <= 0) { break; }
  8898. curr++;
  8899. left <<= 1;
  8900. }
  8901. /* check for enough space */
  8902. used += 1 << curr;
  8903. if ((type === LENS && used > ENOUGH_LENS) ||
  8904. (type === DISTS && used > ENOUGH_DISTS)) {
  8905. return 1;
  8906. }
  8907. /* point entry in root table to sub-table */
  8908. low = huff & mask;
  8909. /*table.op[low] = curr;
  8910. table.bits[low] = root;
  8911. table.val[low] = next - opts.table_index;*/
  8912. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  8913. }
  8914. }
  8915. /* fill in remaining table entry if code is incomplete (guaranteed to have
  8916. at most one remaining entry, since if the code is incomplete, the
  8917. maximum code length that was allowed to get this far is one bit) */
  8918. if (huff !== 0) {
  8919. //table.op[next + huff] = 64; /* invalid code marker */
  8920. //table.bits[next + huff] = len - drop;
  8921. //table.val[next + huff] = 0;
  8922. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  8923. }
  8924. /* set return parameters */
  8925. //opts.table_index += used;
  8926. opts.bits = root;
  8927. return 0;
  8928. };
  8929. },{"../utils/common":41}],51:[function(require,module,exports){
  8930. 'use strict';
  8931. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8932. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8933. //
  8934. // This software is provided 'as-is', without any express or implied
  8935. // warranty. In no event will the authors be held liable for any damages
  8936. // arising from the use of this software.
  8937. //
  8938. // Permission is granted to anyone to use this software for any purpose,
  8939. // including commercial applications, and to alter it and redistribute it
  8940. // freely, subject to the following restrictions:
  8941. //
  8942. // 1. The origin of this software must not be misrepresented; you must not
  8943. // claim that you wrote the original software. If you use this software
  8944. // in a product, an acknowledgment in the product documentation would be
  8945. // appreciated but is not required.
  8946. // 2. Altered source versions must be plainly marked as such, and must not be
  8947. // misrepresented as being the original software.
  8948. // 3. This notice may not be removed or altered from any source distribution.
  8949. module.exports = {
  8950. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  8951. 1: 'stream end', /* Z_STREAM_END 1 */
  8952. 0: '', /* Z_OK 0 */
  8953. '-1': 'file error', /* Z_ERRNO (-1) */
  8954. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  8955. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  8956. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  8957. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  8958. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  8959. };
  8960. },{}],52:[function(require,module,exports){
  8961. 'use strict';
  8962. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  8963. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  8964. //
  8965. // This software is provided 'as-is', without any express or implied
  8966. // warranty. In no event will the authors be held liable for any damages
  8967. // arising from the use of this software.
  8968. //
  8969. // Permission is granted to anyone to use this software for any purpose,
  8970. // including commercial applications, and to alter it and redistribute it
  8971. // freely, subject to the following restrictions:
  8972. //
  8973. // 1. The origin of this software must not be misrepresented; you must not
  8974. // claim that you wrote the original software. If you use this software
  8975. // in a product, an acknowledgment in the product documentation would be
  8976. // appreciated but is not required.
  8977. // 2. Altered source versions must be plainly marked as such, and must not be
  8978. // misrepresented as being the original software.
  8979. // 3. This notice may not be removed or altered from any source distribution.
  8980. var utils = require('../utils/common');
  8981. /* Public constants ==========================================================*/
  8982. /* ===========================================================================*/
  8983. //var Z_FILTERED = 1;
  8984. //var Z_HUFFMAN_ONLY = 2;
  8985. //var Z_RLE = 3;
  8986. var Z_FIXED = 4;
  8987. //var Z_DEFAULT_STRATEGY = 0;
  8988. /* Possible values of the data_type field (though see inflate()) */
  8989. var Z_BINARY = 0;
  8990. var Z_TEXT = 1;
  8991. //var Z_ASCII = 1; // = Z_TEXT
  8992. var Z_UNKNOWN = 2;
  8993. /*============================================================================*/
  8994. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  8995. // From zutil.h
  8996. var STORED_BLOCK = 0;
  8997. var STATIC_TREES = 1;
  8998. var DYN_TREES = 2;
  8999. /* The three kinds of block type */
  9000. var MIN_MATCH = 3;
  9001. var MAX_MATCH = 258;
  9002. /* The minimum and maximum match lengths */
  9003. // From deflate.h
  9004. /* ===========================================================================
  9005. * Internal compression state.
  9006. */
  9007. var LENGTH_CODES = 29;
  9008. /* number of length codes, not counting the special END_BLOCK code */
  9009. var LITERALS = 256;
  9010. /* number of literal bytes 0..255 */
  9011. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  9012. /* number of Literal or Length codes, including the END_BLOCK code */
  9013. var D_CODES = 30;
  9014. /* number of distance codes */
  9015. var BL_CODES = 19;
  9016. /* number of codes used to transfer the bit lengths */
  9017. var HEAP_SIZE = 2 * L_CODES + 1;
  9018. /* maximum heap size */
  9019. var MAX_BITS = 15;
  9020. /* All codes must not exceed MAX_BITS bits */
  9021. var Buf_size = 16;
  9022. /* size of bit buffer in bi_buf */
  9023. /* ===========================================================================
  9024. * Constants
  9025. */
  9026. var MAX_BL_BITS = 7;
  9027. /* Bit length codes must not exceed MAX_BL_BITS bits */
  9028. var END_BLOCK = 256;
  9029. /* end of block literal code */
  9030. var REP_3_6 = 16;
  9031. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  9032. var REPZ_3_10 = 17;
  9033. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  9034. var REPZ_11_138 = 18;
  9035. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  9036. /* eslint-disable comma-spacing,array-bracket-spacing */
  9037. var extra_lbits = /* extra bits for each length code */
  9038. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  9039. var extra_dbits = /* extra bits for each distance code */
  9040. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  9041. var extra_blbits = /* extra bits for each bit length code */
  9042. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  9043. var bl_order =
  9044. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  9045. /* eslint-enable comma-spacing,array-bracket-spacing */
  9046. /* The lengths of the bit length codes are sent in order of decreasing
  9047. * probability, to avoid transmitting the lengths for unused bit length codes.
  9048. */
  9049. /* ===========================================================================
  9050. * Local data. These are initialized only once.
  9051. */
  9052. // We pre-fill arrays with 0 to avoid uninitialized gaps
  9053. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  9054. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  9055. var static_ltree = new Array((L_CODES + 2) * 2);
  9056. zero(static_ltree);
  9057. /* The static literal tree. Since the bit lengths are imposed, there is no
  9058. * need for the L_CODES extra codes used during heap construction. However
  9059. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  9060. * below).
  9061. */
  9062. var static_dtree = new Array(D_CODES * 2);
  9063. zero(static_dtree);
  9064. /* The static distance tree. (Actually a trivial tree since all codes use
  9065. * 5 bits.)
  9066. */
  9067. var _dist_code = new Array(DIST_CODE_LEN);
  9068. zero(_dist_code);
  9069. /* Distance codes. The first 256 values correspond to the distances
  9070. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  9071. * the 15 bit distances.
  9072. */
  9073. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  9074. zero(_length_code);
  9075. /* length code for each normalized match length (0 == MIN_MATCH) */
  9076. var base_length = new Array(LENGTH_CODES);
  9077. zero(base_length);
  9078. /* First normalized length for each code (0 = MIN_MATCH) */
  9079. var base_dist = new Array(D_CODES);
  9080. zero(base_dist);
  9081. /* First normalized distance for each code (0 = distance of 1) */
  9082. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  9083. this.static_tree = static_tree; /* static tree or NULL */
  9084. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  9085. this.extra_base = extra_base; /* base index for extra_bits */
  9086. this.elems = elems; /* max number of elements in the tree */
  9087. this.max_length = max_length; /* max bit length for the codes */
  9088. // show if `static_tree` has data or dummy - needed for monomorphic objects
  9089. this.has_stree = static_tree && static_tree.length;
  9090. }
  9091. var static_l_desc;
  9092. var static_d_desc;
  9093. var static_bl_desc;
  9094. function TreeDesc(dyn_tree, stat_desc) {
  9095. this.dyn_tree = dyn_tree; /* the dynamic tree */
  9096. this.max_code = 0; /* largest code with non zero frequency */
  9097. this.stat_desc = stat_desc; /* the corresponding static tree */
  9098. }
  9099. function d_code(dist) {
  9100. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  9101. }
  9102. /* ===========================================================================
  9103. * Output a short LSB first on the stream.
  9104. * IN assertion: there is enough room in pendingBuf.
  9105. */
  9106. function put_short(s, w) {
  9107. // put_byte(s, (uch)((w) & 0xff));
  9108. // put_byte(s, (uch)((ush)(w) >> 8));
  9109. s.pending_buf[s.pending++] = (w) & 0xff;
  9110. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  9111. }
  9112. /* ===========================================================================
  9113. * Send a value on a given number of bits.
  9114. * IN assertion: length <= 16 and value fits in length bits.
  9115. */
  9116. function send_bits(s, value, length) {
  9117. if (s.bi_valid > (Buf_size - length)) {
  9118. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  9119. put_short(s, s.bi_buf);
  9120. s.bi_buf = value >> (Buf_size - s.bi_valid);
  9121. s.bi_valid += length - Buf_size;
  9122. } else {
  9123. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  9124. s.bi_valid += length;
  9125. }
  9126. }
  9127. function send_code(s, c, tree) {
  9128. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  9129. }
  9130. /* ===========================================================================
  9131. * Reverse the first len bits of a code, using straightforward code (a faster
  9132. * method would use a table)
  9133. * IN assertion: 1 <= len <= 15
  9134. */
  9135. function bi_reverse(code, len) {
  9136. var res = 0;
  9137. do {
  9138. res |= code & 1;
  9139. code >>>= 1;
  9140. res <<= 1;
  9141. } while (--len > 0);
  9142. return res >>> 1;
  9143. }
  9144. /* ===========================================================================
  9145. * Flush the bit buffer, keeping at most 7 bits in it.
  9146. */
  9147. function bi_flush(s) {
  9148. if (s.bi_valid === 16) {
  9149. put_short(s, s.bi_buf);
  9150. s.bi_buf = 0;
  9151. s.bi_valid = 0;
  9152. } else if (s.bi_valid >= 8) {
  9153. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  9154. s.bi_buf >>= 8;
  9155. s.bi_valid -= 8;
  9156. }
  9157. }
  9158. /* ===========================================================================
  9159. * Compute the optimal bit lengths for a tree and update the total bit length
  9160. * for the current block.
  9161. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  9162. * above are the tree nodes sorted by increasing frequency.
  9163. * OUT assertions: the field len is set to the optimal bit length, the
  9164. * array bl_count contains the frequencies for each bit length.
  9165. * The length opt_len is updated; static_len is also updated if stree is
  9166. * not null.
  9167. */
  9168. function gen_bitlen(s, desc)
  9169. // deflate_state *s;
  9170. // tree_desc *desc; /* the tree descriptor */
  9171. {
  9172. var tree = desc.dyn_tree;
  9173. var max_code = desc.max_code;
  9174. var stree = desc.stat_desc.static_tree;
  9175. var has_stree = desc.stat_desc.has_stree;
  9176. var extra = desc.stat_desc.extra_bits;
  9177. var base = desc.stat_desc.extra_base;
  9178. var max_length = desc.stat_desc.max_length;
  9179. var h; /* heap index */
  9180. var n, m; /* iterate over the tree elements */
  9181. var bits; /* bit length */
  9182. var xbits; /* extra bits */
  9183. var f; /* frequency */
  9184. var overflow = 0; /* number of elements with bit length too large */
  9185. for (bits = 0; bits <= MAX_BITS; bits++) {
  9186. s.bl_count[bits] = 0;
  9187. }
  9188. /* In a first pass, compute the optimal bit lengths (which may
  9189. * overflow in the case of the bit length tree).
  9190. */
  9191. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  9192. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  9193. n = s.heap[h];
  9194. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  9195. if (bits > max_length) {
  9196. bits = max_length;
  9197. overflow++;
  9198. }
  9199. tree[n * 2 + 1]/*.Len*/ = bits;
  9200. /* We overwrite tree[n].Dad which is no longer needed */
  9201. if (n > max_code) { continue; } /* not a leaf node */
  9202. s.bl_count[bits]++;
  9203. xbits = 0;
  9204. if (n >= base) {
  9205. xbits = extra[n - base];
  9206. }
  9207. f = tree[n * 2]/*.Freq*/;
  9208. s.opt_len += f * (bits + xbits);
  9209. if (has_stree) {
  9210. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  9211. }
  9212. }
  9213. if (overflow === 0) { return; }
  9214. // Trace((stderr,"\nbit length overflow\n"));
  9215. /* This happens for example on obj2 and pic of the Calgary corpus */
  9216. /* Find the first bit length which could increase: */
  9217. do {
  9218. bits = max_length - 1;
  9219. while (s.bl_count[bits] === 0) { bits--; }
  9220. s.bl_count[bits]--; /* move one leaf down the tree */
  9221. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  9222. s.bl_count[max_length]--;
  9223. /* The brother of the overflow item also moves one step up,
  9224. * but this does not affect bl_count[max_length]
  9225. */
  9226. overflow -= 2;
  9227. } while (overflow > 0);
  9228. /* Now recompute all bit lengths, scanning in increasing frequency.
  9229. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  9230. * lengths instead of fixing only the wrong ones. This idea is taken
  9231. * from 'ar' written by Haruhiko Okumura.)
  9232. */
  9233. for (bits = max_length; bits !== 0; bits--) {
  9234. n = s.bl_count[bits];
  9235. while (n !== 0) {
  9236. m = s.heap[--h];
  9237. if (m > max_code) { continue; }
  9238. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  9239. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  9240. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  9241. tree[m * 2 + 1]/*.Len*/ = bits;
  9242. }
  9243. n--;
  9244. }
  9245. }
  9246. }
  9247. /* ===========================================================================
  9248. * Generate the codes for a given tree and bit counts (which need not be
  9249. * optimal).
  9250. * IN assertion: the array bl_count contains the bit length statistics for
  9251. * the given tree and the field len is set for all tree elements.
  9252. * OUT assertion: the field code is set for all tree elements of non
  9253. * zero code length.
  9254. */
  9255. function gen_codes(tree, max_code, bl_count)
  9256. // ct_data *tree; /* the tree to decorate */
  9257. // int max_code; /* largest code with non zero frequency */
  9258. // ushf *bl_count; /* number of codes at each bit length */
  9259. {
  9260. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  9261. var code = 0; /* running code value */
  9262. var bits; /* bit index */
  9263. var n; /* code index */
  9264. /* The distribution counts are first used to generate the code values
  9265. * without bit reversal.
  9266. */
  9267. for (bits = 1; bits <= MAX_BITS; bits++) {
  9268. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  9269. }
  9270. /* Check that the bit counts in bl_count are consistent. The last code
  9271. * must be all ones.
  9272. */
  9273. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  9274. // "inconsistent bit counts");
  9275. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  9276. for (n = 0; n <= max_code; n++) {
  9277. var len = tree[n * 2 + 1]/*.Len*/;
  9278. if (len === 0) { continue; }
  9279. /* Now reverse the bits */
  9280. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  9281. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  9282. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  9283. }
  9284. }
  9285. /* ===========================================================================
  9286. * Initialize the various 'constant' tables.
  9287. */
  9288. function tr_static_init() {
  9289. var n; /* iterates over tree elements */
  9290. var bits; /* bit counter */
  9291. var length; /* length value */
  9292. var code; /* code value */
  9293. var dist; /* distance index */
  9294. var bl_count = new Array(MAX_BITS + 1);
  9295. /* number of codes at each bit length for an optimal tree */
  9296. // do check in _tr_init()
  9297. //if (static_init_done) return;
  9298. /* For some embedded targets, global variables are not initialized: */
  9299. /*#ifdef NO_INIT_GLOBAL_POINTERS
  9300. static_l_desc.static_tree = static_ltree;
  9301. static_l_desc.extra_bits = extra_lbits;
  9302. static_d_desc.static_tree = static_dtree;
  9303. static_d_desc.extra_bits = extra_dbits;
  9304. static_bl_desc.extra_bits = extra_blbits;
  9305. #endif*/
  9306. /* Initialize the mapping length (0..255) -> length code (0..28) */
  9307. length = 0;
  9308. for (code = 0; code < LENGTH_CODES - 1; code++) {
  9309. base_length[code] = length;
  9310. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  9311. _length_code[length++] = code;
  9312. }
  9313. }
  9314. //Assert (length == 256, "tr_static_init: length != 256");
  9315. /* Note that the length 255 (match length 258) can be represented
  9316. * in two different ways: code 284 + 5 bits or code 285, so we
  9317. * overwrite length_code[255] to use the best encoding:
  9318. */
  9319. _length_code[length - 1] = code;
  9320. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  9321. dist = 0;
  9322. for (code = 0; code < 16; code++) {
  9323. base_dist[code] = dist;
  9324. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  9325. _dist_code[dist++] = code;
  9326. }
  9327. }
  9328. //Assert (dist == 256, "tr_static_init: dist != 256");
  9329. dist >>= 7; /* from now on, all distances are divided by 128 */
  9330. for (; code < D_CODES; code++) {
  9331. base_dist[code] = dist << 7;
  9332. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  9333. _dist_code[256 + dist++] = code;
  9334. }
  9335. }
  9336. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  9337. /* Construct the codes of the static literal tree */
  9338. for (bits = 0; bits <= MAX_BITS; bits++) {
  9339. bl_count[bits] = 0;
  9340. }
  9341. n = 0;
  9342. while (n <= 143) {
  9343. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  9344. n++;
  9345. bl_count[8]++;
  9346. }
  9347. while (n <= 255) {
  9348. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  9349. n++;
  9350. bl_count[9]++;
  9351. }
  9352. while (n <= 279) {
  9353. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  9354. n++;
  9355. bl_count[7]++;
  9356. }
  9357. while (n <= 287) {
  9358. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  9359. n++;
  9360. bl_count[8]++;
  9361. }
  9362. /* Codes 286 and 287 do not exist, but we must include them in the
  9363. * tree construction to get a canonical Huffman tree (longest code
  9364. * all ones)
  9365. */
  9366. gen_codes(static_ltree, L_CODES + 1, bl_count);
  9367. /* The static distance tree is trivial: */
  9368. for (n = 0; n < D_CODES; n++) {
  9369. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  9370. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  9371. }
  9372. // Now data ready and we can init static trees
  9373. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  9374. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  9375. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  9376. //static_init_done = true;
  9377. }
  9378. /* ===========================================================================
  9379. * Initialize a new block.
  9380. */
  9381. function init_block(s) {
  9382. var n; /* iterates over tree elements */
  9383. /* Initialize the trees. */
  9384. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  9385. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  9386. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  9387. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  9388. s.opt_len = s.static_len = 0;
  9389. s.last_lit = s.matches = 0;
  9390. }
  9391. /* ===========================================================================
  9392. * Flush the bit buffer and align the output on a byte boundary
  9393. */
  9394. function bi_windup(s)
  9395. {
  9396. if (s.bi_valid > 8) {
  9397. put_short(s, s.bi_buf);
  9398. } else if (s.bi_valid > 0) {
  9399. //put_byte(s, (Byte)s->bi_buf);
  9400. s.pending_buf[s.pending++] = s.bi_buf;
  9401. }
  9402. s.bi_buf = 0;
  9403. s.bi_valid = 0;
  9404. }
  9405. /* ===========================================================================
  9406. * Copy a stored block, storing first the length and its
  9407. * one's complement if requested.
  9408. */
  9409. function copy_block(s, buf, len, header)
  9410. //DeflateState *s;
  9411. //charf *buf; /* the input data */
  9412. //unsigned len; /* its length */
  9413. //int header; /* true if block header must be written */
  9414. {
  9415. bi_windup(s); /* align on byte boundary */
  9416. if (header) {
  9417. put_short(s, len);
  9418. put_short(s, ~len);
  9419. }
  9420. // while (len--) {
  9421. // put_byte(s, *buf++);
  9422. // }
  9423. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  9424. s.pending += len;
  9425. }
  9426. /* ===========================================================================
  9427. * Compares to subtrees, using the tree depth as tie breaker when
  9428. * the subtrees have equal frequency. This minimizes the worst case length.
  9429. */
  9430. function smaller(tree, n, m, depth) {
  9431. var _n2 = n * 2;
  9432. var _m2 = m * 2;
  9433. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  9434. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  9435. }
  9436. /* ===========================================================================
  9437. * Restore the heap property by moving down the tree starting at node k,
  9438. * exchanging a node with the smallest of its two sons if necessary, stopping
  9439. * when the heap property is re-established (each father smaller than its
  9440. * two sons).
  9441. */
  9442. function pqdownheap(s, tree, k)
  9443. // deflate_state *s;
  9444. // ct_data *tree; /* the tree to restore */
  9445. // int k; /* node to move down */
  9446. {
  9447. var v = s.heap[k];
  9448. var j = k << 1; /* left son of k */
  9449. while (j <= s.heap_len) {
  9450. /* Set j to the smallest of the two sons: */
  9451. if (j < s.heap_len &&
  9452. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  9453. j++;
  9454. }
  9455. /* Exit if v is smaller than both sons */
  9456. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  9457. /* Exchange v with the smallest son */
  9458. s.heap[k] = s.heap[j];
  9459. k = j;
  9460. /* And continue down the tree, setting j to the left son of k */
  9461. j <<= 1;
  9462. }
  9463. s.heap[k] = v;
  9464. }
  9465. // inlined manually
  9466. // var SMALLEST = 1;
  9467. /* ===========================================================================
  9468. * Send the block data compressed using the given Huffman trees
  9469. */
  9470. function compress_block(s, ltree, dtree)
  9471. // deflate_state *s;
  9472. // const ct_data *ltree; /* literal tree */
  9473. // const ct_data *dtree; /* distance tree */
  9474. {
  9475. var dist; /* distance of matched string */
  9476. var lc; /* match length or unmatched char (if dist == 0) */
  9477. var lx = 0; /* running index in l_buf */
  9478. var code; /* the code to send */
  9479. var extra; /* number of extra bits to send */
  9480. if (s.last_lit !== 0) {
  9481. do {
  9482. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  9483. lc = s.pending_buf[s.l_buf + lx];
  9484. lx++;
  9485. if (dist === 0) {
  9486. send_code(s, lc, ltree); /* send a literal byte */
  9487. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  9488. } else {
  9489. /* Here, lc is the match length - MIN_MATCH */
  9490. code = _length_code[lc];
  9491. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  9492. extra = extra_lbits[code];
  9493. if (extra !== 0) {
  9494. lc -= base_length[code];
  9495. send_bits(s, lc, extra); /* send the extra length bits */
  9496. }
  9497. dist--; /* dist is now the match distance - 1 */
  9498. code = d_code(dist);
  9499. //Assert (code < D_CODES, "bad d_code");
  9500. send_code(s, code, dtree); /* send the distance code */
  9501. extra = extra_dbits[code];
  9502. if (extra !== 0) {
  9503. dist -= base_dist[code];
  9504. send_bits(s, dist, extra); /* send the extra distance bits */
  9505. }
  9506. } /* literal or match pair ? */
  9507. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  9508. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  9509. // "pendingBuf overflow");
  9510. } while (lx < s.last_lit);
  9511. }
  9512. send_code(s, END_BLOCK, ltree);
  9513. }
  9514. /* ===========================================================================
  9515. * Construct one Huffman tree and assigns the code bit strings and lengths.
  9516. * Update the total bit length for the current block.
  9517. * IN assertion: the field freq is set for all tree elements.
  9518. * OUT assertions: the fields len and code are set to the optimal bit length
  9519. * and corresponding code. The length opt_len is updated; static_len is
  9520. * also updated if stree is not null. The field max_code is set.
  9521. */
  9522. function build_tree(s, desc)
  9523. // deflate_state *s;
  9524. // tree_desc *desc; /* the tree descriptor */
  9525. {
  9526. var tree = desc.dyn_tree;
  9527. var stree = desc.stat_desc.static_tree;
  9528. var has_stree = desc.stat_desc.has_stree;
  9529. var elems = desc.stat_desc.elems;
  9530. var n, m; /* iterate over heap elements */
  9531. var max_code = -1; /* largest code with non zero frequency */
  9532. var node; /* new node being created */
  9533. /* Construct the initial heap, with least frequent element in
  9534. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  9535. * heap[0] is not used.
  9536. */
  9537. s.heap_len = 0;
  9538. s.heap_max = HEAP_SIZE;
  9539. for (n = 0; n < elems; n++) {
  9540. if (tree[n * 2]/*.Freq*/ !== 0) {
  9541. s.heap[++s.heap_len] = max_code = n;
  9542. s.depth[n] = 0;
  9543. } else {
  9544. tree[n * 2 + 1]/*.Len*/ = 0;
  9545. }
  9546. }
  9547. /* The pkzip format requires that at least one distance code exists,
  9548. * and that at least one bit should be sent even if there is only one
  9549. * possible code. So to avoid special checks later on we force at least
  9550. * two codes of non zero frequency.
  9551. */
  9552. while (s.heap_len < 2) {
  9553. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  9554. tree[node * 2]/*.Freq*/ = 1;
  9555. s.depth[node] = 0;
  9556. s.opt_len--;
  9557. if (has_stree) {
  9558. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  9559. }
  9560. /* node is 0 or 1 so it does not have extra bits */
  9561. }
  9562. desc.max_code = max_code;
  9563. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  9564. * establish sub-heaps of increasing lengths:
  9565. */
  9566. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  9567. /* Construct the Huffman tree by repeatedly combining the least two
  9568. * frequent nodes.
  9569. */
  9570. node = elems; /* next internal node of the tree */
  9571. do {
  9572. //pqremove(s, tree, n); /* n = node of least frequency */
  9573. /*** pqremove ***/
  9574. n = s.heap[1/*SMALLEST*/];
  9575. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  9576. pqdownheap(s, tree, 1/*SMALLEST*/);
  9577. /***/
  9578. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  9579. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  9580. s.heap[--s.heap_max] = m;
  9581. /* Create a new node father of n and m */
  9582. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  9583. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  9584. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  9585. /* and insert the new node in the heap */
  9586. s.heap[1/*SMALLEST*/] = node++;
  9587. pqdownheap(s, tree, 1/*SMALLEST*/);
  9588. } while (s.heap_len >= 2);
  9589. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  9590. /* At this point, the fields freq and dad are set. We can now
  9591. * generate the bit lengths.
  9592. */
  9593. gen_bitlen(s, desc);
  9594. /* The field len is now set, we can generate the bit codes */
  9595. gen_codes(tree, max_code, s.bl_count);
  9596. }
  9597. /* ===========================================================================
  9598. * Scan a literal or distance tree to determine the frequencies of the codes
  9599. * in the bit length tree.
  9600. */
  9601. function scan_tree(s, tree, max_code)
  9602. // deflate_state *s;
  9603. // ct_data *tree; /* the tree to be scanned */
  9604. // int max_code; /* and its largest code of non zero frequency */
  9605. {
  9606. var n; /* iterates over all tree elements */
  9607. var prevlen = -1; /* last emitted length */
  9608. var curlen; /* length of current code */
  9609. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  9610. var count = 0; /* repeat count of the current code */
  9611. var max_count = 7; /* max repeat count */
  9612. var min_count = 4; /* min repeat count */
  9613. if (nextlen === 0) {
  9614. max_count = 138;
  9615. min_count = 3;
  9616. }
  9617. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  9618. for (n = 0; n <= max_code; n++) {
  9619. curlen = nextlen;
  9620. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  9621. if (++count < max_count && curlen === nextlen) {
  9622. continue;
  9623. } else if (count < min_count) {
  9624. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  9625. } else if (curlen !== 0) {
  9626. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  9627. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  9628. } else if (count <= 10) {
  9629. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  9630. } else {
  9631. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  9632. }
  9633. count = 0;
  9634. prevlen = curlen;
  9635. if (nextlen === 0) {
  9636. max_count = 138;
  9637. min_count = 3;
  9638. } else if (curlen === nextlen) {
  9639. max_count = 6;
  9640. min_count = 3;
  9641. } else {
  9642. max_count = 7;
  9643. min_count = 4;
  9644. }
  9645. }
  9646. }
  9647. /* ===========================================================================
  9648. * Send a literal or distance tree in compressed form, using the codes in
  9649. * bl_tree.
  9650. */
  9651. function send_tree(s, tree, max_code)
  9652. // deflate_state *s;
  9653. // ct_data *tree; /* the tree to be scanned */
  9654. // int max_code; /* and its largest code of non zero frequency */
  9655. {
  9656. var n; /* iterates over all tree elements */
  9657. var prevlen = -1; /* last emitted length */
  9658. var curlen; /* length of current code */
  9659. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  9660. var count = 0; /* repeat count of the current code */
  9661. var max_count = 7; /* max repeat count */
  9662. var min_count = 4; /* min repeat count */
  9663. /* tree[max_code+1].Len = -1; */ /* guard already set */
  9664. if (nextlen === 0) {
  9665. max_count = 138;
  9666. min_count = 3;
  9667. }
  9668. for (n = 0; n <= max_code; n++) {
  9669. curlen = nextlen;
  9670. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  9671. if (++count < max_count && curlen === nextlen) {
  9672. continue;
  9673. } else if (count < min_count) {
  9674. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  9675. } else if (curlen !== 0) {
  9676. if (curlen !== prevlen) {
  9677. send_code(s, curlen, s.bl_tree);
  9678. count--;
  9679. }
  9680. //Assert(count >= 3 && count <= 6, " 3_6?");
  9681. send_code(s, REP_3_6, s.bl_tree);
  9682. send_bits(s, count - 3, 2);
  9683. } else if (count <= 10) {
  9684. send_code(s, REPZ_3_10, s.bl_tree);
  9685. send_bits(s, count - 3, 3);
  9686. } else {
  9687. send_code(s, REPZ_11_138, s.bl_tree);
  9688. send_bits(s, count - 11, 7);
  9689. }
  9690. count = 0;
  9691. prevlen = curlen;
  9692. if (nextlen === 0) {
  9693. max_count = 138;
  9694. min_count = 3;
  9695. } else if (curlen === nextlen) {
  9696. max_count = 6;
  9697. min_count = 3;
  9698. } else {
  9699. max_count = 7;
  9700. min_count = 4;
  9701. }
  9702. }
  9703. }
  9704. /* ===========================================================================
  9705. * Construct the Huffman tree for the bit lengths and return the index in
  9706. * bl_order of the last bit length code to send.
  9707. */
  9708. function build_bl_tree(s) {
  9709. var max_blindex; /* index of last bit length code of non zero freq */
  9710. /* Determine the bit length frequencies for literal and distance trees */
  9711. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  9712. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  9713. /* Build the bit length tree: */
  9714. build_tree(s, s.bl_desc);
  9715. /* opt_len now includes the length of the tree representations, except
  9716. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  9717. */
  9718. /* Determine the number of bit length codes to send. The pkzip format
  9719. * requires that at least 4 bit length codes be sent. (appnote.txt says
  9720. * 3 but the actual value used is 4.)
  9721. */
  9722. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  9723. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  9724. break;
  9725. }
  9726. }
  9727. /* Update opt_len to include the bit length tree and counts */
  9728. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  9729. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  9730. // s->opt_len, s->static_len));
  9731. return max_blindex;
  9732. }
  9733. /* ===========================================================================
  9734. * Send the header for a block using dynamic Huffman trees: the counts, the
  9735. * lengths of the bit length codes, the literal tree and the distance tree.
  9736. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  9737. */
  9738. function send_all_trees(s, lcodes, dcodes, blcodes)
  9739. // deflate_state *s;
  9740. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  9741. {
  9742. var rank; /* index in bl_order */
  9743. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  9744. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  9745. // "too many codes");
  9746. //Tracev((stderr, "\nbl counts: "));
  9747. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  9748. send_bits(s, dcodes - 1, 5);
  9749. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  9750. for (rank = 0; rank < blcodes; rank++) {
  9751. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  9752. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  9753. }
  9754. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  9755. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  9756. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  9757. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  9758. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  9759. }
  9760. /* ===========================================================================
  9761. * Check if the data type is TEXT or BINARY, using the following algorithm:
  9762. * - TEXT if the two conditions below are satisfied:
  9763. * a) There are no non-portable control characters belonging to the
  9764. * "black list" (0..6, 14..25, 28..31).
  9765. * b) There is at least one printable character belonging to the
  9766. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  9767. * - BINARY otherwise.
  9768. * - The following partially-portable control characters form a
  9769. * "gray list" that is ignored in this detection algorithm:
  9770. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  9771. * IN assertion: the fields Freq of dyn_ltree are set.
  9772. */
  9773. function detect_data_type(s) {
  9774. /* black_mask is the bit mask of black-listed bytes
  9775. * set bits 0..6, 14..25, and 28..31
  9776. * 0xf3ffc07f = binary 11110011111111111100000001111111
  9777. */
  9778. var black_mask = 0xf3ffc07f;
  9779. var n;
  9780. /* Check for non-textual ("black-listed") bytes. */
  9781. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  9782. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  9783. return Z_BINARY;
  9784. }
  9785. }
  9786. /* Check for textual ("white-listed") bytes. */
  9787. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  9788. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  9789. return Z_TEXT;
  9790. }
  9791. for (n = 32; n < LITERALS; n++) {
  9792. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  9793. return Z_TEXT;
  9794. }
  9795. }
  9796. /* There are no "black-listed" or "white-listed" bytes:
  9797. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  9798. */
  9799. return Z_BINARY;
  9800. }
  9801. var static_init_done = false;
  9802. /* ===========================================================================
  9803. * Initialize the tree data structures for a new zlib stream.
  9804. */
  9805. function _tr_init(s)
  9806. {
  9807. if (!static_init_done) {
  9808. tr_static_init();
  9809. static_init_done = true;
  9810. }
  9811. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  9812. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  9813. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  9814. s.bi_buf = 0;
  9815. s.bi_valid = 0;
  9816. /* Initialize the first block of the first file: */
  9817. init_block(s);
  9818. }
  9819. /* ===========================================================================
  9820. * Send a stored block
  9821. */
  9822. function _tr_stored_block(s, buf, stored_len, last)
  9823. //DeflateState *s;
  9824. //charf *buf; /* input block */
  9825. //ulg stored_len; /* length of input block */
  9826. //int last; /* one if this is the last block for a file */
  9827. {
  9828. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  9829. copy_block(s, buf, stored_len, true); /* with header */
  9830. }
  9831. /* ===========================================================================
  9832. * Send one empty static block to give enough lookahead for inflate.
  9833. * This takes 10 bits, of which 7 may remain in the bit buffer.
  9834. */
  9835. function _tr_align(s) {
  9836. send_bits(s, STATIC_TREES << 1, 3);
  9837. send_code(s, END_BLOCK, static_ltree);
  9838. bi_flush(s);
  9839. }
  9840. /* ===========================================================================
  9841. * Determine the best encoding for the current block: dynamic trees, static
  9842. * trees or store, and output the encoded block to the zip file.
  9843. */
  9844. function _tr_flush_block(s, buf, stored_len, last)
  9845. //DeflateState *s;
  9846. //charf *buf; /* input block, or NULL if too old */
  9847. //ulg stored_len; /* length of input block */
  9848. //int last; /* one if this is the last block for a file */
  9849. {
  9850. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  9851. var max_blindex = 0; /* index of last bit length code of non zero freq */
  9852. /* Build the Huffman trees unless a stored block is forced */
  9853. if (s.level > 0) {
  9854. /* Check if the file is binary or text */
  9855. if (s.strm.data_type === Z_UNKNOWN) {
  9856. s.strm.data_type = detect_data_type(s);
  9857. }
  9858. /* Construct the literal and distance trees */
  9859. build_tree(s, s.l_desc);
  9860. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  9861. // s->static_len));
  9862. build_tree(s, s.d_desc);
  9863. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  9864. // s->static_len));
  9865. /* At this point, opt_len and static_len are the total bit lengths of
  9866. * the compressed block data, excluding the tree representations.
  9867. */
  9868. /* Build the bit length tree for the above two trees, and get the index
  9869. * in bl_order of the last bit length code to send.
  9870. */
  9871. max_blindex = build_bl_tree(s);
  9872. /* Determine the best encoding. Compute the block lengths in bytes. */
  9873. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  9874. static_lenb = (s.static_len + 3 + 7) >>> 3;
  9875. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  9876. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  9877. // s->last_lit));
  9878. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  9879. } else {
  9880. // Assert(buf != (char*)0, "lost buf");
  9881. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  9882. }
  9883. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  9884. /* 4: two words for the lengths */
  9885. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  9886. * Otherwise we can't have processed more than WSIZE input bytes since
  9887. * the last block flush, because compression would have been
  9888. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  9889. * transform a block into a stored block.
  9890. */
  9891. _tr_stored_block(s, buf, stored_len, last);
  9892. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  9893. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  9894. compress_block(s, static_ltree, static_dtree);
  9895. } else {
  9896. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  9897. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  9898. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  9899. }
  9900. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  9901. /* The above check is made mod 2^32, for files larger than 512 MB
  9902. * and uLong implemented on 32 bits.
  9903. */
  9904. init_block(s);
  9905. if (last) {
  9906. bi_windup(s);
  9907. }
  9908. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  9909. // s->compressed_len-7*last));
  9910. }
  9911. /* ===========================================================================
  9912. * Save the match info and tally the frequency counts. Return true if
  9913. * the current block must be flushed.
  9914. */
  9915. function _tr_tally(s, dist, lc)
  9916. // deflate_state *s;
  9917. // unsigned dist; /* distance of matched string */
  9918. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  9919. {
  9920. //var out_length, in_length, dcode;
  9921. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  9922. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  9923. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  9924. s.last_lit++;
  9925. if (dist === 0) {
  9926. /* lc is the unmatched char */
  9927. s.dyn_ltree[lc * 2]/*.Freq*/++;
  9928. } else {
  9929. s.matches++;
  9930. /* Here, lc is the match length - MIN_MATCH */
  9931. dist--; /* dist = match distance - 1 */
  9932. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  9933. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  9934. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  9935. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  9936. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  9937. }
  9938. // (!) This block is disabled in zlib defailts,
  9939. // don't enable it for binary compatibility
  9940. //#ifdef TRUNCATE_BLOCK
  9941. // /* Try to guess if it is profitable to stop the current block here */
  9942. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  9943. // /* Compute an upper bound for the compressed length */
  9944. // out_length = s.last_lit*8;
  9945. // in_length = s.strstart - s.block_start;
  9946. //
  9947. // for (dcode = 0; dcode < D_CODES; dcode++) {
  9948. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  9949. // }
  9950. // out_length >>>= 3;
  9951. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  9952. // // s->last_lit, in_length, out_length,
  9953. // // 100L - out_length*100L/in_length));
  9954. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  9955. // return true;
  9956. // }
  9957. // }
  9958. //#endif
  9959. return (s.last_lit === s.lit_bufsize - 1);
  9960. /* We avoid equality with lit_bufsize because of wraparound at 64K
  9961. * on 16 bit machines and because stored blocks are restricted to
  9962. * 64K-1 bytes.
  9963. */
  9964. }
  9965. exports._tr_init = _tr_init;
  9966. exports._tr_stored_block = _tr_stored_block;
  9967. exports._tr_flush_block = _tr_flush_block;
  9968. exports._tr_tally = _tr_tally;
  9969. exports._tr_align = _tr_align;
  9970. },{"../utils/common":41}],53:[function(require,module,exports){
  9971. 'use strict';
  9972. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  9973. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  9974. //
  9975. // This software is provided 'as-is', without any express or implied
  9976. // warranty. In no event will the authors be held liable for any damages
  9977. // arising from the use of this software.
  9978. //
  9979. // Permission is granted to anyone to use this software for any purpose,
  9980. // including commercial applications, and to alter it and redistribute it
  9981. // freely, subject to the following restrictions:
  9982. //
  9983. // 1. The origin of this software must not be misrepresented; you must not
  9984. // claim that you wrote the original software. If you use this software
  9985. // in a product, an acknowledgment in the product documentation would be
  9986. // appreciated but is not required.
  9987. // 2. Altered source versions must be plainly marked as such, and must not be
  9988. // misrepresented as being the original software.
  9989. // 3. This notice may not be removed or altered from any source distribution.
  9990. function ZStream() {
  9991. /* next input byte */
  9992. this.input = null; // JS specific, because we have no pointers
  9993. this.next_in = 0;
  9994. /* number of bytes available at input */
  9995. this.avail_in = 0;
  9996. /* total number of input bytes read so far */
  9997. this.total_in = 0;
  9998. /* next output byte should be put there */
  9999. this.output = null; // JS specific, because we have no pointers
  10000. this.next_out = 0;
  10001. /* remaining free space at output */
  10002. this.avail_out = 0;
  10003. /* total number of bytes output so far */
  10004. this.total_out = 0;
  10005. /* last error message, NULL if no error */
  10006. this.msg = ''/*Z_NULL*/;
  10007. /* not visible by applications */
  10008. this.state = null;
  10009. /* best guess about the data type: binary or text */
  10010. this.data_type = 2/*Z_UNKNOWN*/;
  10011. /* adler32 value of the uncompressed data */
  10012. this.adler = 0;
  10013. }
  10014. module.exports = ZStream;
  10015. },{}],54:[function(require,module,exports){
  10016. 'use strict';
  10017. module.exports = typeof setImmediate === 'function' ? setImmediate :
  10018. function setImmediate() {
  10019. var args = [].slice.apply(arguments);
  10020. args.splice(1, 0, 0);
  10021. setTimeout.apply(null, args);
  10022. };
  10023. },{}]},{},[10])(10)
  10024. });