zip.js 250 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146
  1. /* This file is automatically rebuilt by the Cesium build process. */
  2. /*
  3. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in
  10. the documentation and/or other materials provided with the distribution.
  11. 3. The names of the authors may not be used to endorse or promote products
  12. derived from this software without specific prior written permission.
  13. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  14. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  15. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  16. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  18. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  19. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  22. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. /*
  25. * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
  26. * JZlib is based on zlib-1.1.3, so all credit should go authors
  27. * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  28. * and contributors of zlib.
  29. */
  30. // Global
  31. const MAX_BITS$1 = 15;
  32. const D_CODES = 30;
  33. const BL_CODES = 19;
  34. const LENGTH_CODES = 29;
  35. const LITERALS = 256;
  36. const L_CODES = (LITERALS + 1 + LENGTH_CODES);
  37. const HEAP_SIZE = (2 * L_CODES + 1);
  38. const END_BLOCK = 256;
  39. // Bit length codes must not exceed MAX_BL_BITS bits
  40. const MAX_BL_BITS = 7;
  41. // repeat previous bit length 3-6 times (2 bits of repeat count)
  42. const REP_3_6 = 16;
  43. // repeat a zero length 3-10 times (3 bits of repeat count)
  44. const REPZ_3_10 = 17;
  45. // repeat a zero length 11-138 times (7 bits of repeat count)
  46. const REPZ_11_138 = 18;
  47. // The lengths of the bit length codes are sent in order of decreasing
  48. // probability, to avoid transmitting the lengths for unused bit
  49. // length codes.
  50. const Buf_size = 8 * 2;
  51. // JZlib version : "1.0.2"
  52. const Z_DEFAULT_COMPRESSION = -1;
  53. // compression strategy
  54. const Z_FILTERED = 1;
  55. const Z_HUFFMAN_ONLY = 2;
  56. const Z_DEFAULT_STRATEGY = 0;
  57. const Z_NO_FLUSH$1 = 0;
  58. const Z_PARTIAL_FLUSH = 1;
  59. const Z_FULL_FLUSH = 3;
  60. const Z_FINISH$1 = 4;
  61. const Z_OK$1 = 0;
  62. const Z_STREAM_END$1 = 1;
  63. const Z_NEED_DICT$1 = 2;
  64. const Z_STREAM_ERROR$1 = -2;
  65. const Z_DATA_ERROR$1 = -3;
  66. const Z_BUF_ERROR$1 = -5;
  67. // Tree
  68. function extractArray(array) {
  69. return flatArray(array.map(([length, value]) => (new Array(length)).fill(value, 0, length)));
  70. }
  71. function flatArray(array) {
  72. return array.reduce((a, b) => a.concat(Array.isArray(b) ? flatArray(b) : b), []);
  73. }
  74. // see definition of array dist_code below
  75. const _dist_code = [0, 1, 2, 3].concat(...extractArray([
  76. [2, 4], [2, 5], [4, 6], [4, 7], [8, 8], [8, 9], [16, 10], [16, 11], [32, 12], [32, 13], [64, 14], [64, 15], [2, 0], [1, 16],
  77. [1, 17], [2, 18], [2, 19], [4, 20], [4, 21], [8, 22], [8, 23], [16, 24], [16, 25], [32, 26], [32, 27], [64, 28], [64, 29]
  78. ]));
  79. function Tree() {
  80. const that = this;
  81. // dyn_tree; // the dynamic tree
  82. // max_code; // largest code with non zero frequency
  83. // stat_desc; // the corresponding static tree
  84. // Compute the optimal bit lengths for a tree and update the total bit
  85. // length
  86. // for the current block.
  87. // IN assertion: the fields freq and dad are set, heap[heap_max] and
  88. // above are the tree nodes sorted by increasing frequency.
  89. // OUT assertions: the field len is set to the optimal bit length, the
  90. // array bl_count contains the frequencies for each bit length.
  91. // The length opt_len is updated; static_len is also updated if stree is
  92. // not null.
  93. function gen_bitlen(s) {
  94. const tree = that.dyn_tree;
  95. const stree = that.stat_desc.static_tree;
  96. const extra = that.stat_desc.extra_bits;
  97. const base = that.stat_desc.extra_base;
  98. const max_length = that.stat_desc.max_length;
  99. let h; // heap index
  100. let n, m; // iterate over the tree elements
  101. let bits; // bit length
  102. let xbits; // extra bits
  103. let f; // frequency
  104. let overflow = 0; // number of elements with bit length too large
  105. for (bits = 0; bits <= MAX_BITS$1; bits++)
  106. s.bl_count[bits] = 0;
  107. // In a first pass, compute the optimal bit lengths (which may
  108. // overflow in the case of the bit length tree).
  109. tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
  110. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  111. n = s.heap[h];
  112. bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
  113. if (bits > max_length) {
  114. bits = max_length;
  115. overflow++;
  116. }
  117. tree[n * 2 + 1] = bits;
  118. // We overwrite tree[n*2+1] which is no longer needed
  119. if (n > that.max_code)
  120. continue; // not a leaf node
  121. s.bl_count[bits]++;
  122. xbits = 0;
  123. if (n >= base)
  124. xbits = extra[n - base];
  125. f = tree[n * 2];
  126. s.opt_len += f * (bits + xbits);
  127. if (stree)
  128. s.static_len += f * (stree[n * 2 + 1] + xbits);
  129. }
  130. if (overflow === 0)
  131. return;
  132. // This happens for example on obj2 and pic of the Calgary corpus
  133. // Find the first bit length which could increase:
  134. do {
  135. bits = max_length - 1;
  136. while (s.bl_count[bits] === 0)
  137. bits--;
  138. s.bl_count[bits]--; // move one leaf down the tree
  139. s.bl_count[bits + 1] += 2; // move one overflow item as its brother
  140. s.bl_count[max_length]--;
  141. // The brother of the overflow item also moves one step up,
  142. // but this does not affect bl_count[max_length]
  143. overflow -= 2;
  144. } while (overflow > 0);
  145. for (bits = max_length; bits !== 0; bits--) {
  146. n = s.bl_count[bits];
  147. while (n !== 0) {
  148. m = s.heap[--h];
  149. if (m > that.max_code)
  150. continue;
  151. if (tree[m * 2 + 1] != bits) {
  152. s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
  153. tree[m * 2 + 1] = bits;
  154. }
  155. n--;
  156. }
  157. }
  158. }
  159. // Reverse the first len bits of a code, using straightforward code (a
  160. // faster
  161. // method would use a table)
  162. // IN assertion: 1 <= len <= 15
  163. function bi_reverse(code, // the value to invert
  164. len // its bit length
  165. ) {
  166. let res = 0;
  167. do {
  168. res |= code & 1;
  169. code >>>= 1;
  170. res <<= 1;
  171. } while (--len > 0);
  172. return res >>> 1;
  173. }
  174. // Generate the codes for a given tree and bit counts (which need not be
  175. // optimal).
  176. // IN assertion: the array bl_count contains the bit length statistics for
  177. // the given tree and the field len is set for all tree elements.
  178. // OUT assertion: the field code is set for all tree elements of non
  179. // zero code length.
  180. function gen_codes(tree, // the tree to decorate
  181. max_code, // largest code with non zero frequency
  182. bl_count // number of codes at each bit length
  183. ) {
  184. const next_code = []; // next code value for each
  185. // bit length
  186. let code = 0; // running code value
  187. let bits; // bit index
  188. let n; // code index
  189. let len;
  190. // The distribution counts are first used to generate the code values
  191. // without bit reversal.
  192. for (bits = 1; bits <= MAX_BITS$1; bits++) {
  193. next_code[bits] = code = ((code + bl_count[bits - 1]) << 1);
  194. }
  195. // Check that the bit counts in bl_count are consistent. The last code
  196. // must be all ones.
  197. // Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  198. // "inconsistent bit counts");
  199. // Tracev((stderr,"gen_codes: max_code %d ", max_code));
  200. for (n = 0; n <= max_code; n++) {
  201. len = tree[n * 2 + 1];
  202. if (len === 0)
  203. continue;
  204. // Now reverse the bits
  205. tree[n * 2] = bi_reverse(next_code[len]++, len);
  206. }
  207. }
  208. // Construct one Huffman tree and assigns the code bit strings and lengths.
  209. // Update the total bit length for the current block.
  210. // IN assertion: the field freq is set for all tree elements.
  211. // OUT assertions: the fields len and code are set to the optimal bit length
  212. // and corresponding code. The length opt_len is updated; static_len is
  213. // also updated if stree is not null. The field max_code is set.
  214. that.build_tree = function (s) {
  215. const tree = that.dyn_tree;
  216. const stree = that.stat_desc.static_tree;
  217. const elems = that.stat_desc.elems;
  218. let n, m; // iterate over heap elements
  219. let max_code = -1; // largest code with non zero frequency
  220. let node; // new node being created
  221. // Construct the initial heap, with least frequent element in
  222. // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  223. // heap[0] is not used.
  224. s.heap_len = 0;
  225. s.heap_max = HEAP_SIZE;
  226. for (n = 0; n < elems; n++) {
  227. if (tree[n * 2] !== 0) {
  228. s.heap[++s.heap_len] = max_code = n;
  229. s.depth[n] = 0;
  230. } else {
  231. tree[n * 2 + 1] = 0;
  232. }
  233. }
  234. // The pkzip format requires that at least one distance code exists,
  235. // and that at least one bit should be sent even if there is only one
  236. // possible code. So to avoid special checks later on we force at least
  237. // two codes of non zero frequency.
  238. while (s.heap_len < 2) {
  239. node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
  240. tree[node * 2] = 1;
  241. s.depth[node] = 0;
  242. s.opt_len--;
  243. if (stree)
  244. s.static_len -= stree[node * 2 + 1];
  245. // node is 0 or 1 so it does not have extra bits
  246. }
  247. that.max_code = max_code;
  248. // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  249. // establish sub-heaps of increasing lengths:
  250. for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
  251. s.pqdownheap(tree, n);
  252. // Construct the Huffman tree by repeatedly combining the least two
  253. // frequent nodes.
  254. node = elems; // next internal node of the tree
  255. do {
  256. // n = node of least frequency
  257. n = s.heap[1];
  258. s.heap[1] = s.heap[s.heap_len--];
  259. s.pqdownheap(tree, 1);
  260. m = s.heap[1]; // m = node of next least frequency
  261. s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
  262. s.heap[--s.heap_max] = m;
  263. // Create a new node father of n and m
  264. tree[node * 2] = (tree[n * 2] + tree[m * 2]);
  265. s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
  266. tree[n * 2 + 1] = tree[m * 2 + 1] = node;
  267. // and insert the new node in the heap
  268. s.heap[1] = node++;
  269. s.pqdownheap(tree, 1);
  270. } while (s.heap_len >= 2);
  271. s.heap[--s.heap_max] = s.heap[1];
  272. // At this point, the fields freq and dad are set. We can now
  273. // generate the bit lengths.
  274. gen_bitlen(s);
  275. // The field len is now set, we can generate the bit codes
  276. gen_codes(tree, that.max_code, s.bl_count);
  277. };
  278. }
  279. Tree._length_code = [0, 1, 2, 3, 4, 5, 6, 7].concat(...extractArray([
  280. [2, 8], [2, 9], [2, 10], [2, 11], [4, 12], [4, 13], [4, 14], [4, 15], [8, 16], [8, 17], [8, 18], [8, 19],
  281. [16, 20], [16, 21], [16, 22], [16, 23], [32, 24], [32, 25], [32, 26], [31, 27], [1, 28]]));
  282. Tree.base_length = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0];
  283. Tree.base_dist = [0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384,
  284. 24576];
  285. // Mapping from a distance to a distance code. dist is the distance - 1 and
  286. // must not have side effects. _dist_code[256] and _dist_code[257] are never
  287. // used.
  288. Tree.d_code = function (dist) {
  289. return ((dist) < 256 ? _dist_code[dist] : _dist_code[256 + ((dist) >>> 7)]);
  290. };
  291. // extra bits for each length code
  292. Tree.extra_lbits = [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];
  293. // extra bits for each distance code
  294. Tree.extra_dbits = [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];
  295. // extra bits for each bit length code
  296. Tree.extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];
  297. Tree.bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  298. // StaticTree
  299. function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
  300. const that = this;
  301. that.static_tree = static_tree;
  302. that.extra_bits = extra_bits;
  303. that.extra_base = extra_base;
  304. that.elems = elems;
  305. that.max_length = max_length;
  306. }
  307. const static_ltree2_first_part = [12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, 60, 188, 124, 252, 2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82,
  308. 210, 50, 178, 114, 242, 10, 138, 74, 202, 42, 170, 106, 234, 26, 154, 90, 218, 58, 186, 122, 250, 6, 134, 70, 198, 38, 166, 102, 230, 22, 150, 86,
  309. 214, 54, 182, 118, 246, 14, 142, 78, 206, 46, 174, 110, 238, 30, 158, 94, 222, 62, 190, 126, 254, 1, 129, 65, 193, 33, 161, 97, 225, 17, 145, 81,
  310. 209, 49, 177, 113, 241, 9, 137, 73, 201, 41, 169, 105, 233, 25, 153, 89, 217, 57, 185, 121, 249, 5, 133, 69, 197, 37, 165, 101, 229, 21, 149, 85,
  311. 213, 53, 181, 117, 245, 13, 141, 77, 205, 45, 173, 109, 237, 29, 157, 93, 221, 61, 189, 125, 253, 19, 275, 147, 403, 83, 339, 211, 467, 51, 307,
  312. 179, 435, 115, 371, 243, 499, 11, 267, 139, 395, 75, 331, 203, 459, 43, 299, 171, 427, 107, 363, 235, 491, 27, 283, 155, 411, 91, 347, 219, 475,
  313. 59, 315, 187, 443, 123, 379, 251, 507, 7, 263, 135, 391, 71, 327, 199, 455, 39, 295, 167, 423, 103, 359, 231, 487, 23, 279, 151, 407, 87, 343, 215,
  314. 471, 55, 311, 183, 439, 119, 375, 247, 503, 15, 271, 143, 399, 79, 335, 207, 463, 47, 303, 175, 431, 111, 367, 239, 495, 31, 287, 159, 415, 95,
  315. 351, 223, 479, 63, 319, 191, 447, 127, 383, 255, 511, 0, 64, 32, 96, 16, 80, 48, 112, 8, 72, 40, 104, 24, 88, 56, 120, 4, 68, 36, 100, 20, 84, 52,
  316. 116, 3, 131, 67, 195, 35, 163, 99, 227];
  317. const static_ltree2_second_part = extractArray([[144, 8], [112, 9], [24, 7], [8, 8]]);
  318. StaticTree.static_ltree = flatArray(static_ltree2_first_part.map((value, index) => [value, static_ltree2_second_part[index]]));
  319. const static_dtree_first_part = [0, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30, 1, 17, 9, 25, 5, 21, 13, 29, 3, 19, 11, 27, 7, 23];
  320. const static_dtree_second_part = extractArray([[30, 5]]);
  321. StaticTree.static_dtree = flatArray(static_dtree_first_part.map((value, index) => [value, static_dtree_second_part[index]]));
  322. StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS$1);
  323. StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS$1);
  324. StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  325. // Deflate
  326. const MAX_MEM_LEVEL = 9;
  327. const DEF_MEM_LEVEL = 8;
  328. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  329. const that = this;
  330. that.good_length = good_length;
  331. that.max_lazy = max_lazy;
  332. that.nice_length = nice_length;
  333. that.max_chain = max_chain;
  334. that.func = func;
  335. }
  336. const STORED$1 = 0;
  337. const FAST = 1;
  338. const SLOW = 2;
  339. const config_table = [
  340. new Config(0, 0, 0, 0, STORED$1),
  341. new Config(4, 4, 8, 4, FAST),
  342. new Config(4, 5, 16, 8, FAST),
  343. new Config(4, 6, 32, 32, FAST),
  344. new Config(4, 4, 16, 16, SLOW),
  345. new Config(8, 16, 32, 32, SLOW),
  346. new Config(8, 16, 128, 128, SLOW),
  347. new Config(8, 32, 128, 256, SLOW),
  348. new Config(32, 128, 258, 1024, SLOW),
  349. new Config(32, 258, 258, 4096, SLOW)
  350. ];
  351. const z_errmsg = ["need dictionary", // Z_NEED_DICT
  352. // 2
  353. "stream end", // Z_STREAM_END 1
  354. "", // Z_OK 0
  355. "", // Z_ERRNO (-1)
  356. "stream error", // Z_STREAM_ERROR (-2)
  357. "data error", // Z_DATA_ERROR (-3)
  358. "", // Z_MEM_ERROR (-4)
  359. "buffer error", // Z_BUF_ERROR (-5)
  360. "",// Z_VERSION_ERROR (-6)
  361. ""];
  362. // block not completed, need more input or more output
  363. const NeedMore = 0;
  364. // block flush performed
  365. const BlockDone = 1;
  366. // finish started, need only more output at next deflate
  367. const FinishStarted = 2;
  368. // finish done, accept no more input or output
  369. const FinishDone = 3;
  370. // preset dictionary flag in zlib header
  371. const PRESET_DICT$1 = 0x20;
  372. const INIT_STATE = 42;
  373. const BUSY_STATE = 113;
  374. const FINISH_STATE = 666;
  375. // The deflate compression method
  376. const Z_DEFLATED$1 = 8;
  377. const STORED_BLOCK = 0;
  378. const STATIC_TREES = 1;
  379. const DYN_TREES = 2;
  380. const MIN_MATCH = 3;
  381. const MAX_MATCH = 258;
  382. const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  383. function smaller(tree, n, m, depth) {
  384. const tn2 = tree[n * 2];
  385. const tm2 = tree[m * 2];
  386. return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
  387. }
  388. function Deflate$1() {
  389. const that = this;
  390. let strm; // pointer back to this zlib stream
  391. let status; // as the name implies
  392. // pending_buf; // output still pending
  393. let pending_buf_size; // size of pending_buf
  394. // pending_out; // next pending byte to output to the stream
  395. // pending; // nb of bytes in the pending buffer
  396. // dist_buf; // buffer for distances
  397. // lc_buf; // buffer for literals or lengths
  398. // To simplify the code, dist_buf and lc_buf have the same number of elements.
  399. // To use different lengths, an extra flag array would be necessary.
  400. let last_flush; // value of flush param for previous deflate call
  401. let w_size; // LZ77 win size (32K by default)
  402. let w_bits; // log2(w_size) (8..16)
  403. let w_mask; // w_size - 1
  404. let win;
  405. // Sliding win. Input bytes are read into the second half of the win,
  406. // and move to the first half later to keep a dictionary of at least wSize
  407. // bytes. With this organization, matches are limited to a distance of
  408. // wSize-MAX_MATCH bytes, but this ensures that IO is always
  409. // performed with a length multiple of the block size. Also, it limits
  410. // the win size to 64K, which is quite useful on MSDOS.
  411. // To do: use the user input buffer as sliding win.
  412. let window_size;
  413. // Actual size of win: 2*wSize, except when the user input buffer
  414. // is directly used as sliding win.
  415. let prev;
  416. // Link to older string with same hash index. To limit the size of this
  417. // array to 64K, this link is maintained only for the last 32K strings.
  418. // An index in this array is thus a win index modulo 32K.
  419. let head; // Heads of the hash chains or NIL.
  420. let ins_h; // hash index of string to be inserted
  421. let hash_size; // number of elements in hash table
  422. let hash_bits; // log2(hash_size)
  423. let hash_mask; // hash_size-1
  424. // Number of bits by which ins_h must be shifted at each input
  425. // step. It must be such that after MIN_MATCH steps, the oldest
  426. // byte no longer takes part in the hash key, that is:
  427. // hash_shift * MIN_MATCH >= hash_bits
  428. let hash_shift;
  429. // Window position at the beginning of the current output block. Gets
  430. // negative when the win is moved backwards.
  431. let block_start;
  432. let match_length; // length of best match
  433. let prev_match; // previous match
  434. let match_available; // set if previous match exists
  435. let strstart; // start of string to insert
  436. let match_start; // start of matching string
  437. let lookahead; // number of valid bytes ahead in win
  438. // Length of the best match at previous step. Matches not greater than this
  439. // are discarded. This is used in the lazy match evaluation.
  440. let prev_length;
  441. // To speed up deflation, hash chains are never searched beyond this
  442. // length. A higher limit improves compression ratio but degrades the speed.
  443. let max_chain_length;
  444. // Attempt to find a better match only when the current match is strictly
  445. // smaller than this value. This mechanism is used only for compression
  446. // levels >= 4.
  447. let max_lazy_match;
  448. // Insert new strings in the hash table only if the match length is not
  449. // greater than this length. This saves time but degrades compression.
  450. // max_insert_length is used only for compression levels <= 3.
  451. let level; // compression level (1..9)
  452. let strategy; // favor or force Huffman coding
  453. // Use a faster search when the previous match is longer than this
  454. let good_match;
  455. // Stop searching when current match exceeds this
  456. let nice_match;
  457. let dyn_ltree; // literal and length tree
  458. let dyn_dtree; // distance tree
  459. let bl_tree; // Huffman tree for bit lengths
  460. const l_desc = new Tree(); // desc for literal tree
  461. const d_desc = new Tree(); // desc for distance tree
  462. const bl_desc = new Tree(); // desc for bit length tree
  463. // that.heap_len; // number of elements in the heap
  464. // that.heap_max; // element of largest frequency
  465. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  466. // The same heap array is used to build all trees.
  467. // Depth of each subtree used as tie breaker for trees of equal frequency
  468. that.depth = [];
  469. // Size of match buffer for literals/lengths. There are 4 reasons for
  470. // limiting lit_bufsize to 64K:
  471. // - frequencies can be kept in 16 bit counters
  472. // - if compression is not successful for the first block, all input
  473. // data is still in the win so we can still emit a stored block even
  474. // when input comes from standard input. (This can also be done for
  475. // all blocks if lit_bufsize is not greater than 32K.)
  476. // - if compression is not successful for a file smaller than 64K, we can
  477. // even emit a stored file instead of a stored block (saving 5 bytes).
  478. // This is applicable only for zip (not gzip or zlib).
  479. // - creating new Huffman trees less frequently may not provide fast
  480. // adaptation to changes in the input data statistics. (Take for
  481. // example a binary file with poorly compressible code followed by
  482. // a highly compressible string table.) Smaller buffer sizes give
  483. // fast adaptation but have of course the overhead of transmitting
  484. // trees more frequently.
  485. // - I can't count above 4
  486. let lit_bufsize;
  487. let last_lit; // running index in dist_buf and lc_buf
  488. // that.opt_len; // bit length of current block with optimal trees
  489. // that.static_len; // bit length of current block with static trees
  490. let matches; // number of string matches in current block
  491. let last_eob_len; // bit length of EOB code for last block
  492. // Output buffer. bits are inserted starting at the bottom (least
  493. // significant bits).
  494. let bi_buf;
  495. // Number of valid bits in bi_buf. All bits above the last valid bit
  496. // are always zero.
  497. let bi_valid;
  498. // number of codes at each bit length for an optimal tree
  499. that.bl_count = [];
  500. // heap used to build the Huffman trees
  501. that.heap = [];
  502. dyn_ltree = [];
  503. dyn_dtree = [];
  504. bl_tree = [];
  505. function lm_init() {
  506. window_size = 2 * w_size;
  507. head[hash_size - 1] = 0;
  508. for (let i = 0; i < hash_size - 1; i++) {
  509. head[i] = 0;
  510. }
  511. // Set the default configuration parameters:
  512. max_lazy_match = config_table[level].max_lazy;
  513. good_match = config_table[level].good_length;
  514. nice_match = config_table[level].nice_length;
  515. max_chain_length = config_table[level].max_chain;
  516. strstart = 0;
  517. block_start = 0;
  518. lookahead = 0;
  519. match_length = prev_length = MIN_MATCH - 1;
  520. match_available = 0;
  521. ins_h = 0;
  522. }
  523. function init_block() {
  524. let i;
  525. // Initialize the trees.
  526. for (i = 0; i < L_CODES; i++)
  527. dyn_ltree[i * 2] = 0;
  528. for (i = 0; i < D_CODES; i++)
  529. dyn_dtree[i * 2] = 0;
  530. for (i = 0; i < BL_CODES; i++)
  531. bl_tree[i * 2] = 0;
  532. dyn_ltree[END_BLOCK * 2] = 1;
  533. that.opt_len = that.static_len = 0;
  534. last_lit = matches = 0;
  535. }
  536. // Initialize the tree data structures for a new zlib stream.
  537. function tr_init() {
  538. l_desc.dyn_tree = dyn_ltree;
  539. l_desc.stat_desc = StaticTree.static_l_desc;
  540. d_desc.dyn_tree = dyn_dtree;
  541. d_desc.stat_desc = StaticTree.static_d_desc;
  542. bl_desc.dyn_tree = bl_tree;
  543. bl_desc.stat_desc = StaticTree.static_bl_desc;
  544. bi_buf = 0;
  545. bi_valid = 0;
  546. last_eob_len = 8; // enough lookahead for inflate
  547. // Initialize the first block of the first file:
  548. init_block();
  549. }
  550. // Restore the heap property by moving down the tree starting at node k,
  551. // exchanging a node with the smallest of its two sons if necessary,
  552. // stopping
  553. // when the heap property is re-established (each father smaller than its
  554. // two sons).
  555. that.pqdownheap = function (tree, // the tree to restore
  556. k // node to move down
  557. ) {
  558. const heap = that.heap;
  559. const v = heap[k];
  560. let j = k << 1; // left son of k
  561. while (j <= that.heap_len) {
  562. // Set j to the smallest of the two sons:
  563. if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
  564. j++;
  565. }
  566. // Exit if v is smaller than both sons
  567. if (smaller(tree, v, heap[j], that.depth))
  568. break;
  569. // Exchange v with the smallest son
  570. heap[k] = heap[j];
  571. k = j;
  572. // And continue down the tree, setting j to the left son of k
  573. j <<= 1;
  574. }
  575. heap[k] = v;
  576. };
  577. // Scan a literal or distance tree to determine the frequencies of the codes
  578. // in the bit length tree.
  579. function scan_tree(tree,// the tree to be scanned
  580. max_code // and its largest code of non zero frequency
  581. ) {
  582. let prevlen = -1; // last emitted length
  583. let curlen; // length of current code
  584. let nextlen = tree[0 * 2 + 1]; // length of next code
  585. let count = 0; // repeat count of the current code
  586. let max_count = 7; // max repeat count
  587. let min_count = 4; // min repeat count
  588. if (nextlen === 0) {
  589. max_count = 138;
  590. min_count = 3;
  591. }
  592. tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
  593. for (let n = 0; n <= max_code; n++) {
  594. curlen = nextlen;
  595. nextlen = tree[(n + 1) * 2 + 1];
  596. if (++count < max_count && curlen == nextlen) {
  597. continue;
  598. } else if (count < min_count) {
  599. bl_tree[curlen * 2] += count;
  600. } else if (curlen !== 0) {
  601. if (curlen != prevlen)
  602. bl_tree[curlen * 2]++;
  603. bl_tree[REP_3_6 * 2]++;
  604. } else if (count <= 10) {
  605. bl_tree[REPZ_3_10 * 2]++;
  606. } else {
  607. bl_tree[REPZ_11_138 * 2]++;
  608. }
  609. count = 0;
  610. prevlen = curlen;
  611. if (nextlen === 0) {
  612. max_count = 138;
  613. min_count = 3;
  614. } else if (curlen == nextlen) {
  615. max_count = 6;
  616. min_count = 3;
  617. } else {
  618. max_count = 7;
  619. min_count = 4;
  620. }
  621. }
  622. }
  623. // Construct the Huffman tree for the bit lengths and return the index in
  624. // bl_order of the last bit length code to send.
  625. function build_bl_tree() {
  626. let max_blindex; // index of last bit length code of non zero freq
  627. // Determine the bit length frequencies for literal and distance trees
  628. scan_tree(dyn_ltree, l_desc.max_code);
  629. scan_tree(dyn_dtree, d_desc.max_code);
  630. // Build the bit length tree:
  631. bl_desc.build_tree(that);
  632. // opt_len now includes the length of the tree representations, except
  633. // the lengths of the bit lengths codes and the 5+5+4 bits for the
  634. // counts.
  635. // Determine the number of bit length codes to send. The pkzip format
  636. // requires that at least 4 bit length codes be sent. (appnote.txt says
  637. // 3 but the actual value used is 4.)
  638. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  639. if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
  640. break;
  641. }
  642. // Update opt_len to include the bit length tree and counts
  643. that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  644. return max_blindex;
  645. }
  646. // Output a byte on the stream.
  647. // IN assertion: there is enough room in pending_buf.
  648. function put_byte(p) {
  649. that.pending_buf[that.pending++] = p;
  650. }
  651. function put_short(w) {
  652. put_byte(w & 0xff);
  653. put_byte((w >>> 8) & 0xff);
  654. }
  655. function putShortMSB(b) {
  656. put_byte((b >> 8) & 0xff);
  657. put_byte((b & 0xff) & 0xff);
  658. }
  659. function send_bits(value, length) {
  660. let val;
  661. const len = length;
  662. if (bi_valid > Buf_size - len) {
  663. val = value;
  664. // bi_buf |= (val << bi_valid);
  665. bi_buf |= ((val << bi_valid) & 0xffff);
  666. put_short(bi_buf);
  667. bi_buf = val >>> (Buf_size - bi_valid);
  668. bi_valid += len - Buf_size;
  669. } else {
  670. // bi_buf |= (value) << bi_valid;
  671. bi_buf |= (((value) << bi_valid) & 0xffff);
  672. bi_valid += len;
  673. }
  674. }
  675. function send_code(c, tree) {
  676. const c2 = c * 2;
  677. send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
  678. }
  679. // Send a literal or distance tree in compressed form, using the codes in
  680. // bl_tree.
  681. function send_tree(tree,// the tree to be sent
  682. max_code // and its largest code of non zero frequency
  683. ) {
  684. let n; // iterates over all tree elements
  685. let prevlen = -1; // last emitted length
  686. let curlen; // length of current code
  687. let nextlen = tree[0 * 2 + 1]; // length of next code
  688. let count = 0; // repeat count of the current code
  689. let max_count = 7; // max repeat count
  690. let min_count = 4; // min repeat count
  691. if (nextlen === 0) {
  692. max_count = 138;
  693. min_count = 3;
  694. }
  695. for (n = 0; n <= max_code; n++) {
  696. curlen = nextlen;
  697. nextlen = tree[(n + 1) * 2 + 1];
  698. if (++count < max_count && curlen == nextlen) {
  699. continue;
  700. } else if (count < min_count) {
  701. do {
  702. send_code(curlen, bl_tree);
  703. } while (--count !== 0);
  704. } else if (curlen !== 0) {
  705. if (curlen != prevlen) {
  706. send_code(curlen, bl_tree);
  707. count--;
  708. }
  709. send_code(REP_3_6, bl_tree);
  710. send_bits(count - 3, 2);
  711. } else if (count <= 10) {
  712. send_code(REPZ_3_10, bl_tree);
  713. send_bits(count - 3, 3);
  714. } else {
  715. send_code(REPZ_11_138, bl_tree);
  716. send_bits(count - 11, 7);
  717. }
  718. count = 0;
  719. prevlen = curlen;
  720. if (nextlen === 0) {
  721. max_count = 138;
  722. min_count = 3;
  723. } else if (curlen == nextlen) {
  724. max_count = 6;
  725. min_count = 3;
  726. } else {
  727. max_count = 7;
  728. min_count = 4;
  729. }
  730. }
  731. }
  732. // Send the header for a block using dynamic Huffman trees: the counts, the
  733. // lengths of the bit length codes, the literal tree and the distance tree.
  734. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  735. function send_all_trees(lcodes, dcodes, blcodes) {
  736. let rank; // index in bl_order
  737. send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  738. send_bits(dcodes - 1, 5);
  739. send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  740. for (rank = 0; rank < blcodes; rank++) {
  741. send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
  742. }
  743. send_tree(dyn_ltree, lcodes - 1); // literal tree
  744. send_tree(dyn_dtree, dcodes - 1); // distance tree
  745. }
  746. // Flush the bit buffer, keeping at most 7 bits in it.
  747. function bi_flush() {
  748. if (bi_valid == 16) {
  749. put_short(bi_buf);
  750. bi_buf = 0;
  751. bi_valid = 0;
  752. } else if (bi_valid >= 8) {
  753. put_byte(bi_buf & 0xff);
  754. bi_buf >>>= 8;
  755. bi_valid -= 8;
  756. }
  757. }
  758. // Send one empty static block to give enough lookahead for inflate.
  759. // This takes 10 bits, of which 7 may remain in the bit buffer.
  760. // The current inflate code requires 9 bits of lookahead. If the
  761. // last two codes for the previous block (real code plus EOB) were coded
  762. // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  763. // the last real code. In this case we send two empty static blocks instead
  764. // of one. (There are no problems if the previous block is stored or fixed.)
  765. // To simplify the code, we assume the worst case of last real code encoded
  766. // on one bit only.
  767. function _tr_align() {
  768. send_bits(STATIC_TREES << 1, 3);
  769. send_code(END_BLOCK, StaticTree.static_ltree);
  770. bi_flush();
  771. // Of the 10 bits for the empty block, we have already sent
  772. // (10 - bi_valid) bits. The lookahead for the last real code (before
  773. // the EOB of the previous block) was thus at least one plus the length
  774. // of the EOB plus what we have just sent of the empty static block.
  775. if (1 + last_eob_len + 10 - bi_valid < 9) {
  776. send_bits(STATIC_TREES << 1, 3);
  777. send_code(END_BLOCK, StaticTree.static_ltree);
  778. bi_flush();
  779. }
  780. last_eob_len = 7;
  781. }
  782. // Save the match info and tally the frequency counts. Return true if
  783. // the current block must be flushed.
  784. function _tr_tally(dist, // distance of matched string
  785. lc // match length-MIN_MATCH or unmatched char (if dist==0)
  786. ) {
  787. let out_length, in_length, dcode;
  788. that.dist_buf[last_lit] = dist;
  789. that.lc_buf[last_lit] = lc & 0xff;
  790. last_lit++;
  791. if (dist === 0) {
  792. // lc is the unmatched char
  793. dyn_ltree[lc * 2]++;
  794. } else {
  795. matches++;
  796. // Here, lc is the match length - MIN_MATCH
  797. dist--; // dist = match distance - 1
  798. dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
  799. dyn_dtree[Tree.d_code(dist) * 2]++;
  800. }
  801. if ((last_lit & 0x1fff) === 0 && level > 2) {
  802. // Compute an upper bound for the compressed length
  803. out_length = last_lit * 8;
  804. in_length = strstart - block_start;
  805. for (dcode = 0; dcode < D_CODES; dcode++) {
  806. out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
  807. }
  808. out_length >>>= 3;
  809. if ((matches < Math.floor(last_lit / 2)) && out_length < Math.floor(in_length / 2))
  810. return true;
  811. }
  812. return (last_lit == lit_bufsize - 1);
  813. // We avoid equality with lit_bufsize because of wraparound at 64K
  814. // on 16 bit machines and because stored blocks are restricted to
  815. // 64K-1 bytes.
  816. }
  817. // Send the block data compressed using the given Huffman trees
  818. function compress_block(ltree, dtree) {
  819. let dist; // distance of matched string
  820. let lc; // match length or unmatched char (if dist === 0)
  821. let lx = 0; // running index in dist_buf and lc_buf
  822. let code; // the code to send
  823. let extra; // number of extra bits to send
  824. if (last_lit !== 0) {
  825. do {
  826. dist = that.dist_buf[lx];
  827. lc = that.lc_buf[lx];
  828. lx++;
  829. if (dist === 0) {
  830. send_code(lc, ltree); // send a literal byte
  831. } else {
  832. // Here, lc is the match length - MIN_MATCH
  833. code = Tree._length_code[lc];
  834. send_code(code + LITERALS + 1, ltree); // send the length
  835. // code
  836. extra = Tree.extra_lbits[code];
  837. if (extra !== 0) {
  838. lc -= Tree.base_length[code];
  839. send_bits(lc, extra); // send the extra length bits
  840. }
  841. dist--; // dist is now the match distance - 1
  842. code = Tree.d_code(dist);
  843. send_code(code, dtree); // send the distance code
  844. extra = Tree.extra_dbits[code];
  845. if (extra !== 0) {
  846. dist -= Tree.base_dist[code];
  847. send_bits(dist, extra); // send the extra distance bits
  848. }
  849. } // literal or match pair ?
  850. } while (lx < last_lit);
  851. }
  852. send_code(END_BLOCK, ltree);
  853. last_eob_len = ltree[END_BLOCK * 2 + 1];
  854. }
  855. // Flush the bit buffer and align the output on a byte boundary
  856. function bi_windup() {
  857. if (bi_valid > 8) {
  858. put_short(bi_buf);
  859. } else if (bi_valid > 0) {
  860. put_byte(bi_buf & 0xff);
  861. }
  862. bi_buf = 0;
  863. bi_valid = 0;
  864. }
  865. // Copy a stored block, storing first the length and its
  866. // one's complement if requested.
  867. function copy_block(buf, // the input data
  868. len, // its length
  869. header // true if block header must be written
  870. ) {
  871. bi_windup(); // align on byte boundary
  872. last_eob_len = 8; // enough lookahead for inflate
  873. if (header) {
  874. put_short(len);
  875. put_short(~len);
  876. }
  877. that.pending_buf.set(win.subarray(buf, buf + len), that.pending);
  878. that.pending += len;
  879. }
  880. // Send a stored block
  881. function _tr_stored_block(buf, // input block
  882. stored_len, // length of input block
  883. eof // true if this is the last block for a file
  884. ) {
  885. send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
  886. copy_block(buf, stored_len, true); // with header
  887. }
  888. // Determine the best encoding for the current block: dynamic trees, static
  889. // trees or store, and output the encoded block to the zip file.
  890. function _tr_flush_block(buf, // input block, or NULL if too old
  891. stored_len, // length of input block
  892. eof // true if this is the last block for a file
  893. ) {
  894. let opt_lenb, static_lenb;// opt_len and static_len in bytes
  895. let max_blindex = 0; // index of last bit length code of non zero freq
  896. // Build the Huffman trees unless a stored block is forced
  897. if (level > 0) {
  898. // Construct the literal and distance trees
  899. l_desc.build_tree(that);
  900. d_desc.build_tree(that);
  901. // At this point, opt_len and static_len are the total bit lengths
  902. // of
  903. // the compressed block data, excluding the tree representations.
  904. // Build the bit length tree for the above two trees, and get the
  905. // index
  906. // in bl_order of the last bit length code to send.
  907. max_blindex = build_bl_tree();
  908. // Determine the best encoding. Compute first the block length in
  909. // bytes
  910. opt_lenb = (that.opt_len + 3 + 7) >>> 3;
  911. static_lenb = (that.static_len + 3 + 7) >>> 3;
  912. if (static_lenb <= opt_lenb)
  913. opt_lenb = static_lenb;
  914. } else {
  915. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  916. }
  917. if ((stored_len + 4 <= opt_lenb) && buf != -1) {
  918. // 4: two words for the lengths
  919. // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  920. // Otherwise we can't have processed more than WSIZE input bytes
  921. // since
  922. // the last block flush, because compression would have been
  923. // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  924. // transform a block into a stored block.
  925. _tr_stored_block(buf, stored_len, eof);
  926. } else if (static_lenb == opt_lenb) {
  927. send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
  928. compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
  929. } else {
  930. send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
  931. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
  932. compress_block(dyn_ltree, dyn_dtree);
  933. }
  934. // The above check is made mod 2^32, for files larger than 512 MB
  935. // and uLong implemented on 32 bits.
  936. init_block();
  937. if (eof) {
  938. bi_windup();
  939. }
  940. }
  941. function flush_block_only(eof) {
  942. _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
  943. block_start = strstart;
  944. strm.flush_pending();
  945. }
  946. // Fill the win when the lookahead becomes insufficient.
  947. // Updates strstart and lookahead.
  948. //
  949. // IN assertion: lookahead < MIN_LOOKAHEAD
  950. // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  951. // At least one byte has been read, or avail_in === 0; reads are
  952. // performed for at least two bytes (required for the zip translate_eol
  953. // option -- not supported here).
  954. function fill_window() {
  955. let n, m;
  956. let p;
  957. let more; // Amount of free space at the end of the win.
  958. do {
  959. more = (window_size - lookahead - strstart);
  960. // Deal with !@#$% 64K limit:
  961. if (more === 0 && strstart === 0 && lookahead === 0) {
  962. more = w_size;
  963. } else if (more == -1) {
  964. // Very unlikely, but possible on 16 bit machine if strstart ==
  965. // 0
  966. // and lookahead == 1 (input done one byte at time)
  967. more--;
  968. // If the win is almost full and there is insufficient
  969. // lookahead,
  970. // move the upper half to the lower one to make room in the
  971. // upper half.
  972. } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
  973. win.set(win.subarray(w_size, w_size + w_size), 0);
  974. match_start -= w_size;
  975. strstart -= w_size; // we now have strstart >= MAX_DIST
  976. block_start -= w_size;
  977. // Slide the hash table (could be avoided with 32 bit values
  978. // at the expense of memory usage). We slide even when level ==
  979. // 0
  980. // to keep the hash table consistent if we switch back to level
  981. // > 0
  982. // later. (Using level 0 permanently is not an optimal usage of
  983. // zlib, so we don't care about this pathological case.)
  984. n = hash_size;
  985. p = n;
  986. do {
  987. m = (head[--p] & 0xffff);
  988. head[p] = (m >= w_size ? m - w_size : 0);
  989. } while (--n !== 0);
  990. n = w_size;
  991. p = n;
  992. do {
  993. m = (prev[--p] & 0xffff);
  994. prev[p] = (m >= w_size ? m - w_size : 0);
  995. // If n is not on any hash chain, prev[n] is garbage but
  996. // its value will never be used.
  997. } while (--n !== 0);
  998. more += w_size;
  999. }
  1000. if (strm.avail_in === 0)
  1001. return;
  1002. // If there was no sliding:
  1003. // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1004. // more == window_size - lookahead - strstart
  1005. // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1006. // => more >= window_size - 2*WSIZE + 2
  1007. // In the BIG_MEM or MMAP case (not yet supported),
  1008. // window_size == input_size + MIN_LOOKAHEAD &&
  1009. // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1010. // Otherwise, window_size == 2*WSIZE so more >= 2.
  1011. // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1012. n = strm.read_buf(win, strstart + lookahead, more);
  1013. lookahead += n;
  1014. // Initialize the hash value now that we have some input:
  1015. if (lookahead >= MIN_MATCH) {
  1016. ins_h = win[strstart] & 0xff;
  1017. ins_h = (((ins_h) << hash_shift) ^ (win[strstart + 1] & 0xff)) & hash_mask;
  1018. }
  1019. // If the whole input has less than MIN_MATCH bytes, ins_h is
  1020. // garbage,
  1021. // but this is not important since only literal bytes will be
  1022. // emitted.
  1023. } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
  1024. }
  1025. // Copy without compression as much as possible from the input stream,
  1026. // return
  1027. // the current block state.
  1028. // This function does not insert new strings in the dictionary since
  1029. // uncompressible data is probably not useful. This function is used
  1030. // only for the level=0 compression option.
  1031. // NOTE: this function should be optimized to avoid extra copying from
  1032. // win to pending_buf.
  1033. function deflate_stored(flush) {
  1034. // Stored blocks are limited to 0xffff bytes, pending_buf is limited
  1035. // to pending_buf_size, and each stored block has a 5 byte header:
  1036. let max_block_size = 0xffff;
  1037. let max_start;
  1038. if (max_block_size > pending_buf_size - 5) {
  1039. max_block_size = pending_buf_size - 5;
  1040. }
  1041. // Copy as much as possible from input to output:
  1042. // eslint-disable-next-line no-constant-condition
  1043. while (true) {
  1044. // Fill the win as much as possible:
  1045. if (lookahead <= 1) {
  1046. fill_window();
  1047. if (lookahead === 0 && flush == Z_NO_FLUSH$1)
  1048. return NeedMore;
  1049. if (lookahead === 0)
  1050. break; // flush the current block
  1051. }
  1052. strstart += lookahead;
  1053. lookahead = 0;
  1054. // Emit a stored block if pending_buf will be full:
  1055. max_start = block_start + max_block_size;
  1056. if (strstart === 0 || strstart >= max_start) {
  1057. // strstart === 0 is possible when wraparound on 16-bit machine
  1058. lookahead = (strstart - max_start);
  1059. strstart = max_start;
  1060. flush_block_only(false);
  1061. if (strm.avail_out === 0)
  1062. return NeedMore;
  1063. }
  1064. // Flush if we may have to slide, otherwise block_start may become
  1065. // negative and the data will be gone:
  1066. if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
  1067. flush_block_only(false);
  1068. if (strm.avail_out === 0)
  1069. return NeedMore;
  1070. }
  1071. }
  1072. flush_block_only(flush == Z_FINISH$1);
  1073. if (strm.avail_out === 0)
  1074. return (flush == Z_FINISH$1) ? FinishStarted : NeedMore;
  1075. return flush == Z_FINISH$1 ? FinishDone : BlockDone;
  1076. }
  1077. function longest_match(cur_match) {
  1078. let chain_length = max_chain_length; // max hash chain length
  1079. let scan = strstart; // current string
  1080. let match; // matched string
  1081. let len; // length of current match
  1082. let best_len = prev_length; // best match length so far
  1083. const limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
  1084. let _nice_match = nice_match;
  1085. // Stop when cur_match becomes <= limit. To simplify the code,
  1086. // we prevent matches with the string of win index 0.
  1087. const wmask = w_mask;
  1088. const strend = strstart + MAX_MATCH;
  1089. let scan_end1 = win[scan + best_len - 1];
  1090. let scan_end = win[scan + best_len];
  1091. // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
  1092. // 16.
  1093. // It is easy to get rid of this optimization if necessary.
  1094. // Do not waste too much time if we already have a good match:
  1095. if (prev_length >= good_match) {
  1096. chain_length >>= 2;
  1097. }
  1098. // Do not look for matches beyond the end of the input. This is
  1099. // necessary
  1100. // to make deflate deterministic.
  1101. if (_nice_match > lookahead)
  1102. _nice_match = lookahead;
  1103. do {
  1104. match = cur_match;
  1105. // Skip to next match if the match length cannot increase
  1106. // or if the match length is less than 2:
  1107. if (win[match + best_len] != scan_end || win[match + best_len - 1] != scan_end1 || win[match] != win[scan]
  1108. || win[++match] != win[scan + 1])
  1109. continue;
  1110. // The check at best_len-1 can be removed because it will be made
  1111. // again later. (This heuristic is not always a win.)
  1112. // It is not necessary to compare scan[2] and match[2] since they
  1113. // are always equal when the other bytes match, given that
  1114. // the hash keys are equal and that HASH_BITS >= 8.
  1115. scan += 2;
  1116. match++;
  1117. // We check for insufficient lookahead only every 8th comparison;
  1118. // the 256th check will be made at strstart+258.
  1119. // eslint-disable-next-line no-empty
  1120. do {
  1121. } while (win[++scan] == win[++match] && win[++scan] == win[++match] && win[++scan] == win[++match]
  1122. && win[++scan] == win[++match] && win[++scan] == win[++match] && win[++scan] == win[++match]
  1123. && win[++scan] == win[++match] && win[++scan] == win[++match] && scan < strend);
  1124. len = MAX_MATCH - (strend - scan);
  1125. scan = strend - MAX_MATCH;
  1126. if (len > best_len) {
  1127. match_start = cur_match;
  1128. best_len = len;
  1129. if (len >= _nice_match)
  1130. break;
  1131. scan_end1 = win[scan + best_len - 1];
  1132. scan_end = win[scan + best_len];
  1133. }
  1134. } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length !== 0);
  1135. if (best_len <= lookahead)
  1136. return best_len;
  1137. return lookahead;
  1138. }
  1139. // Compress as much as possible from the input stream, return the current
  1140. // block state.
  1141. // This function does not perform lazy evaluation of matches and inserts
  1142. // new strings in the dictionary only for unmatched strings or for short
  1143. // matches. It is used only for the fast compression options.
  1144. function deflate_fast(flush) {
  1145. // short hash_head = 0; // head of the hash chain
  1146. let hash_head = 0; // head of the hash chain
  1147. let bflush; // set if current block must be flushed
  1148. // eslint-disable-next-line no-constant-condition
  1149. while (true) {
  1150. // Make sure that we always have enough lookahead, except
  1151. // at the end of the input file. We need MAX_MATCH bytes
  1152. // for the next match, plus MIN_MATCH bytes to insert the
  1153. // string following the next match.
  1154. if (lookahead < MIN_LOOKAHEAD) {
  1155. fill_window();
  1156. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH$1) {
  1157. return NeedMore;
  1158. }
  1159. if (lookahead === 0)
  1160. break; // flush the current block
  1161. }
  1162. // Insert the string win[strstart .. strstart+2] in the
  1163. // dictionary, and set hash_head to the head of the hash chain:
  1164. if (lookahead >= MIN_MATCH) {
  1165. ins_h = (((ins_h) << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1166. // prev[strstart&w_mask]=hash_head=head[ins_h];
  1167. hash_head = (head[ins_h] & 0xffff);
  1168. prev[strstart & w_mask] = head[ins_h];
  1169. head[ins_h] = strstart;
  1170. }
  1171. // Find the longest match, discarding those <= prev_length.
  1172. // At this point we have always match_length < MIN_MATCH
  1173. if (hash_head !== 0 && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  1174. // To simplify the code, we prevent matches with the string
  1175. // of win index 0 (in particular we have to avoid a match
  1176. // of the string with itself at the start of the input file).
  1177. if (strategy != Z_HUFFMAN_ONLY) {
  1178. match_length = longest_match(hash_head);
  1179. }
  1180. // longest_match() sets match_start
  1181. }
  1182. if (match_length >= MIN_MATCH) {
  1183. // check_match(strstart, match_start, match_length);
  1184. bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
  1185. lookahead -= match_length;
  1186. // Insert new strings in the hash table only if the match length
  1187. // is not too large. This saves time but degrades compression.
  1188. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
  1189. match_length--; // string at strstart already in hash table
  1190. do {
  1191. strstart++;
  1192. ins_h = ((ins_h << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1193. // prev[strstart&w_mask]=hash_head=head[ins_h];
  1194. hash_head = (head[ins_h] & 0xffff);
  1195. prev[strstart & w_mask] = head[ins_h];
  1196. head[ins_h] = strstart;
  1197. // strstart never exceeds WSIZE-MAX_MATCH, so there are
  1198. // always MIN_MATCH bytes ahead.
  1199. } while (--match_length !== 0);
  1200. strstart++;
  1201. } else {
  1202. strstart += match_length;
  1203. match_length = 0;
  1204. ins_h = win[strstart] & 0xff;
  1205. ins_h = (((ins_h) << hash_shift) ^ (win[strstart + 1] & 0xff)) & hash_mask;
  1206. // If lookahead < MIN_MATCH, ins_h is garbage, but it does
  1207. // not
  1208. // matter since it will be recomputed at next deflate call.
  1209. }
  1210. } else {
  1211. // No match, output a literal byte
  1212. bflush = _tr_tally(0, win[strstart] & 0xff);
  1213. lookahead--;
  1214. strstart++;
  1215. }
  1216. if (bflush) {
  1217. flush_block_only(false);
  1218. if (strm.avail_out === 0)
  1219. return NeedMore;
  1220. }
  1221. }
  1222. flush_block_only(flush == Z_FINISH$1);
  1223. if (strm.avail_out === 0) {
  1224. if (flush == Z_FINISH$1)
  1225. return FinishStarted;
  1226. else
  1227. return NeedMore;
  1228. }
  1229. return flush == Z_FINISH$1 ? FinishDone : BlockDone;
  1230. }
  1231. // Same as above, but achieves better compression. We use a lazy
  1232. // evaluation for matches: a match is finally adopted only if there is
  1233. // no better match at the next win position.
  1234. function deflate_slow(flush) {
  1235. // short hash_head = 0; // head of hash chain
  1236. let hash_head = 0; // head of hash chain
  1237. let bflush; // set if current block must be flushed
  1238. let max_insert;
  1239. // Process the input block.
  1240. // eslint-disable-next-line no-constant-condition
  1241. while (true) {
  1242. // Make sure that we always have enough lookahead, except
  1243. // at the end of the input file. We need MAX_MATCH bytes
  1244. // for the next match, plus MIN_MATCH bytes to insert the
  1245. // string following the next match.
  1246. if (lookahead < MIN_LOOKAHEAD) {
  1247. fill_window();
  1248. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH$1) {
  1249. return NeedMore;
  1250. }
  1251. if (lookahead === 0)
  1252. break; // flush the current block
  1253. }
  1254. // Insert the string win[strstart .. strstart+2] in the
  1255. // dictionary, and set hash_head to the head of the hash chain:
  1256. if (lookahead >= MIN_MATCH) {
  1257. ins_h = (((ins_h) << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1258. // prev[strstart&w_mask]=hash_head=head[ins_h];
  1259. hash_head = (head[ins_h] & 0xffff);
  1260. prev[strstart & w_mask] = head[ins_h];
  1261. head[ins_h] = strstart;
  1262. }
  1263. // Find the longest match, discarding those <= prev_length.
  1264. prev_length = match_length;
  1265. prev_match = match_start;
  1266. match_length = MIN_MATCH - 1;
  1267. if (hash_head !== 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  1268. // To simplify the code, we prevent matches with the string
  1269. // of win index 0 (in particular we have to avoid a match
  1270. // of the string with itself at the start of the input file).
  1271. if (strategy != Z_HUFFMAN_ONLY) {
  1272. match_length = longest_match(hash_head);
  1273. }
  1274. // longest_match() sets match_start
  1275. if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
  1276. // If prev_match is also MIN_MATCH, match_start is garbage
  1277. // but we will ignore the current match anyway.
  1278. match_length = MIN_MATCH - 1;
  1279. }
  1280. }
  1281. // If there was a match at the previous step and the current
  1282. // match is not better, output the previous match:
  1283. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  1284. max_insert = strstart + lookahead - MIN_MATCH;
  1285. // Do not insert strings in hash table beyond this.
  1286. // check_match(strstart-1, prev_match, prev_length);
  1287. bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
  1288. // Insert in hash table all strings up to the end of the match.
  1289. // strstart-1 and strstart are already inserted. If there is not
  1290. // enough lookahead, the last two strings are not inserted in
  1291. // the hash table.
  1292. lookahead -= prev_length - 1;
  1293. prev_length -= 2;
  1294. do {
  1295. if (++strstart <= max_insert) {
  1296. ins_h = (((ins_h) << hash_shift) ^ (win[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1297. // prev[strstart&w_mask]=hash_head=head[ins_h];
  1298. hash_head = (head[ins_h] & 0xffff);
  1299. prev[strstart & w_mask] = head[ins_h];
  1300. head[ins_h] = strstart;
  1301. }
  1302. } while (--prev_length !== 0);
  1303. match_available = 0;
  1304. match_length = MIN_MATCH - 1;
  1305. strstart++;
  1306. if (bflush) {
  1307. flush_block_only(false);
  1308. if (strm.avail_out === 0)
  1309. return NeedMore;
  1310. }
  1311. } else if (match_available !== 0) {
  1312. // If there was no match at the previous position, output a
  1313. // single literal. If there was a match but the current match
  1314. // is longer, truncate the previous match to a single literal.
  1315. bflush = _tr_tally(0, win[strstart - 1] & 0xff);
  1316. if (bflush) {
  1317. flush_block_only(false);
  1318. }
  1319. strstart++;
  1320. lookahead--;
  1321. if (strm.avail_out === 0)
  1322. return NeedMore;
  1323. } else {
  1324. // There is no previous match to compare with, wait for
  1325. // the next step to decide.
  1326. match_available = 1;
  1327. strstart++;
  1328. lookahead--;
  1329. }
  1330. }
  1331. if (match_available !== 0) {
  1332. bflush = _tr_tally(0, win[strstart - 1] & 0xff);
  1333. match_available = 0;
  1334. }
  1335. flush_block_only(flush == Z_FINISH$1);
  1336. if (strm.avail_out === 0) {
  1337. if (flush == Z_FINISH$1)
  1338. return FinishStarted;
  1339. else
  1340. return NeedMore;
  1341. }
  1342. return flush == Z_FINISH$1 ? FinishDone : BlockDone;
  1343. }
  1344. function deflateReset(strm) {
  1345. strm.total_in = strm.total_out = 0;
  1346. strm.msg = null; //
  1347. that.pending = 0;
  1348. that.pending_out = 0;
  1349. status = BUSY_STATE;
  1350. last_flush = Z_NO_FLUSH$1;
  1351. tr_init();
  1352. lm_init();
  1353. return Z_OK$1;
  1354. }
  1355. that.deflateInit = function (strm, _level, bits, _method, memLevel, _strategy) {
  1356. if (!_method)
  1357. _method = Z_DEFLATED$1;
  1358. if (!memLevel)
  1359. memLevel = DEF_MEM_LEVEL;
  1360. if (!_strategy)
  1361. _strategy = Z_DEFAULT_STRATEGY;
  1362. // byte[] my_version=ZLIB_VERSION;
  1363. //
  1364. // if (!version || version[0] != my_version[0]
  1365. // || stream_size != sizeof(z_stream)) {
  1366. // return Z_VERSION_ERROR;
  1367. // }
  1368. strm.msg = null;
  1369. if (_level == Z_DEFAULT_COMPRESSION)
  1370. _level = 6;
  1371. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED$1 || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0
  1372. || _strategy > Z_HUFFMAN_ONLY) {
  1373. return Z_STREAM_ERROR$1;
  1374. }
  1375. strm.dstate = that;
  1376. w_bits = bits;
  1377. w_size = 1 << w_bits;
  1378. w_mask = w_size - 1;
  1379. hash_bits = memLevel + 7;
  1380. hash_size = 1 << hash_bits;
  1381. hash_mask = hash_size - 1;
  1382. hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  1383. win = new Uint8Array(w_size * 2);
  1384. prev = [];
  1385. head = [];
  1386. lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
  1387. that.pending_buf = new Uint8Array(lit_bufsize * 4);
  1388. pending_buf_size = lit_bufsize * 4;
  1389. that.dist_buf = new Uint16Array(lit_bufsize);
  1390. that.lc_buf = new Uint8Array(lit_bufsize);
  1391. level = _level;
  1392. strategy = _strategy;
  1393. return deflateReset(strm);
  1394. };
  1395. that.deflateEnd = function () {
  1396. if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
  1397. return Z_STREAM_ERROR$1;
  1398. }
  1399. // Deallocate in reverse order of allocations:
  1400. that.lc_buf = null;
  1401. that.dist_buf = null;
  1402. that.pending_buf = null;
  1403. head = null;
  1404. prev = null;
  1405. win = null;
  1406. // free
  1407. that.dstate = null;
  1408. return status == BUSY_STATE ? Z_DATA_ERROR$1 : Z_OK$1;
  1409. };
  1410. that.deflateParams = function (strm, _level, _strategy) {
  1411. let err = Z_OK$1;
  1412. if (_level == Z_DEFAULT_COMPRESSION) {
  1413. _level = 6;
  1414. }
  1415. if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  1416. return Z_STREAM_ERROR$1;
  1417. }
  1418. if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
  1419. // Flush the last buffer:
  1420. err = strm.deflate(Z_PARTIAL_FLUSH);
  1421. }
  1422. if (level != _level) {
  1423. level = _level;
  1424. max_lazy_match = config_table[level].max_lazy;
  1425. good_match = config_table[level].good_length;
  1426. nice_match = config_table[level].nice_length;
  1427. max_chain_length = config_table[level].max_chain;
  1428. }
  1429. strategy = _strategy;
  1430. return err;
  1431. };
  1432. that.deflateSetDictionary = function (strm, dictionary, dictLength) {
  1433. let length = dictLength;
  1434. let n, index = 0;
  1435. if (!dictionary || status != INIT_STATE)
  1436. return Z_STREAM_ERROR$1;
  1437. if (length < MIN_MATCH)
  1438. return Z_OK$1;
  1439. if (length > w_size - MIN_LOOKAHEAD) {
  1440. length = w_size - MIN_LOOKAHEAD;
  1441. index = dictLength - length; // use the tail of the dictionary
  1442. }
  1443. win.set(dictionary.subarray(index, index + length), 0);
  1444. strstart = length;
  1445. block_start = length;
  1446. // Insert all strings in the hash table (except for the last two bytes).
  1447. // s->lookahead stays null, so s->ins_h will be recomputed at the next
  1448. // call of fill_window.
  1449. ins_h = win[0] & 0xff;
  1450. ins_h = (((ins_h) << hash_shift) ^ (win[1] & 0xff)) & hash_mask;
  1451. for (n = 0; n <= length - MIN_MATCH; n++) {
  1452. ins_h = (((ins_h) << hash_shift) ^ (win[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
  1453. prev[n & w_mask] = head[ins_h];
  1454. head[ins_h] = n;
  1455. }
  1456. return Z_OK$1;
  1457. };
  1458. that.deflate = function (_strm, flush) {
  1459. let i, header, level_flags, old_flush, bstate;
  1460. if (flush > Z_FINISH$1 || flush < 0) {
  1461. return Z_STREAM_ERROR$1;
  1462. }
  1463. if (!_strm.next_out || (!_strm.next_in && _strm.avail_in !== 0) || (status == FINISH_STATE && flush != Z_FINISH$1)) {
  1464. _strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_STREAM_ERROR$1)];
  1465. return Z_STREAM_ERROR$1;
  1466. }
  1467. if (_strm.avail_out === 0) {
  1468. _strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_BUF_ERROR$1)];
  1469. return Z_BUF_ERROR$1;
  1470. }
  1471. strm = _strm; // just in case
  1472. old_flush = last_flush;
  1473. last_flush = flush;
  1474. // Write the zlib header
  1475. if (status == INIT_STATE) {
  1476. header = (Z_DEFLATED$1 + ((w_bits - 8) << 4)) << 8;
  1477. level_flags = ((level - 1) & 0xff) >> 1;
  1478. if (level_flags > 3)
  1479. level_flags = 3;
  1480. header |= (level_flags << 6);
  1481. if (strstart !== 0)
  1482. header |= PRESET_DICT$1;
  1483. header += 31 - (header % 31);
  1484. status = BUSY_STATE;
  1485. putShortMSB(header);
  1486. }
  1487. // Flush as much pending output as possible
  1488. if (that.pending !== 0) {
  1489. strm.flush_pending();
  1490. if (strm.avail_out === 0) {
  1491. // console.log(" avail_out==0");
  1492. // Since avail_out is 0, deflate will be called again with
  1493. // more output space, but possibly with both pending and
  1494. // avail_in equal to zero. There won't be anything to do,
  1495. // but this is not an error situation so make sure we
  1496. // return OK instead of BUF_ERROR at next call of deflate:
  1497. last_flush = -1;
  1498. return Z_OK$1;
  1499. }
  1500. // Make sure there is something to do and avoid duplicate
  1501. // consecutive
  1502. // flushes. For repeated and useless calls with Z_FINISH, we keep
  1503. // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  1504. } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH$1) {
  1505. strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_BUF_ERROR$1)];
  1506. return Z_BUF_ERROR$1;
  1507. }
  1508. // User must not provide more input after the first FINISH:
  1509. if (status == FINISH_STATE && strm.avail_in !== 0) {
  1510. _strm.msg = z_errmsg[Z_NEED_DICT$1 - (Z_BUF_ERROR$1)];
  1511. return Z_BUF_ERROR$1;
  1512. }
  1513. // Start a new block or continue the current one.
  1514. if (strm.avail_in !== 0 || lookahead !== 0 || (flush != Z_NO_FLUSH$1 && status != FINISH_STATE)) {
  1515. bstate = -1;
  1516. switch (config_table[level].func) {
  1517. case STORED$1:
  1518. bstate = deflate_stored(flush);
  1519. break;
  1520. case FAST:
  1521. bstate = deflate_fast(flush);
  1522. break;
  1523. case SLOW:
  1524. bstate = deflate_slow(flush);
  1525. break;
  1526. }
  1527. if (bstate == FinishStarted || bstate == FinishDone) {
  1528. status = FINISH_STATE;
  1529. }
  1530. if (bstate == NeedMore || bstate == FinishStarted) {
  1531. if (strm.avail_out === 0) {
  1532. last_flush = -1; // avoid BUF_ERROR next call, see above
  1533. }
  1534. return Z_OK$1;
  1535. // If flush != Z_NO_FLUSH && avail_out === 0, the next call
  1536. // of deflate should use the same flush parameter to make sure
  1537. // that the flush is complete. So we don't have to output an
  1538. // empty block here, this will be done at next call. This also
  1539. // ensures that for a very small output buffer, we emit at most
  1540. // one empty block.
  1541. }
  1542. if (bstate == BlockDone) {
  1543. if (flush == Z_PARTIAL_FLUSH) {
  1544. _tr_align();
  1545. } else { // FULL_FLUSH or SYNC_FLUSH
  1546. _tr_stored_block(0, 0, false);
  1547. // For a full flush, this empty block will be recognized
  1548. // as a special marker by inflate_sync().
  1549. if (flush == Z_FULL_FLUSH) {
  1550. // state.head[s.hash_size-1]=0;
  1551. for (i = 0; i < hash_size/*-1*/; i++)
  1552. // forget history
  1553. head[i] = 0;
  1554. }
  1555. }
  1556. strm.flush_pending();
  1557. if (strm.avail_out === 0) {
  1558. last_flush = -1; // avoid BUF_ERROR at next call, see above
  1559. return Z_OK$1;
  1560. }
  1561. }
  1562. }
  1563. if (flush != Z_FINISH$1)
  1564. return Z_OK$1;
  1565. return Z_STREAM_END$1;
  1566. };
  1567. }
  1568. // ZStream
  1569. function ZStream$1() {
  1570. const that = this;
  1571. that.next_in_index = 0;
  1572. that.next_out_index = 0;
  1573. // that.next_in; // next input byte
  1574. that.avail_in = 0; // number of bytes available at next_in
  1575. that.total_in = 0; // total nb of input bytes read so far
  1576. // that.next_out; // next output byte should be put there
  1577. that.avail_out = 0; // remaining free space at next_out
  1578. that.total_out = 0; // total nb of bytes output so far
  1579. // that.msg;
  1580. // that.dstate;
  1581. }
  1582. ZStream$1.prototype = {
  1583. deflateInit: function (level, bits) {
  1584. const that = this;
  1585. that.dstate = new Deflate$1();
  1586. if (!bits)
  1587. bits = MAX_BITS$1;
  1588. return that.dstate.deflateInit(that, level, bits);
  1589. },
  1590. deflate: function (flush) {
  1591. const that = this;
  1592. if (!that.dstate) {
  1593. return Z_STREAM_ERROR$1;
  1594. }
  1595. return that.dstate.deflate(that, flush);
  1596. },
  1597. deflateEnd: function () {
  1598. const that = this;
  1599. if (!that.dstate)
  1600. return Z_STREAM_ERROR$1;
  1601. const ret = that.dstate.deflateEnd();
  1602. that.dstate = null;
  1603. return ret;
  1604. },
  1605. deflateParams: function (level, strategy) {
  1606. const that = this;
  1607. if (!that.dstate)
  1608. return Z_STREAM_ERROR$1;
  1609. return that.dstate.deflateParams(that, level, strategy);
  1610. },
  1611. deflateSetDictionary: function (dictionary, dictLength) {
  1612. const that = this;
  1613. if (!that.dstate)
  1614. return Z_STREAM_ERROR$1;
  1615. return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
  1616. },
  1617. // Read a new buffer from the current input stream, update the
  1618. // total number of bytes read. All deflate() input goes through
  1619. // this function so some applications may wish to modify it to avoid
  1620. // allocating a large strm->next_in buffer and copying from it.
  1621. // (See also flush_pending()).
  1622. read_buf: function (buf, start, size) {
  1623. const that = this;
  1624. let len = that.avail_in;
  1625. if (len > size)
  1626. len = size;
  1627. if (len === 0)
  1628. return 0;
  1629. that.avail_in -= len;
  1630. buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
  1631. that.next_in_index += len;
  1632. that.total_in += len;
  1633. return len;
  1634. },
  1635. // Flush as much pending output as possible. All deflate() output goes
  1636. // through this function so some applications may wish to modify it
  1637. // to avoid allocating a large strm->next_out buffer and copying into it.
  1638. // (See also read_buf()).
  1639. flush_pending: function () {
  1640. const that = this;
  1641. let len = that.dstate.pending;
  1642. if (len > that.avail_out)
  1643. len = that.avail_out;
  1644. if (len === 0)
  1645. return;
  1646. // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
  1647. // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
  1648. // len)) {
  1649. // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
  1650. // that.next_out_index + ", " + len);
  1651. // console.log("avail_out=" + that.avail_out);
  1652. // }
  1653. that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
  1654. that.next_out_index += len;
  1655. that.dstate.pending_out += len;
  1656. that.total_out += len;
  1657. that.avail_out -= len;
  1658. that.dstate.pending -= len;
  1659. if (that.dstate.pending === 0) {
  1660. that.dstate.pending_out = 0;
  1661. }
  1662. }
  1663. };
  1664. // Deflate
  1665. function ZipDeflate(options) {
  1666. const that = this;
  1667. const z = new ZStream$1();
  1668. const bufsize = getMaximumCompressedSize$1(options && options.chunkSize ? options.chunkSize : 64 * 1024);
  1669. const flush = Z_NO_FLUSH$1;
  1670. const buf = new Uint8Array(bufsize);
  1671. let level = options ? options.level : Z_DEFAULT_COMPRESSION;
  1672. if (typeof level == "undefined")
  1673. level = Z_DEFAULT_COMPRESSION;
  1674. z.deflateInit(level);
  1675. z.next_out = buf;
  1676. that.append = function (data, onprogress) {
  1677. let err, array, lastIndex = 0, bufferIndex = 0, bufferSize = 0;
  1678. const buffers = [];
  1679. if (!data.length)
  1680. return;
  1681. z.next_in_index = 0;
  1682. z.next_in = data;
  1683. z.avail_in = data.length;
  1684. do {
  1685. z.next_out_index = 0;
  1686. z.avail_out = bufsize;
  1687. err = z.deflate(flush);
  1688. if (err != Z_OK$1)
  1689. throw new Error("deflating: " + z.msg);
  1690. if (z.next_out_index)
  1691. if (z.next_out_index == bufsize)
  1692. buffers.push(new Uint8Array(buf));
  1693. else
  1694. buffers.push(buf.slice(0, z.next_out_index));
  1695. bufferSize += z.next_out_index;
  1696. if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  1697. onprogress(z.next_in_index);
  1698. lastIndex = z.next_in_index;
  1699. }
  1700. } while (z.avail_in > 0 || z.avail_out === 0);
  1701. if (buffers.length > 1) {
  1702. array = new Uint8Array(bufferSize);
  1703. buffers.forEach(function (chunk) {
  1704. array.set(chunk, bufferIndex);
  1705. bufferIndex += chunk.length;
  1706. });
  1707. } else {
  1708. array = buffers[0] || new Uint8Array(0);
  1709. }
  1710. return array;
  1711. };
  1712. that.flush = function () {
  1713. let err, array, bufferIndex = 0, bufferSize = 0;
  1714. const buffers = [];
  1715. do {
  1716. z.next_out_index = 0;
  1717. z.avail_out = bufsize;
  1718. err = z.deflate(Z_FINISH$1);
  1719. if (err != Z_STREAM_END$1 && err != Z_OK$1)
  1720. throw new Error("deflating: " + z.msg);
  1721. if (bufsize - z.avail_out > 0)
  1722. buffers.push(buf.slice(0, z.next_out_index));
  1723. bufferSize += z.next_out_index;
  1724. } while (z.avail_in > 0 || z.avail_out === 0);
  1725. z.deflateEnd();
  1726. array = new Uint8Array(bufferSize);
  1727. buffers.forEach(function (chunk) {
  1728. array.set(chunk, bufferIndex);
  1729. bufferIndex += chunk.length;
  1730. });
  1731. return array;
  1732. };
  1733. }
  1734. function getMaximumCompressedSize$1(uncompressedSize) {
  1735. return uncompressedSize + (5 * (Math.floor(uncompressedSize / 16383) + 1));
  1736. }
  1737. /*
  1738. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1739. Redistribution and use in source and binary forms, with or without
  1740. modification, are permitted provided that the following conditions are met:
  1741. 1. Redistributions of source code must retain the above copyright notice,
  1742. this list of conditions and the following disclaimer.
  1743. 2. Redistributions in binary form must reproduce the above copyright
  1744. notice, this list of conditions and the following disclaimer in
  1745. the documentation and/or other materials provided with the distribution.
  1746. 3. The names of the authors may not be used to endorse or promote products
  1747. derived from this software without specific prior written permission.
  1748. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1749. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1750. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1751. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1752. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1753. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1754. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1755. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1756. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1757. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1758. */
  1759. /*
  1760. * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
  1761. * JZlib is based on zlib-1.1.3, so all credit should go authors
  1762. * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  1763. * and contributors of zlib.
  1764. */
  1765. // Global
  1766. const MAX_BITS = 15;
  1767. const Z_OK = 0;
  1768. const Z_STREAM_END = 1;
  1769. const Z_NEED_DICT = 2;
  1770. const Z_STREAM_ERROR = -2;
  1771. const Z_DATA_ERROR = -3;
  1772. const Z_MEM_ERROR = -4;
  1773. const Z_BUF_ERROR = -5;
  1774. const inflate_mask = [0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff,
  1775. 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff];
  1776. const MANY = 1440;
  1777. // JZlib version : "1.0.2"
  1778. const Z_NO_FLUSH = 0;
  1779. const Z_FINISH = 4;
  1780. // InfTree
  1781. const fixed_bl = 9;
  1782. const fixed_bd = 5;
  1783. const fixed_tl = [96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0,
  1784. 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40,
  1785. 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13,
  1786. 0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60,
  1787. 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7,
  1788. 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8,
  1789. 26, 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80,
  1790. 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0,
  1791. 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0,
  1792. 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97,
  1793. 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210,
  1794. 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117,
  1795. 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154,
  1796. 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83,
  1797. 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230,
  1798. 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139,
  1799. 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174,
  1800. 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111,
  1801. 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9,
  1802. 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8,
  1803. 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8,
  1804. 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8,
  1805. 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9,
  1806. 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8,
  1807. 130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9,
  1808. 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8,
  1809. 102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9,
  1810. 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0,
  1811. 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9,
  1812. 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8,
  1813. 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9,
  1814. 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8,
  1815. 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9,
  1816. 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8,
  1817. 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9,
  1818. 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8,
  1819. 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 255];
  1820. const fixed_td = [80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33, 92, 5,
  1821. 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537, 85, 5, 97, 93, 5,
  1822. 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5, 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577];
  1823. // Tables for deflate from PKZIP's appnote.txt.
  1824. const cplens = [ // Copy lengths for literal codes 257..285
  1825. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0];
  1826. // see note #13 above about 258
  1827. const cplext = [ // Extra bits for literal codes 257..285
  1828. 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, 112, 112 // 112==invalid
  1829. ];
  1830. const cpdist = [ // Copy offsets for distance codes 0..29
  1831. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
  1832. const cpdext = [ // Extra bits for distance codes
  1833. 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];
  1834. // If BMAX needs to be larger than 16, then h and x[] should be uLong.
  1835. const BMAX = 15; // maximum bit length of any code
  1836. function InfTree() {
  1837. const that = this;
  1838. let hn; // hufts used in space
  1839. let v; // work area for huft_build
  1840. let c; // bit length count table
  1841. let r; // table entry for structure assignment
  1842. let u; // table stack
  1843. let x; // bit offsets, then code stack
  1844. function huft_build(b, // code lengths in bits (all assumed <=
  1845. // BMAX)
  1846. bindex, n, // number of codes (assumed <= 288)
  1847. s, // number of simple-valued codes (0..s-1)
  1848. d, // list of base values for non-simple codes
  1849. e, // list of extra bits for non-simple codes
  1850. t, // result: starting table
  1851. m, // maximum lookup bits, returns actual
  1852. hp,// space for trees
  1853. hn,// hufts used in space
  1854. v // working area: values in order of bit length
  1855. ) {
  1856. // Given a list of code lengths and a maximum table size, make a set of
  1857. // tables to decode that set of codes. Return Z_OK on success,
  1858. // Z_BUF_ERROR
  1859. // if the given code set is incomplete (the tables are still built in
  1860. // this
  1861. // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set
  1862. // of
  1863. // lengths), or Z_MEM_ERROR if not enough memory.
  1864. let a; // counter for codes of length k
  1865. let f; // i repeats in table every f entries
  1866. let g; // maximum code length
  1867. let h; // table level
  1868. let i; // counter, current code
  1869. let j; // counter
  1870. let k; // number of bits in current code
  1871. let l; // bits per table (returned in m)
  1872. let mask; // (1 << w) - 1, to avoid cc -O bug on HP
  1873. let p; // pointer into c[], b[], or v[]
  1874. let q; // points to current table
  1875. let w; // bits before this table == (l * h)
  1876. let xp; // pointer into x
  1877. let y; // number of dummy codes added
  1878. let z; // number of entries in current table
  1879. // Generate counts for each bit length
  1880. p = 0;
  1881. i = n;
  1882. do {
  1883. c[b[bindex + p]]++;
  1884. p++;
  1885. i--; // assume all entries <= BMAX
  1886. } while (i !== 0);
  1887. if (c[0] == n) { // null input--all zero length codes
  1888. t[0] = -1;
  1889. m[0] = 0;
  1890. return Z_OK;
  1891. }
  1892. // Find minimum and maximum length, bound *m by those
  1893. l = m[0];
  1894. for (j = 1; j <= BMAX; j++)
  1895. if (c[j] !== 0)
  1896. break;
  1897. k = j; // minimum code length
  1898. if (l < j) {
  1899. l = j;
  1900. }
  1901. for (i = BMAX; i !== 0; i--) {
  1902. if (c[i] !== 0)
  1903. break;
  1904. }
  1905. g = i; // maximum code length
  1906. if (l > i) {
  1907. l = i;
  1908. }
  1909. m[0] = l;
  1910. // Adjust last length count to fill out codes, if needed
  1911. for (y = 1 << j; j < i; j++, y <<= 1) {
  1912. if ((y -= c[j]) < 0) {
  1913. return Z_DATA_ERROR;
  1914. }
  1915. }
  1916. if ((y -= c[i]) < 0) {
  1917. return Z_DATA_ERROR;
  1918. }
  1919. c[i] += y;
  1920. // Generate starting offsets into the value table for each length
  1921. x[1] = j = 0;
  1922. p = 1;
  1923. xp = 2;
  1924. while (--i !== 0) { // note that i == g from above
  1925. x[xp] = (j += c[p]);
  1926. xp++;
  1927. p++;
  1928. }
  1929. // Make a table of values in order of bit lengths
  1930. i = 0;
  1931. p = 0;
  1932. do {
  1933. if ((j = b[bindex + p]) !== 0) {
  1934. v[x[j]++] = i;
  1935. }
  1936. p++;
  1937. } while (++i < n);
  1938. n = x[g]; // set n to length of v
  1939. // Generate the Huffman codes and for each, make the table entries
  1940. x[0] = i = 0; // first Huffman code is zero
  1941. p = 0; // grab values in bit order
  1942. h = -1; // no tables yet--level -1
  1943. w = -l; // bits decoded == (l * h)
  1944. u[0] = 0; // just to keep compilers happy
  1945. q = 0; // ditto
  1946. z = 0; // ditto
  1947. // go through the bit lengths (k already is bits in shortest code)
  1948. for (; k <= g; k++) {
  1949. a = c[k];
  1950. while (a-- !== 0) {
  1951. // here i is the Huffman code of length k bits for value *p
  1952. // make tables up to required level
  1953. while (k > w + l) {
  1954. h++;
  1955. w += l; // previous table always l bits
  1956. // compute minimum size table less than or equal to l bits
  1957. z = g - w;
  1958. z = (z > l) ? l : z; // table size upper limit
  1959. if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table
  1960. // too few codes for
  1961. // k-w bit table
  1962. f -= a + 1; // deduct codes from patterns left
  1963. xp = k;
  1964. if (j < z) {
  1965. while (++j < z) { // try smaller tables up to z bits
  1966. if ((f <<= 1) <= c[++xp])
  1967. break; // enough codes to use up j bits
  1968. f -= c[xp]; // else deduct codes from patterns
  1969. }
  1970. }
  1971. }
  1972. z = 1 << j; // table entries for j-bit table
  1973. // allocate new table
  1974. if (hn[0] + z > MANY) { // (note: doesn't matter for fixed)
  1975. return Z_DATA_ERROR; // overflow of MANY
  1976. }
  1977. u[h] = q = /* hp+ */hn[0]; // DEBUG
  1978. hn[0] += z;
  1979. // connect to last table, if there is one
  1980. if (h !== 0) {
  1981. x[h] = i; // save pattern for backing up
  1982. r[0] = /* (byte) */j; // bits in this table
  1983. r[1] = /* (byte) */l; // bits to dump before this table
  1984. j = i >>> (w - l);
  1985. r[2] = /* (int) */(q - u[h - 1] - j); // offset to this table
  1986. hp.set(r, (u[h - 1] + j) * 3);
  1987. // to
  1988. // last
  1989. // table
  1990. } else {
  1991. t[0] = q; // first table is returned result
  1992. }
  1993. }
  1994. // set up table entry in r
  1995. r[1] = /* (byte) */(k - w);
  1996. if (p >= n) {
  1997. r[0] = 128 + 64; // out of values--invalid code
  1998. } else if (v[p] < s) {
  1999. r[0] = /* (byte) */(v[p] < 256 ? 0 : 32 + 64); // 256 is
  2000. // end-of-block
  2001. r[2] = v[p++]; // simple code is just the value
  2002. } else {
  2003. r[0] = /* (byte) */(e[v[p] - s] + 16 + 64); // non-simple--look
  2004. // up in lists
  2005. r[2] = d[v[p++] - s];
  2006. }
  2007. // fill code-like entries with r
  2008. f = 1 << (k - w);
  2009. for (j = i >>> w; j < z; j += f) {
  2010. hp.set(r, (q + j) * 3);
  2011. }
  2012. // backwards increment the k-bit code i
  2013. for (j = 1 << (k - 1); (i & j) !== 0; j >>>= 1) {
  2014. i ^= j;
  2015. }
  2016. i ^= j;
  2017. // backup over finished tables
  2018. mask = (1 << w) - 1; // needed on HP, cc -O bug
  2019. while ((i & mask) != x[h]) {
  2020. h--; // don't need to update q
  2021. w -= l;
  2022. mask = (1 << w) - 1;
  2023. }
  2024. }
  2025. }
  2026. // Return Z_BUF_ERROR if we were given an incomplete table
  2027. return y !== 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
  2028. }
  2029. function initWorkArea(vsize) {
  2030. let i;
  2031. if (!hn) {
  2032. hn = []; // []; //new Array(1);
  2033. v = []; // new Array(vsize);
  2034. c = new Int32Array(BMAX + 1); // new Array(BMAX + 1);
  2035. r = []; // new Array(3);
  2036. u = new Int32Array(BMAX); // new Array(BMAX);
  2037. x = new Int32Array(BMAX + 1); // new Array(BMAX + 1);
  2038. }
  2039. if (v.length < vsize) {
  2040. v = []; // new Array(vsize);
  2041. }
  2042. for (i = 0; i < vsize; i++) {
  2043. v[i] = 0;
  2044. }
  2045. for (i = 0; i < BMAX + 1; i++) {
  2046. c[i] = 0;
  2047. }
  2048. for (i = 0; i < 3; i++) {
  2049. r[i] = 0;
  2050. }
  2051. // for(int i=0; i<BMAX; i++){u[i]=0;}
  2052. u.set(c.subarray(0, BMAX), 0);
  2053. // for(int i=0; i<BMAX+1; i++){x[i]=0;}
  2054. x.set(c.subarray(0, BMAX + 1), 0);
  2055. }
  2056. that.inflate_trees_bits = function (c, // 19 code lengths
  2057. bb, // bits tree desired/actual depth
  2058. tb, // bits tree result
  2059. hp, // space for trees
  2060. z // for messages
  2061. ) {
  2062. let result;
  2063. initWorkArea(19);
  2064. hn[0] = 0;
  2065. result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);
  2066. if (result == Z_DATA_ERROR) {
  2067. z.msg = "oversubscribed dynamic bit lengths tree";
  2068. } else if (result == Z_BUF_ERROR || bb[0] === 0) {
  2069. z.msg = "incomplete dynamic bit lengths tree";
  2070. result = Z_DATA_ERROR;
  2071. }
  2072. return result;
  2073. };
  2074. that.inflate_trees_dynamic = function (nl, // number of literal/length codes
  2075. nd, // number of distance codes
  2076. c, // that many (total) code lengths
  2077. bl, // literal desired/actual bit depth
  2078. bd, // distance desired/actual bit depth
  2079. tl, // literal/length tree result
  2080. td, // distance tree result
  2081. hp, // space for trees
  2082. z // for messages
  2083. ) {
  2084. let result;
  2085. // build literal/length tree
  2086. initWorkArea(288);
  2087. hn[0] = 0;
  2088. result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v);
  2089. if (result != Z_OK || bl[0] === 0) {
  2090. if (result == Z_DATA_ERROR) {
  2091. z.msg = "oversubscribed literal/length tree";
  2092. } else if (result != Z_MEM_ERROR) {
  2093. z.msg = "incomplete literal/length tree";
  2094. result = Z_DATA_ERROR;
  2095. }
  2096. return result;
  2097. }
  2098. // build distance tree
  2099. initWorkArea(288);
  2100. result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v);
  2101. if (result != Z_OK || (bd[0] === 0 && nl > 257)) {
  2102. if (result == Z_DATA_ERROR) {
  2103. z.msg = "oversubscribed distance tree";
  2104. } else if (result == Z_BUF_ERROR) {
  2105. z.msg = "incomplete distance tree";
  2106. result = Z_DATA_ERROR;
  2107. } else if (result != Z_MEM_ERROR) {
  2108. z.msg = "empty distance tree with lengths";
  2109. result = Z_DATA_ERROR;
  2110. }
  2111. return result;
  2112. }
  2113. return Z_OK;
  2114. };
  2115. }
  2116. InfTree.inflate_trees_fixed = function (bl, // literal desired/actual bit depth
  2117. bd, // distance desired/actual bit depth
  2118. tl,// literal/length tree result
  2119. td// distance tree result
  2120. ) {
  2121. bl[0] = fixed_bl;
  2122. bd[0] = fixed_bd;
  2123. tl[0] = fixed_tl;
  2124. td[0] = fixed_td;
  2125. return Z_OK;
  2126. };
  2127. // InfCodes
  2128. // waiting for "i:"=input,
  2129. // "o:"=output,
  2130. // "x:"=nothing
  2131. const START = 0; // x: set up for LEN
  2132. const LEN = 1; // i: get length/literal/eob next
  2133. const LENEXT = 2; // i: getting length extra (have base)
  2134. const DIST = 3; // i: get distance next
  2135. const DISTEXT = 4;// i: getting distance extra
  2136. const COPY = 5; // o: copying bytes in win, waiting
  2137. // for space
  2138. const LIT = 6; // o: got literal, waiting for output
  2139. // space
  2140. const WASH = 7; // o: got eob, possibly still output
  2141. // waiting
  2142. const END = 8; // x: got eob and all data flushed
  2143. const BADCODE = 9;// x: got error
  2144. function InfCodes() {
  2145. const that = this;
  2146. let mode; // current inflate_codes mode
  2147. // mode dependent information
  2148. let len = 0;
  2149. let tree; // pointer into tree
  2150. let tree_index = 0;
  2151. let need = 0; // bits needed
  2152. let lit = 0;
  2153. // if EXT or COPY, where and how much
  2154. let get = 0; // bits to get for extra
  2155. let dist = 0; // distance back to copy from
  2156. let lbits = 0; // ltree bits decoded per branch
  2157. let dbits = 0; // dtree bits decoder per branch
  2158. let ltree; // literal/length/eob tree
  2159. let ltree_index = 0; // literal/length/eob tree
  2160. let dtree; // distance tree
  2161. let dtree_index = 0; // distance tree
  2162. // Called with number of bytes left to write in win at least 258
  2163. // (the maximum string length) and number of input bytes available
  2164. // at least ten. The ten bytes are six bytes for the longest length/
  2165. // distance pair plus four bytes for overloading the bit buffer.
  2166. function inflate_fast(bl, bd, tl, tl_index, td, td_index, s, z) {
  2167. let t; // temporary pointer
  2168. let tp; // temporary pointer
  2169. let tp_index; // temporary pointer
  2170. let e; // extra bits or operation
  2171. let b; // bit buffer
  2172. let k; // bits in bit buffer
  2173. let p; // input data pointer
  2174. let n; // bytes available there
  2175. let q; // output win write pointer
  2176. let m; // bytes to end of win or read pointer
  2177. let ml; // mask for literal/length tree
  2178. let md; // mask for distance tree
  2179. let c; // bytes to copy
  2180. let d; // distance back to copy from
  2181. let r; // copy source pointer
  2182. let tp_index_t_3; // (tp_index+t)*3
  2183. // load input, output, bit values
  2184. p = z.next_in_index;
  2185. n = z.avail_in;
  2186. b = s.bitb;
  2187. k = s.bitk;
  2188. q = s.write;
  2189. m = q < s.read ? s.read - q - 1 : s.end - q;
  2190. // initialize masks
  2191. ml = inflate_mask[bl];
  2192. md = inflate_mask[bd];
  2193. // do until not enough input or output space for fast loop
  2194. do { // assume called with m >= 258 && n >= 10
  2195. // get literal/length code
  2196. while (k < (20)) { // max bits for literal/length code
  2197. n--;
  2198. b |= (z.read_byte(p++) & 0xff) << k;
  2199. k += 8;
  2200. }
  2201. t = b & ml;
  2202. tp = tl;
  2203. tp_index = tl_index;
  2204. tp_index_t_3 = (tp_index + t) * 3;
  2205. if ((e = tp[tp_index_t_3]) === 0) {
  2206. b >>= (tp[tp_index_t_3 + 1]);
  2207. k -= (tp[tp_index_t_3 + 1]);
  2208. s.win[q++] = /* (byte) */tp[tp_index_t_3 + 2];
  2209. m--;
  2210. continue;
  2211. }
  2212. do {
  2213. b >>= (tp[tp_index_t_3 + 1]);
  2214. k -= (tp[tp_index_t_3 + 1]);
  2215. if ((e & 16) !== 0) {
  2216. e &= 15;
  2217. c = tp[tp_index_t_3 + 2] + (/* (int) */b & inflate_mask[e]);
  2218. b >>= e;
  2219. k -= e;
  2220. // decode distance base of block to copy
  2221. while (k < (15)) { // max bits for distance code
  2222. n--;
  2223. b |= (z.read_byte(p++) & 0xff) << k;
  2224. k += 8;
  2225. }
  2226. t = b & md;
  2227. tp = td;
  2228. tp_index = td_index;
  2229. tp_index_t_3 = (tp_index + t) * 3;
  2230. e = tp[tp_index_t_3];
  2231. do {
  2232. b >>= (tp[tp_index_t_3 + 1]);
  2233. k -= (tp[tp_index_t_3 + 1]);
  2234. if ((e & 16) !== 0) {
  2235. // get extra bits to add to distance base
  2236. e &= 15;
  2237. while (k < (e)) { // get extra bits (up to 13)
  2238. n--;
  2239. b |= (z.read_byte(p++) & 0xff) << k;
  2240. k += 8;
  2241. }
  2242. d = tp[tp_index_t_3 + 2] + (b & inflate_mask[e]);
  2243. b >>= (e);
  2244. k -= (e);
  2245. // do the copy
  2246. m -= c;
  2247. if (q >= d) { // offset before dest
  2248. // just copy
  2249. r = q - d;
  2250. if (q - r > 0 && 2 > (q - r)) {
  2251. s.win[q++] = s.win[r++]; // minimum
  2252. // count is
  2253. // three,
  2254. s.win[q++] = s.win[r++]; // so unroll
  2255. // loop a
  2256. // little
  2257. c -= 2;
  2258. } else {
  2259. s.win.set(s.win.subarray(r, r + 2), q);
  2260. q += 2;
  2261. r += 2;
  2262. c -= 2;
  2263. }
  2264. } else { // else offset after destination
  2265. r = q - d;
  2266. do {
  2267. r += s.end; // force pointer in win
  2268. } while (r < 0); // covers invalid distances
  2269. e = s.end - r;
  2270. if (c > e) { // if source crosses,
  2271. c -= e; // wrapped copy
  2272. if (q - r > 0 && e > (q - r)) {
  2273. do {
  2274. s.win[q++] = s.win[r++];
  2275. } while (--e !== 0);
  2276. } else {
  2277. s.win.set(s.win.subarray(r, r + e), q);
  2278. q += e;
  2279. r += e;
  2280. e = 0;
  2281. }
  2282. r = 0; // copy rest from start of win
  2283. }
  2284. }
  2285. // copy all or what's left
  2286. if (q - r > 0 && c > (q - r)) {
  2287. do {
  2288. s.win[q++] = s.win[r++];
  2289. } while (--c !== 0);
  2290. } else {
  2291. s.win.set(s.win.subarray(r, r + c), q);
  2292. q += c;
  2293. r += c;
  2294. c = 0;
  2295. }
  2296. break;
  2297. } else if ((e & 64) === 0) {
  2298. t += tp[tp_index_t_3 + 2];
  2299. t += (b & inflate_mask[e]);
  2300. tp_index_t_3 = (tp_index + t) * 3;
  2301. e = tp[tp_index_t_3];
  2302. } else {
  2303. z.msg = "invalid distance code";
  2304. c = z.avail_in - n;
  2305. c = (k >> 3) < c ? k >> 3 : c;
  2306. n += c;
  2307. p -= c;
  2308. k -= c << 3;
  2309. s.bitb = b;
  2310. s.bitk = k;
  2311. z.avail_in = n;
  2312. z.total_in += p - z.next_in_index;
  2313. z.next_in_index = p;
  2314. s.write = q;
  2315. return Z_DATA_ERROR;
  2316. }
  2317. // eslint-disable-next-line no-constant-condition
  2318. } while (true);
  2319. break;
  2320. }
  2321. if ((e & 64) === 0) {
  2322. t += tp[tp_index_t_3 + 2];
  2323. t += (b & inflate_mask[e]);
  2324. tp_index_t_3 = (tp_index + t) * 3;
  2325. if ((e = tp[tp_index_t_3]) === 0) {
  2326. b >>= (tp[tp_index_t_3 + 1]);
  2327. k -= (tp[tp_index_t_3 + 1]);
  2328. s.win[q++] = /* (byte) */tp[tp_index_t_3 + 2];
  2329. m--;
  2330. break;
  2331. }
  2332. } else if ((e & 32) !== 0) {
  2333. c = z.avail_in - n;
  2334. c = (k >> 3) < c ? k >> 3 : c;
  2335. n += c;
  2336. p -= c;
  2337. k -= c << 3;
  2338. s.bitb = b;
  2339. s.bitk = k;
  2340. z.avail_in = n;
  2341. z.total_in += p - z.next_in_index;
  2342. z.next_in_index = p;
  2343. s.write = q;
  2344. return Z_STREAM_END;
  2345. } else {
  2346. z.msg = "invalid literal/length code";
  2347. c = z.avail_in - n;
  2348. c = (k >> 3) < c ? k >> 3 : c;
  2349. n += c;
  2350. p -= c;
  2351. k -= c << 3;
  2352. s.bitb = b;
  2353. s.bitk = k;
  2354. z.avail_in = n;
  2355. z.total_in += p - z.next_in_index;
  2356. z.next_in_index = p;
  2357. s.write = q;
  2358. return Z_DATA_ERROR;
  2359. }
  2360. // eslint-disable-next-line no-constant-condition
  2361. } while (true);
  2362. } while (m >= 258 && n >= 10);
  2363. // not enough input or output--restore pointers and return
  2364. c = z.avail_in - n;
  2365. c = (k >> 3) < c ? k >> 3 : c;
  2366. n += c;
  2367. p -= c;
  2368. k -= c << 3;
  2369. s.bitb = b;
  2370. s.bitk = k;
  2371. z.avail_in = n;
  2372. z.total_in += p - z.next_in_index;
  2373. z.next_in_index = p;
  2374. s.write = q;
  2375. return Z_OK;
  2376. }
  2377. that.init = function (bl, bd, tl, tl_index, td, td_index) {
  2378. mode = START;
  2379. lbits = /* (byte) */bl;
  2380. dbits = /* (byte) */bd;
  2381. ltree = tl;
  2382. ltree_index = tl_index;
  2383. dtree = td;
  2384. dtree_index = td_index;
  2385. tree = null;
  2386. };
  2387. that.proc = function (s, z, r) {
  2388. let j; // temporary storage
  2389. let tindex; // temporary pointer
  2390. let e; // extra bits or operation
  2391. let b = 0; // bit buffer
  2392. let k = 0; // bits in bit buffer
  2393. let p = 0; // input data pointer
  2394. let n; // bytes available there
  2395. let q; // output win write pointer
  2396. let m; // bytes to end of win or read pointer
  2397. let f; // pointer to copy strings from
  2398. // copy input/output information to locals (UPDATE macro restores)
  2399. p = z.next_in_index;
  2400. n = z.avail_in;
  2401. b = s.bitb;
  2402. k = s.bitk;
  2403. q = s.write;
  2404. m = q < s.read ? s.read - q - 1 : s.end - q;
  2405. // process input and output based on current state
  2406. // eslint-disable-next-line no-constant-condition
  2407. while (true) {
  2408. switch (mode) {
  2409. // waiting for "i:"=input, "o:"=output, "x:"=nothing
  2410. case START: // x: set up for LEN
  2411. if (m >= 258 && n >= 10) {
  2412. s.bitb = b;
  2413. s.bitk = k;
  2414. z.avail_in = n;
  2415. z.total_in += p - z.next_in_index;
  2416. z.next_in_index = p;
  2417. s.write = q;
  2418. r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, s, z);
  2419. p = z.next_in_index;
  2420. n = z.avail_in;
  2421. b = s.bitb;
  2422. k = s.bitk;
  2423. q = s.write;
  2424. m = q < s.read ? s.read - q - 1 : s.end - q;
  2425. if (r != Z_OK) {
  2426. mode = r == Z_STREAM_END ? WASH : BADCODE;
  2427. break;
  2428. }
  2429. }
  2430. need = lbits;
  2431. tree = ltree;
  2432. tree_index = ltree_index;
  2433. mode = LEN;
  2434. /* falls through */
  2435. case LEN: // i: get length/literal/eob next
  2436. j = need;
  2437. while (k < (j)) {
  2438. if (n !== 0)
  2439. r = Z_OK;
  2440. else {
  2441. s.bitb = b;
  2442. s.bitk = k;
  2443. z.avail_in = n;
  2444. z.total_in += p - z.next_in_index;
  2445. z.next_in_index = p;
  2446. s.write = q;
  2447. return s.inflate_flush(z, r);
  2448. }
  2449. n--;
  2450. b |= (z.read_byte(p++) & 0xff) << k;
  2451. k += 8;
  2452. }
  2453. tindex = (tree_index + (b & inflate_mask[j])) * 3;
  2454. b >>>= (tree[tindex + 1]);
  2455. k -= (tree[tindex + 1]);
  2456. e = tree[tindex];
  2457. if (e === 0) { // literal
  2458. lit = tree[tindex + 2];
  2459. mode = LIT;
  2460. break;
  2461. }
  2462. if ((e & 16) !== 0) { // length
  2463. get = e & 15;
  2464. len = tree[tindex + 2];
  2465. mode = LENEXT;
  2466. break;
  2467. }
  2468. if ((e & 64) === 0) { // next table
  2469. need = e;
  2470. tree_index = tindex / 3 + tree[tindex + 2];
  2471. break;
  2472. }
  2473. if ((e & 32) !== 0) { // end of block
  2474. mode = WASH;
  2475. break;
  2476. }
  2477. mode = BADCODE; // invalid code
  2478. z.msg = "invalid literal/length code";
  2479. r = Z_DATA_ERROR;
  2480. s.bitb = b;
  2481. s.bitk = k;
  2482. z.avail_in = n;
  2483. z.total_in += p - z.next_in_index;
  2484. z.next_in_index = p;
  2485. s.write = q;
  2486. return s.inflate_flush(z, r);
  2487. case LENEXT: // i: getting length extra (have base)
  2488. j = get;
  2489. while (k < (j)) {
  2490. if (n !== 0)
  2491. r = Z_OK;
  2492. else {
  2493. s.bitb = b;
  2494. s.bitk = k;
  2495. z.avail_in = n;
  2496. z.total_in += p - z.next_in_index;
  2497. z.next_in_index = p;
  2498. s.write = q;
  2499. return s.inflate_flush(z, r);
  2500. }
  2501. n--;
  2502. b |= (z.read_byte(p++) & 0xff) << k;
  2503. k += 8;
  2504. }
  2505. len += (b & inflate_mask[j]);
  2506. b >>= j;
  2507. k -= j;
  2508. need = dbits;
  2509. tree = dtree;
  2510. tree_index = dtree_index;
  2511. mode = DIST;
  2512. /* falls through */
  2513. case DIST: // i: get distance next
  2514. j = need;
  2515. while (k < (j)) {
  2516. if (n !== 0)
  2517. r = Z_OK;
  2518. else {
  2519. s.bitb = b;
  2520. s.bitk = k;
  2521. z.avail_in = n;
  2522. z.total_in += p - z.next_in_index;
  2523. z.next_in_index = p;
  2524. s.write = q;
  2525. return s.inflate_flush(z, r);
  2526. }
  2527. n--;
  2528. b |= (z.read_byte(p++) & 0xff) << k;
  2529. k += 8;
  2530. }
  2531. tindex = (tree_index + (b & inflate_mask[j])) * 3;
  2532. b >>= tree[tindex + 1];
  2533. k -= tree[tindex + 1];
  2534. e = (tree[tindex]);
  2535. if ((e & 16) !== 0) { // distance
  2536. get = e & 15;
  2537. dist = tree[tindex + 2];
  2538. mode = DISTEXT;
  2539. break;
  2540. }
  2541. if ((e & 64) === 0) { // next table
  2542. need = e;
  2543. tree_index = tindex / 3 + tree[tindex + 2];
  2544. break;
  2545. }
  2546. mode = BADCODE; // invalid code
  2547. z.msg = "invalid distance code";
  2548. r = Z_DATA_ERROR;
  2549. s.bitb = b;
  2550. s.bitk = k;
  2551. z.avail_in = n;
  2552. z.total_in += p - z.next_in_index;
  2553. z.next_in_index = p;
  2554. s.write = q;
  2555. return s.inflate_flush(z, r);
  2556. case DISTEXT: // i: getting distance extra
  2557. j = get;
  2558. while (k < (j)) {
  2559. if (n !== 0)
  2560. r = Z_OK;
  2561. else {
  2562. s.bitb = b;
  2563. s.bitk = k;
  2564. z.avail_in = n;
  2565. z.total_in += p - z.next_in_index;
  2566. z.next_in_index = p;
  2567. s.write = q;
  2568. return s.inflate_flush(z, r);
  2569. }
  2570. n--;
  2571. b |= (z.read_byte(p++) & 0xff) << k;
  2572. k += 8;
  2573. }
  2574. dist += (b & inflate_mask[j]);
  2575. b >>= j;
  2576. k -= j;
  2577. mode = COPY;
  2578. /* falls through */
  2579. case COPY: // o: copying bytes in win, waiting for space
  2580. f = q - dist;
  2581. while (f < 0) { // modulo win size-"while" instead
  2582. f += s.end; // of "if" handles invalid distances
  2583. }
  2584. while (len !== 0) {
  2585. if (m === 0) {
  2586. if (q == s.end && s.read !== 0) {
  2587. q = 0;
  2588. m = q < s.read ? s.read - q - 1 : s.end - q;
  2589. }
  2590. if (m === 0) {
  2591. s.write = q;
  2592. r = s.inflate_flush(z, r);
  2593. q = s.write;
  2594. m = q < s.read ? s.read - q - 1 : s.end - q;
  2595. if (q == s.end && s.read !== 0) {
  2596. q = 0;
  2597. m = q < s.read ? s.read - q - 1 : s.end - q;
  2598. }
  2599. if (m === 0) {
  2600. s.bitb = b;
  2601. s.bitk = k;
  2602. z.avail_in = n;
  2603. z.total_in += p - z.next_in_index;
  2604. z.next_in_index = p;
  2605. s.write = q;
  2606. return s.inflate_flush(z, r);
  2607. }
  2608. }
  2609. }
  2610. s.win[q++] = s.win[f++];
  2611. m--;
  2612. if (f == s.end)
  2613. f = 0;
  2614. len--;
  2615. }
  2616. mode = START;
  2617. break;
  2618. case LIT: // o: got literal, waiting for output space
  2619. if (m === 0) {
  2620. if (q == s.end && s.read !== 0) {
  2621. q = 0;
  2622. m = q < s.read ? s.read - q - 1 : s.end - q;
  2623. }
  2624. if (m === 0) {
  2625. s.write = q;
  2626. r = s.inflate_flush(z, r);
  2627. q = s.write;
  2628. m = q < s.read ? s.read - q - 1 : s.end - q;
  2629. if (q == s.end && s.read !== 0) {
  2630. q = 0;
  2631. m = q < s.read ? s.read - q - 1 : s.end - q;
  2632. }
  2633. if (m === 0) {
  2634. s.bitb = b;
  2635. s.bitk = k;
  2636. z.avail_in = n;
  2637. z.total_in += p - z.next_in_index;
  2638. z.next_in_index = p;
  2639. s.write = q;
  2640. return s.inflate_flush(z, r);
  2641. }
  2642. }
  2643. }
  2644. r = Z_OK;
  2645. s.win[q++] = /* (byte) */lit;
  2646. m--;
  2647. mode = START;
  2648. break;
  2649. case WASH: // o: got eob, possibly more output
  2650. if (k > 7) { // return unused byte, if any
  2651. k -= 8;
  2652. n++;
  2653. p--; // can always return one
  2654. }
  2655. s.write = q;
  2656. r = s.inflate_flush(z, r);
  2657. q = s.write;
  2658. m = q < s.read ? s.read - q - 1 : s.end - q;
  2659. if (s.read != s.write) {
  2660. s.bitb = b;
  2661. s.bitk = k;
  2662. z.avail_in = n;
  2663. z.total_in += p - z.next_in_index;
  2664. z.next_in_index = p;
  2665. s.write = q;
  2666. return s.inflate_flush(z, r);
  2667. }
  2668. mode = END;
  2669. /* falls through */
  2670. case END:
  2671. r = Z_STREAM_END;
  2672. s.bitb = b;
  2673. s.bitk = k;
  2674. z.avail_in = n;
  2675. z.total_in += p - z.next_in_index;
  2676. z.next_in_index = p;
  2677. s.write = q;
  2678. return s.inflate_flush(z, r);
  2679. case BADCODE: // x: got error
  2680. r = Z_DATA_ERROR;
  2681. s.bitb = b;
  2682. s.bitk = k;
  2683. z.avail_in = n;
  2684. z.total_in += p - z.next_in_index;
  2685. z.next_in_index = p;
  2686. s.write = q;
  2687. return s.inflate_flush(z, r);
  2688. default:
  2689. r = Z_STREAM_ERROR;
  2690. s.bitb = b;
  2691. s.bitk = k;
  2692. z.avail_in = n;
  2693. z.total_in += p - z.next_in_index;
  2694. z.next_in_index = p;
  2695. s.write = q;
  2696. return s.inflate_flush(z, r);
  2697. }
  2698. }
  2699. };
  2700. that.free = function () {
  2701. // ZFREE(z, c);
  2702. };
  2703. }
  2704. // InfBlocks
  2705. // Table for deflate from PKZIP's appnote.txt.
  2706. const border = [ // Order of the bit length code lengths
  2707. 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  2708. const TYPE = 0; // get type bits (3, including end bit)
  2709. const LENS = 1; // get lengths for stored
  2710. const STORED = 2;// processing stored block
  2711. const TABLE = 3; // get table lengths
  2712. const BTREE = 4; // get bit lengths tree for a dynamic
  2713. // block
  2714. const DTREE = 5; // get length, distance trees for a
  2715. // dynamic block
  2716. const CODES = 6; // processing fixed or dynamic block
  2717. const DRY = 7; // output remaining win bytes
  2718. const DONELOCKS = 8; // finished last block, done
  2719. const BADBLOCKS = 9; // ot a data error--stuck here
  2720. function InfBlocks(z, w) {
  2721. const that = this;
  2722. let mode = TYPE; // current inflate_block mode
  2723. let left = 0; // if STORED, bytes left to copy
  2724. let table = 0; // table lengths (14 bits)
  2725. let index = 0; // index into blens (or border)
  2726. let blens; // bit lengths of codes
  2727. const bb = [0]; // bit length tree depth
  2728. const tb = [0]; // bit length decoding tree
  2729. const codes = new InfCodes(); // if CODES, current state
  2730. let last = 0; // true if this block is the last block
  2731. let hufts = new Int32Array(MANY * 3); // single malloc for tree space
  2732. const check = 0; // check on output
  2733. const inftree = new InfTree();
  2734. that.bitk = 0; // bits in bit buffer
  2735. that.bitb = 0; // bit buffer
  2736. that.win = new Uint8Array(w); // sliding win
  2737. that.end = w; // one byte after sliding win
  2738. that.read = 0; // win read pointer
  2739. that.write = 0; // win write pointer
  2740. that.reset = function (z, c) {
  2741. if (c)
  2742. c[0] = check;
  2743. // if (mode == BTREE || mode == DTREE) {
  2744. // }
  2745. if (mode == CODES) {
  2746. codes.free(z);
  2747. }
  2748. mode = TYPE;
  2749. that.bitk = 0;
  2750. that.bitb = 0;
  2751. that.read = that.write = 0;
  2752. };
  2753. that.reset(z, null);
  2754. // copy as much as possible from the sliding win to the output area
  2755. that.inflate_flush = function (z, r) {
  2756. let n;
  2757. let p;
  2758. let q;
  2759. // local copies of source and destination pointers
  2760. p = z.next_out_index;
  2761. q = that.read;
  2762. // compute number of bytes to copy as far as end of win
  2763. n = /* (int) */((q <= that.write ? that.write : that.end) - q);
  2764. if (n > z.avail_out)
  2765. n = z.avail_out;
  2766. if (n !== 0 && r == Z_BUF_ERROR)
  2767. r = Z_OK;
  2768. // update counters
  2769. z.avail_out -= n;
  2770. z.total_out += n;
  2771. // copy as far as end of win
  2772. z.next_out.set(that.win.subarray(q, q + n), p);
  2773. p += n;
  2774. q += n;
  2775. // see if more to copy at beginning of win
  2776. if (q == that.end) {
  2777. // wrap pointers
  2778. q = 0;
  2779. if (that.write == that.end)
  2780. that.write = 0;
  2781. // compute bytes to copy
  2782. n = that.write - q;
  2783. if (n > z.avail_out)
  2784. n = z.avail_out;
  2785. if (n !== 0 && r == Z_BUF_ERROR)
  2786. r = Z_OK;
  2787. // update counters
  2788. z.avail_out -= n;
  2789. z.total_out += n;
  2790. // copy
  2791. z.next_out.set(that.win.subarray(q, q + n), p);
  2792. p += n;
  2793. q += n;
  2794. }
  2795. // update pointers
  2796. z.next_out_index = p;
  2797. that.read = q;
  2798. // done
  2799. return r;
  2800. };
  2801. that.proc = function (z, r) {
  2802. let t; // temporary storage
  2803. let b; // bit buffer
  2804. let k; // bits in bit buffer
  2805. let p; // input data pointer
  2806. let n; // bytes available there
  2807. let q; // output win write pointer
  2808. let m; // bytes to end of win or read pointer
  2809. let i;
  2810. // copy input/output information to locals (UPDATE macro restores)
  2811. // {
  2812. p = z.next_in_index;
  2813. n = z.avail_in;
  2814. b = that.bitb;
  2815. k = that.bitk;
  2816. // }
  2817. // {
  2818. q = that.write;
  2819. m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  2820. // }
  2821. // process input based on current state
  2822. // DEBUG dtree
  2823. // eslint-disable-next-line no-constant-condition
  2824. while (true) {
  2825. let bl, bd, tl, td, bl_, bd_, tl_, td_;
  2826. switch (mode) {
  2827. case TYPE:
  2828. while (k < (3)) {
  2829. if (n !== 0) {
  2830. r = Z_OK;
  2831. } else {
  2832. that.bitb = b;
  2833. that.bitk = k;
  2834. z.avail_in = n;
  2835. z.total_in += p - z.next_in_index;
  2836. z.next_in_index = p;
  2837. that.write = q;
  2838. return that.inflate_flush(z, r);
  2839. }
  2840. n--;
  2841. b |= (z.read_byte(p++) & 0xff) << k;
  2842. k += 8;
  2843. }
  2844. t = /* (int) */(b & 7);
  2845. last = t & 1;
  2846. switch (t >>> 1) {
  2847. case 0: // stored
  2848. // {
  2849. b >>>= (3);
  2850. k -= (3);
  2851. // }
  2852. t = k & 7; // go to byte boundary
  2853. // {
  2854. b >>>= (t);
  2855. k -= (t);
  2856. // }
  2857. mode = LENS; // get length of stored block
  2858. break;
  2859. case 1: // fixed
  2860. // {
  2861. bl = []; // new Array(1);
  2862. bd = []; // new Array(1);
  2863. tl = [[]]; // new Array(1);
  2864. td = [[]]; // new Array(1);
  2865. InfTree.inflate_trees_fixed(bl, bd, tl, td);
  2866. codes.init(bl[0], bd[0], tl[0], 0, td[0], 0);
  2867. // }
  2868. // {
  2869. b >>>= (3);
  2870. k -= (3);
  2871. // }
  2872. mode = CODES;
  2873. break;
  2874. case 2: // dynamic
  2875. // {
  2876. b >>>= (3);
  2877. k -= (3);
  2878. // }
  2879. mode = TABLE;
  2880. break;
  2881. case 3: // illegal
  2882. // {
  2883. b >>>= (3);
  2884. k -= (3);
  2885. // }
  2886. mode = BADBLOCKS;
  2887. z.msg = "invalid block type";
  2888. r = Z_DATA_ERROR;
  2889. that.bitb = b;
  2890. that.bitk = k;
  2891. z.avail_in = n;
  2892. z.total_in += p - z.next_in_index;
  2893. z.next_in_index = p;
  2894. that.write = q;
  2895. return that.inflate_flush(z, r);
  2896. }
  2897. break;
  2898. case LENS:
  2899. while (k < (32)) {
  2900. if (n !== 0) {
  2901. r = Z_OK;
  2902. } else {
  2903. that.bitb = b;
  2904. that.bitk = k;
  2905. z.avail_in = n;
  2906. z.total_in += p - z.next_in_index;
  2907. z.next_in_index = p;
  2908. that.write = q;
  2909. return that.inflate_flush(z, r);
  2910. }
  2911. n--;
  2912. b |= (z.read_byte(p++) & 0xff) << k;
  2913. k += 8;
  2914. }
  2915. if ((((~b) >>> 16) & 0xffff) != (b & 0xffff)) {
  2916. mode = BADBLOCKS;
  2917. z.msg = "invalid stored block lengths";
  2918. r = Z_DATA_ERROR;
  2919. that.bitb = b;
  2920. that.bitk = k;
  2921. z.avail_in = n;
  2922. z.total_in += p - z.next_in_index;
  2923. z.next_in_index = p;
  2924. that.write = q;
  2925. return that.inflate_flush(z, r);
  2926. }
  2927. left = (b & 0xffff);
  2928. b = k = 0; // dump bits
  2929. mode = left !== 0 ? STORED : (last !== 0 ? DRY : TYPE);
  2930. break;
  2931. case STORED:
  2932. if (n === 0) {
  2933. that.bitb = b;
  2934. that.bitk = k;
  2935. z.avail_in = n;
  2936. z.total_in += p - z.next_in_index;
  2937. z.next_in_index = p;
  2938. that.write = q;
  2939. return that.inflate_flush(z, r);
  2940. }
  2941. if (m === 0) {
  2942. if (q == that.end && that.read !== 0) {
  2943. q = 0;
  2944. m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  2945. }
  2946. if (m === 0) {
  2947. that.write = q;
  2948. r = that.inflate_flush(z, r);
  2949. q = that.write;
  2950. m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  2951. if (q == that.end && that.read !== 0) {
  2952. q = 0;
  2953. m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  2954. }
  2955. if (m === 0) {
  2956. that.bitb = b;
  2957. that.bitk = k;
  2958. z.avail_in = n;
  2959. z.total_in += p - z.next_in_index;
  2960. z.next_in_index = p;
  2961. that.write = q;
  2962. return that.inflate_flush(z, r);
  2963. }
  2964. }
  2965. }
  2966. r = Z_OK;
  2967. t = left;
  2968. if (t > n)
  2969. t = n;
  2970. if (t > m)
  2971. t = m;
  2972. that.win.set(z.read_buf(p, t), q);
  2973. p += t;
  2974. n -= t;
  2975. q += t;
  2976. m -= t;
  2977. if ((left -= t) !== 0)
  2978. break;
  2979. mode = last !== 0 ? DRY : TYPE;
  2980. break;
  2981. case TABLE:
  2982. while (k < (14)) {
  2983. if (n !== 0) {
  2984. r = Z_OK;
  2985. } else {
  2986. that.bitb = b;
  2987. that.bitk = k;
  2988. z.avail_in = n;
  2989. z.total_in += p - z.next_in_index;
  2990. z.next_in_index = p;
  2991. that.write = q;
  2992. return that.inflate_flush(z, r);
  2993. }
  2994. n--;
  2995. b |= (z.read_byte(p++) & 0xff) << k;
  2996. k += 8;
  2997. }
  2998. table = t = (b & 0x3fff);
  2999. if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) {
  3000. mode = BADBLOCKS;
  3001. z.msg = "too many length or distance symbols";
  3002. r = Z_DATA_ERROR;
  3003. that.bitb = b;
  3004. that.bitk = k;
  3005. z.avail_in = n;
  3006. z.total_in += p - z.next_in_index;
  3007. z.next_in_index = p;
  3008. that.write = q;
  3009. return that.inflate_flush(z, r);
  3010. }
  3011. t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
  3012. if (!blens || blens.length < t) {
  3013. blens = []; // new Array(t);
  3014. } else {
  3015. for (i = 0; i < t; i++) {
  3016. blens[i] = 0;
  3017. }
  3018. }
  3019. // {
  3020. b >>>= (14);
  3021. k -= (14);
  3022. // }
  3023. index = 0;
  3024. mode = BTREE;
  3025. /* falls through */
  3026. case BTREE:
  3027. while (index < 4 + (table >>> 10)) {
  3028. while (k < (3)) {
  3029. if (n !== 0) {
  3030. r = Z_OK;
  3031. } else {
  3032. that.bitb = b;
  3033. that.bitk = k;
  3034. z.avail_in = n;
  3035. z.total_in += p - z.next_in_index;
  3036. z.next_in_index = p;
  3037. that.write = q;
  3038. return that.inflate_flush(z, r);
  3039. }
  3040. n--;
  3041. b |= (z.read_byte(p++) & 0xff) << k;
  3042. k += 8;
  3043. }
  3044. blens[border[index++]] = b & 7;
  3045. // {
  3046. b >>>= (3);
  3047. k -= (3);
  3048. // }
  3049. }
  3050. while (index < 19) {
  3051. blens[border[index++]] = 0;
  3052. }
  3053. bb[0] = 7;
  3054. t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z);
  3055. if (t != Z_OK) {
  3056. r = t;
  3057. if (r == Z_DATA_ERROR) {
  3058. blens = null;
  3059. mode = BADBLOCKS;
  3060. }
  3061. that.bitb = b;
  3062. that.bitk = k;
  3063. z.avail_in = n;
  3064. z.total_in += p - z.next_in_index;
  3065. z.next_in_index = p;
  3066. that.write = q;
  3067. return that.inflate_flush(z, r);
  3068. }
  3069. index = 0;
  3070. mode = DTREE;
  3071. /* falls through */
  3072. case DTREE:
  3073. // eslint-disable-next-line no-constant-condition
  3074. while (true) {
  3075. t = table;
  3076. if (index >= 258 + (t & 0x1f) + ((t >> 5) & 0x1f)) {
  3077. break;
  3078. }
  3079. let j, c;
  3080. t = bb[0];
  3081. while (k < (t)) {
  3082. if (n !== 0) {
  3083. r = Z_OK;
  3084. } else {
  3085. that.bitb = b;
  3086. that.bitk = k;
  3087. z.avail_in = n;
  3088. z.total_in += p - z.next_in_index;
  3089. z.next_in_index = p;
  3090. that.write = q;
  3091. return that.inflate_flush(z, r);
  3092. }
  3093. n--;
  3094. b |= (z.read_byte(p++) & 0xff) << k;
  3095. k += 8;
  3096. }
  3097. // if (tb[0] == -1) {
  3098. // System.err.println("null...");
  3099. // }
  3100. t = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 1];
  3101. c = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 2];
  3102. if (c < 16) {
  3103. b >>>= (t);
  3104. k -= (t);
  3105. blens[index++] = c;
  3106. } else { // c == 16..18
  3107. i = c == 18 ? 7 : c - 14;
  3108. j = c == 18 ? 11 : 3;
  3109. while (k < (t + i)) {
  3110. if (n !== 0) {
  3111. r = Z_OK;
  3112. } else {
  3113. that.bitb = b;
  3114. that.bitk = k;
  3115. z.avail_in = n;
  3116. z.total_in += p - z.next_in_index;
  3117. z.next_in_index = p;
  3118. that.write = q;
  3119. return that.inflate_flush(z, r);
  3120. }
  3121. n--;
  3122. b |= (z.read_byte(p++) & 0xff) << k;
  3123. k += 8;
  3124. }
  3125. b >>>= (t);
  3126. k -= (t);
  3127. j += (b & inflate_mask[i]);
  3128. b >>>= (i);
  3129. k -= (i);
  3130. i = index;
  3131. t = table;
  3132. if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) {
  3133. blens = null;
  3134. mode = BADBLOCKS;
  3135. z.msg = "invalid bit length repeat";
  3136. r = Z_DATA_ERROR;
  3137. that.bitb = b;
  3138. that.bitk = k;
  3139. z.avail_in = n;
  3140. z.total_in += p - z.next_in_index;
  3141. z.next_in_index = p;
  3142. that.write = q;
  3143. return that.inflate_flush(z, r);
  3144. }
  3145. c = c == 16 ? blens[i - 1] : 0;
  3146. do {
  3147. blens[i++] = c;
  3148. } while (--j !== 0);
  3149. index = i;
  3150. }
  3151. }
  3152. tb[0] = -1;
  3153. // {
  3154. bl_ = []; // new Array(1);
  3155. bd_ = []; // new Array(1);
  3156. tl_ = []; // new Array(1);
  3157. td_ = []; // new Array(1);
  3158. bl_[0] = 9; // must be <= 9 for lookahead assumptions
  3159. bd_[0] = 6; // must be <= 9 for lookahead assumptions
  3160. t = table;
  3161. t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl_, bd_, tl_, td_, hufts, z);
  3162. if (t != Z_OK) {
  3163. if (t == Z_DATA_ERROR) {
  3164. blens = null;
  3165. mode = BADBLOCKS;
  3166. }
  3167. r = t;
  3168. that.bitb = b;
  3169. that.bitk = k;
  3170. z.avail_in = n;
  3171. z.total_in += p - z.next_in_index;
  3172. z.next_in_index = p;
  3173. that.write = q;
  3174. return that.inflate_flush(z, r);
  3175. }
  3176. codes.init(bl_[0], bd_[0], hufts, tl_[0], hufts, td_[0]);
  3177. // }
  3178. mode = CODES;
  3179. /* falls through */
  3180. case CODES:
  3181. that.bitb = b;
  3182. that.bitk = k;
  3183. z.avail_in = n;
  3184. z.total_in += p - z.next_in_index;
  3185. z.next_in_index = p;
  3186. that.write = q;
  3187. if ((r = codes.proc(that, z, r)) != Z_STREAM_END) {
  3188. return that.inflate_flush(z, r);
  3189. }
  3190. r = Z_OK;
  3191. codes.free(z);
  3192. p = z.next_in_index;
  3193. n = z.avail_in;
  3194. b = that.bitb;
  3195. k = that.bitk;
  3196. q = that.write;
  3197. m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  3198. if (last === 0) {
  3199. mode = TYPE;
  3200. break;
  3201. }
  3202. mode = DRY;
  3203. /* falls through */
  3204. case DRY:
  3205. that.write = q;
  3206. r = that.inflate_flush(z, r);
  3207. q = that.write;
  3208. m = /* (int) */(q < that.read ? that.read - q - 1 : that.end - q);
  3209. if (that.read != that.write) {
  3210. that.bitb = b;
  3211. that.bitk = k;
  3212. z.avail_in = n;
  3213. z.total_in += p - z.next_in_index;
  3214. z.next_in_index = p;
  3215. that.write = q;
  3216. return that.inflate_flush(z, r);
  3217. }
  3218. mode = DONELOCKS;
  3219. /* falls through */
  3220. case DONELOCKS:
  3221. r = Z_STREAM_END;
  3222. that.bitb = b;
  3223. that.bitk = k;
  3224. z.avail_in = n;
  3225. z.total_in += p - z.next_in_index;
  3226. z.next_in_index = p;
  3227. that.write = q;
  3228. return that.inflate_flush(z, r);
  3229. case BADBLOCKS:
  3230. r = Z_DATA_ERROR;
  3231. that.bitb = b;
  3232. that.bitk = k;
  3233. z.avail_in = n;
  3234. z.total_in += p - z.next_in_index;
  3235. z.next_in_index = p;
  3236. that.write = q;
  3237. return that.inflate_flush(z, r);
  3238. default:
  3239. r = Z_STREAM_ERROR;
  3240. that.bitb = b;
  3241. that.bitk = k;
  3242. z.avail_in = n;
  3243. z.total_in += p - z.next_in_index;
  3244. z.next_in_index = p;
  3245. that.write = q;
  3246. return that.inflate_flush(z, r);
  3247. }
  3248. }
  3249. };
  3250. that.free = function (z) {
  3251. that.reset(z, null);
  3252. that.win = null;
  3253. hufts = null;
  3254. // ZFREE(z, s);
  3255. };
  3256. that.set_dictionary = function (d, start, n) {
  3257. that.win.set(d.subarray(start, start + n), 0);
  3258. that.read = that.write = n;
  3259. };
  3260. // Returns true if inflate is currently at the end of a block generated
  3261. // by Z_SYNC_FLUSH or Z_FULL_FLUSH.
  3262. that.sync_point = function () {
  3263. return mode == LENS ? 1 : 0;
  3264. };
  3265. }
  3266. // Inflate
  3267. // preset dictionary flag in zlib header
  3268. const PRESET_DICT = 0x20;
  3269. const Z_DEFLATED = 8;
  3270. const METHOD = 0; // waiting for method byte
  3271. const FLAG = 1; // waiting for flag byte
  3272. const DICT4 = 2; // four dictionary check bytes to go
  3273. const DICT3 = 3; // three dictionary check bytes to go
  3274. const DICT2 = 4; // two dictionary check bytes to go
  3275. const DICT1 = 5; // one dictionary check byte to go
  3276. const DICT0 = 6; // waiting for inflateSetDictionary
  3277. const BLOCKS = 7; // decompressing blocks
  3278. const DONE = 12; // finished check, done
  3279. const BAD = 13; // got an error--stay here
  3280. const mark = [0, 0, 0xff, 0xff];
  3281. function Inflate$1() {
  3282. const that = this;
  3283. that.mode = 0; // current inflate mode
  3284. // mode dependent information
  3285. that.method = 0; // if FLAGS, method byte
  3286. // if CHECK, check values to compare
  3287. that.was = [0]; // new Array(1); // computed check value
  3288. that.need = 0; // stream check value
  3289. // if BAD, inflateSync's marker bytes count
  3290. that.marker = 0;
  3291. // mode independent information
  3292. that.wbits = 0; // log2(win size) (8..15, defaults to 15)
  3293. // this.blocks; // current inflate_blocks state
  3294. function inflateReset(z) {
  3295. if (!z || !z.istate)
  3296. return Z_STREAM_ERROR;
  3297. z.total_in = z.total_out = 0;
  3298. z.msg = null;
  3299. z.istate.mode = BLOCKS;
  3300. z.istate.blocks.reset(z, null);
  3301. return Z_OK;
  3302. }
  3303. that.inflateEnd = function (z) {
  3304. if (that.blocks)
  3305. that.blocks.free(z);
  3306. that.blocks = null;
  3307. // ZFREE(z, z->state);
  3308. return Z_OK;
  3309. };
  3310. that.inflateInit = function (z, w) {
  3311. z.msg = null;
  3312. that.blocks = null;
  3313. // set win size
  3314. if (w < 8 || w > 15) {
  3315. that.inflateEnd(z);
  3316. return Z_STREAM_ERROR;
  3317. }
  3318. that.wbits = w;
  3319. z.istate.blocks = new InfBlocks(z, 1 << w);
  3320. // reset state
  3321. inflateReset(z);
  3322. return Z_OK;
  3323. };
  3324. that.inflate = function (z, f) {
  3325. let r;
  3326. let b;
  3327. if (!z || !z.istate || !z.next_in)
  3328. return Z_STREAM_ERROR;
  3329. const istate = z.istate;
  3330. f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
  3331. r = Z_BUF_ERROR;
  3332. // eslint-disable-next-line no-constant-condition
  3333. while (true) {
  3334. switch (istate.mode) {
  3335. case METHOD:
  3336. if (z.avail_in === 0)
  3337. return r;
  3338. r = f;
  3339. z.avail_in--;
  3340. z.total_in++;
  3341. if (((istate.method = z.read_byte(z.next_in_index++)) & 0xf) != Z_DEFLATED) {
  3342. istate.mode = BAD;
  3343. z.msg = "unknown compression method";
  3344. istate.marker = 5; // can't try inflateSync
  3345. break;
  3346. }
  3347. if ((istate.method >> 4) + 8 > istate.wbits) {
  3348. istate.mode = BAD;
  3349. z.msg = "invalid win size";
  3350. istate.marker = 5; // can't try inflateSync
  3351. break;
  3352. }
  3353. istate.mode = FLAG;
  3354. /* falls through */
  3355. case FLAG:
  3356. if (z.avail_in === 0)
  3357. return r;
  3358. r = f;
  3359. z.avail_in--;
  3360. z.total_in++;
  3361. b = (z.read_byte(z.next_in_index++)) & 0xff;
  3362. if ((((istate.method << 8) + b) % 31) !== 0) {
  3363. istate.mode = BAD;
  3364. z.msg = "incorrect header check";
  3365. istate.marker = 5; // can't try inflateSync
  3366. break;
  3367. }
  3368. if ((b & PRESET_DICT) === 0) {
  3369. istate.mode = BLOCKS;
  3370. break;
  3371. }
  3372. istate.mode = DICT4;
  3373. /* falls through */
  3374. case DICT4:
  3375. if (z.avail_in === 0)
  3376. return r;
  3377. r = f;
  3378. z.avail_in--;
  3379. z.total_in++;
  3380. istate.need = ((z.read_byte(z.next_in_index++) & 0xff) << 24) & 0xff000000;
  3381. istate.mode = DICT3;
  3382. /* falls through */
  3383. case DICT3:
  3384. if (z.avail_in === 0)
  3385. return r;
  3386. r = f;
  3387. z.avail_in--;
  3388. z.total_in++;
  3389. istate.need += ((z.read_byte(z.next_in_index++) & 0xff) << 16) & 0xff0000;
  3390. istate.mode = DICT2;
  3391. /* falls through */
  3392. case DICT2:
  3393. if (z.avail_in === 0)
  3394. return r;
  3395. r = f;
  3396. z.avail_in--;
  3397. z.total_in++;
  3398. istate.need += ((z.read_byte(z.next_in_index++) & 0xff) << 8) & 0xff00;
  3399. istate.mode = DICT1;
  3400. /* falls through */
  3401. case DICT1:
  3402. if (z.avail_in === 0)
  3403. return r;
  3404. r = f;
  3405. z.avail_in--;
  3406. z.total_in++;
  3407. istate.need += (z.read_byte(z.next_in_index++) & 0xff);
  3408. istate.mode = DICT0;
  3409. return Z_NEED_DICT;
  3410. case DICT0:
  3411. istate.mode = BAD;
  3412. z.msg = "need dictionary";
  3413. istate.marker = 0; // can try inflateSync
  3414. return Z_STREAM_ERROR;
  3415. case BLOCKS:
  3416. r = istate.blocks.proc(z, r);
  3417. if (r == Z_DATA_ERROR) {
  3418. istate.mode = BAD;
  3419. istate.marker = 0; // can try inflateSync
  3420. break;
  3421. }
  3422. if (r == Z_OK) {
  3423. r = f;
  3424. }
  3425. if (r != Z_STREAM_END) {
  3426. return r;
  3427. }
  3428. r = f;
  3429. istate.blocks.reset(z, istate.was);
  3430. istate.mode = DONE;
  3431. /* falls through */
  3432. case DONE:
  3433. z.avail_in = 0;
  3434. return Z_STREAM_END;
  3435. case BAD:
  3436. return Z_DATA_ERROR;
  3437. default:
  3438. return Z_STREAM_ERROR;
  3439. }
  3440. }
  3441. };
  3442. that.inflateSetDictionary = function (z, dictionary, dictLength) {
  3443. let index = 0, length = dictLength;
  3444. if (!z || !z.istate || z.istate.mode != DICT0)
  3445. return Z_STREAM_ERROR;
  3446. const istate = z.istate;
  3447. if (length >= (1 << istate.wbits)) {
  3448. length = (1 << istate.wbits) - 1;
  3449. index = dictLength - length;
  3450. }
  3451. istate.blocks.set_dictionary(dictionary, index, length);
  3452. istate.mode = BLOCKS;
  3453. return Z_OK;
  3454. };
  3455. that.inflateSync = function (z) {
  3456. let n; // number of bytes to look at
  3457. let p; // pointer to bytes
  3458. let m; // number of marker bytes found in a row
  3459. let r, w; // temporaries to save total_in and total_out
  3460. // set up
  3461. if (!z || !z.istate)
  3462. return Z_STREAM_ERROR;
  3463. const istate = z.istate;
  3464. if (istate.mode != BAD) {
  3465. istate.mode = BAD;
  3466. istate.marker = 0;
  3467. }
  3468. if ((n = z.avail_in) === 0)
  3469. return Z_BUF_ERROR;
  3470. p = z.next_in_index;
  3471. m = istate.marker;
  3472. // search
  3473. while (n !== 0 && m < 4) {
  3474. if (z.read_byte(p) == mark[m]) {
  3475. m++;
  3476. } else if (z.read_byte(p) !== 0) {
  3477. m = 0;
  3478. } else {
  3479. m = 4 - m;
  3480. }
  3481. p++;
  3482. n--;
  3483. }
  3484. // restore
  3485. z.total_in += p - z.next_in_index;
  3486. z.next_in_index = p;
  3487. z.avail_in = n;
  3488. istate.marker = m;
  3489. // return no joy or set up to restart on a new block
  3490. if (m != 4) {
  3491. return Z_DATA_ERROR;
  3492. }
  3493. r = z.total_in;
  3494. w = z.total_out;
  3495. inflateReset(z);
  3496. z.total_in = r;
  3497. z.total_out = w;
  3498. istate.mode = BLOCKS;
  3499. return Z_OK;
  3500. };
  3501. // Returns true if inflate is currently at the end of a block generated
  3502. // by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  3503. // implementation to provide an additional safety check. PPP uses
  3504. // Z_SYNC_FLUSH
  3505. // but removes the length bytes of the resulting empty stored block. When
  3506. // decompressing, PPP checks that at the end of input packet, inflate is
  3507. // waiting for these length bytes.
  3508. that.inflateSyncPoint = function (z) {
  3509. if (!z || !z.istate || !z.istate.blocks)
  3510. return Z_STREAM_ERROR;
  3511. return z.istate.blocks.sync_point();
  3512. };
  3513. }
  3514. // ZStream
  3515. function ZStream() {
  3516. }
  3517. ZStream.prototype = {
  3518. inflateInit: function (bits) {
  3519. const that = this;
  3520. that.istate = new Inflate$1();
  3521. if (!bits)
  3522. bits = MAX_BITS;
  3523. return that.istate.inflateInit(that, bits);
  3524. },
  3525. inflate: function (f) {
  3526. const that = this;
  3527. if (!that.istate)
  3528. return Z_STREAM_ERROR;
  3529. return that.istate.inflate(that, f);
  3530. },
  3531. inflateEnd: function () {
  3532. const that = this;
  3533. if (!that.istate)
  3534. return Z_STREAM_ERROR;
  3535. const ret = that.istate.inflateEnd(that);
  3536. that.istate = null;
  3537. return ret;
  3538. },
  3539. inflateSync: function () {
  3540. const that = this;
  3541. if (!that.istate)
  3542. return Z_STREAM_ERROR;
  3543. return that.istate.inflateSync(that);
  3544. },
  3545. inflateSetDictionary: function (dictionary, dictLength) {
  3546. const that = this;
  3547. if (!that.istate)
  3548. return Z_STREAM_ERROR;
  3549. return that.istate.inflateSetDictionary(that, dictionary, dictLength);
  3550. },
  3551. read_byte: function (start) {
  3552. const that = this;
  3553. return that.next_in[start];
  3554. },
  3555. read_buf: function (start, size) {
  3556. const that = this;
  3557. return that.next_in.subarray(start, start + size);
  3558. }
  3559. };
  3560. // Inflater
  3561. function ZipInflate(options) {
  3562. const that = this;
  3563. const z = new ZStream();
  3564. const bufsize = options && options.chunkSize ? Math.floor(options.chunkSize * 2) : 128 * 1024;
  3565. const flush = Z_NO_FLUSH;
  3566. const buf = new Uint8Array(bufsize);
  3567. let nomoreinput = false;
  3568. z.inflateInit();
  3569. z.next_out = buf;
  3570. that.append = function (data, onprogress) {
  3571. const buffers = [];
  3572. let err, array, lastIndex = 0, bufferIndex = 0, bufferSize = 0;
  3573. if (data.length === 0)
  3574. return;
  3575. z.next_in_index = 0;
  3576. z.next_in = data;
  3577. z.avail_in = data.length;
  3578. do {
  3579. z.next_out_index = 0;
  3580. z.avail_out = bufsize;
  3581. if ((z.avail_in === 0) && (!nomoreinput)) { // if buffer is empty and more input is available, refill it
  3582. z.next_in_index = 0;
  3583. nomoreinput = true;
  3584. }
  3585. err = z.inflate(flush);
  3586. if (nomoreinput && (err === Z_BUF_ERROR)) {
  3587. if (z.avail_in !== 0)
  3588. throw new Error("inflating: bad input");
  3589. } else if (err !== Z_OK && err !== Z_STREAM_END)
  3590. throw new Error("inflating: " + z.msg);
  3591. if ((nomoreinput || err === Z_STREAM_END) && (z.avail_in === data.length))
  3592. throw new Error("inflating: bad input");
  3593. if (z.next_out_index)
  3594. if (z.next_out_index === bufsize)
  3595. buffers.push(new Uint8Array(buf));
  3596. else
  3597. buffers.push(buf.slice(0, z.next_out_index));
  3598. bufferSize += z.next_out_index;
  3599. if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  3600. onprogress(z.next_in_index);
  3601. lastIndex = z.next_in_index;
  3602. }
  3603. } while (z.avail_in > 0 || z.avail_out === 0);
  3604. if (buffers.length > 1) {
  3605. array = new Uint8Array(bufferSize);
  3606. buffers.forEach(function (chunk) {
  3607. array.set(chunk, bufferIndex);
  3608. bufferIndex += chunk.length;
  3609. });
  3610. } else {
  3611. array = buffers[0] || new Uint8Array(0);
  3612. }
  3613. return array;
  3614. };
  3615. that.flush = function () {
  3616. z.inflateEnd();
  3617. };
  3618. }
  3619. /*
  3620. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  3621. Redistribution and use in source and binary forms, with or without
  3622. modification, are permitted provided that the following conditions are met:
  3623. 1. Redistributions of source code must retain the above copyright notice,
  3624. this list of conditions and the following disclaimer.
  3625. 2. Redistributions in binary form must reproduce the above copyright
  3626. notice, this list of conditions and the following disclaimer in
  3627. the documentation and/or other materials provided with the distribution.
  3628. 3. The names of the authors may not be used to endorse or promote products
  3629. derived from this software without specific prior written permission.
  3630. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  3631. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  3632. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  3633. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  3634. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  3635. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  3636. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  3637. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  3638. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  3639. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3640. */
  3641. /* global navigator */
  3642. const DEFAULT_CONFIGURATION = {
  3643. chunkSize: 512 * 1024,
  3644. maxWorkers: (typeof navigator != "undefined" && navigator.hardwareConcurrency) || 2,
  3645. terminateWorkerTimeout: 5000,
  3646. useWebWorkers: true,
  3647. workerScripts: undefined
  3648. };
  3649. const config = Object.assign({}, DEFAULT_CONFIGURATION);
  3650. function getConfiguration() {
  3651. return config;
  3652. }
  3653. function configure(configuration) {
  3654. if (configuration.baseURL !== undefined) {
  3655. config.baseURL = configuration.baseURL;
  3656. }
  3657. if (configuration.chunkSize !== undefined) {
  3658. config.chunkSize = configuration.chunkSize;
  3659. }
  3660. if (configuration.maxWorkers !== undefined) {
  3661. config.maxWorkers = configuration.maxWorkers;
  3662. }
  3663. if (configuration.terminateWorkerTimeout !== undefined) {
  3664. config.terminateWorkerTimeout = configuration.terminateWorkerTimeout;
  3665. }
  3666. if (configuration.useWebWorkers !== undefined) {
  3667. config.useWebWorkers = configuration.useWebWorkers;
  3668. }
  3669. if (configuration.Deflate !== undefined) {
  3670. config.Deflate = configuration.Deflate;
  3671. }
  3672. if (configuration.Inflate !== undefined) {
  3673. config.Inflate = configuration.Inflate;
  3674. }
  3675. if (configuration.workerScripts !== undefined) {
  3676. if (configuration.workerScripts.deflate) {
  3677. if (!Array.isArray(configuration.workerScripts.deflate)) {
  3678. throw new Error("workerScripts.deflate must be an array");
  3679. }
  3680. if (!config.workerScripts) {
  3681. config.workerScripts = {};
  3682. }
  3683. config.workerScripts.deflate = configuration.workerScripts.deflate;
  3684. }
  3685. if (configuration.workerScripts.inflate) {
  3686. if (!Array.isArray(configuration.workerScripts.inflate)) {
  3687. throw new Error("workerScripts.inflate must be an array");
  3688. }
  3689. if (!config.workerScripts) {
  3690. config.workerScripts = {};
  3691. }
  3692. config.workerScripts.inflate = configuration.workerScripts.inflate;
  3693. }
  3694. }
  3695. }
  3696. /*
  3697. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  3698. Redistribution and use in source and binary forms, with or without
  3699. modification, are permitted provided that the following conditions are met:
  3700. 1. Redistributions of source code must retain the above copyright notice,
  3701. this list of conditions and the following disclaimer.
  3702. 2. Redistributions in binary form must reproduce the above copyright
  3703. notice, this list of conditions and the following disclaimer in
  3704. the documentation and/or other materials provided with the distribution.
  3705. 3. The names of the authors may not be used to endorse or promote products
  3706. derived from this software without specific prior written permission.
  3707. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  3708. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  3709. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  3710. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  3711. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  3712. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  3713. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  3714. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  3715. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  3716. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3717. */
  3718. function getMimeType() {
  3719. return "application/octet-stream";
  3720. }
  3721. /*
  3722. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  3723. Redistribution and use in source and binary forms, with or without
  3724. modification, are permitted provided that the following conditions are met:
  3725. 1. Redistributions of source code must retain the above copyright notice,
  3726. this list of conditions and the following disclaimer.
  3727. 2. Redistributions in binary form must reproduce the above copyright
  3728. notice, this list of conditions and the following disclaimer in
  3729. the documentation and/or other materials provided with the distribution.
  3730. 3. The names of the authors may not be used to endorse or promote products
  3731. derived from this software without specific prior written permission.
  3732. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  3733. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  3734. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  3735. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  3736. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  3737. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  3738. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  3739. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  3740. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  3741. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3742. */
  3743. const table = [];
  3744. for (let i = 0; i < 256; i++) {
  3745. let t = i;
  3746. for (let j = 0; j < 8; j++) {
  3747. if (t & 1) {
  3748. t = (t >>> 1) ^ 0xEDB88320;
  3749. } else {
  3750. t = t >>> 1;
  3751. }
  3752. }
  3753. table[i] = t;
  3754. }
  3755. class Crc32 {
  3756. constructor(crc) {
  3757. this.crc = crc || -1;
  3758. }
  3759. append(data) {
  3760. let crc = this.crc | 0;
  3761. for (let offset = 0, length = data.length | 0; offset < length; offset++) {
  3762. crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF];
  3763. }
  3764. this.crc = crc;
  3765. }
  3766. get() {
  3767. return ~this.crc;
  3768. }
  3769. }
  3770. /*
  3771. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  3772. Redistribution and use in source and binary forms, with or without
  3773. modification, are permitted provided that the following conditions are met:
  3774. 1. Redistributions of source code must retain the above copyright notice,
  3775. this list of conditions and the following disclaimer.
  3776. 2. Redistributions in binary form must reproduce the above copyright
  3777. notice, this list of conditions and the following disclaimer in
  3778. the documentation and/or other materials provided with the distribution.
  3779. 3. The names of the authors may not be used to endorse or promote products
  3780. derived from this software without specific prior written permission.
  3781. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  3782. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  3783. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  3784. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  3785. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  3786. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  3787. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  3788. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  3789. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  3790. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3791. */
  3792. function encodeText(value) {
  3793. if (typeof TextEncoder == "undefined") {
  3794. value = unescape(encodeURIComponent(value));
  3795. const result = new Uint8Array(value.length);
  3796. for (let i = 0; i < result.length; i++) {
  3797. result[i] = value.charCodeAt(i);
  3798. }
  3799. return result;
  3800. } else {
  3801. return new TextEncoder().encode(value);
  3802. }
  3803. }
  3804. // Derived from https://github.com/xqdoo00o/jszip/blob/master/lib/sjcl.js and https://github.com/bitwiseshiftleft/sjcl
  3805. /*
  3806. * SJCL is open. You can use, modify and redistribute it under a BSD
  3807. * license or under the GNU GPL, version 2.0.
  3808. */
  3809. /** @fileOverview Javascript cryptography implementation.
  3810. *
  3811. * Crush to remove comments, shorten variable names and
  3812. * generally reduce transmission size.
  3813. *
  3814. * @author Emily Stark
  3815. * @author Mike Hamburg
  3816. * @author Dan Boneh
  3817. */
  3818. /*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */
  3819. /** @fileOverview Arrays of bits, encoded as arrays of Numbers.
  3820. *
  3821. * @author Emily Stark
  3822. * @author Mike Hamburg
  3823. * @author Dan Boneh
  3824. */
  3825. /**
  3826. * Arrays of bits, encoded as arrays of Numbers.
  3827. * @namespace
  3828. * @description
  3829. * <p>
  3830. * These objects are the currency accepted by SJCL's crypto functions.
  3831. * </p>
  3832. *
  3833. * <p>
  3834. * Most of our crypto primitives operate on arrays of 4-byte words internally,
  3835. * but many of them can take arguments that are not a multiple of 4 bytes.
  3836. * This library encodes arrays of bits (whose size need not be a multiple of 8
  3837. * bits) as arrays of 32-bit words. The bits are packed, big-endian, into an
  3838. * array of words, 32 bits at a time. Since the words are double-precision
  3839. * floating point numbers, they fit some extra data. We use this (in a private,
  3840. * possibly-changing manner) to encode the number of bits actually present
  3841. * in the last word of the array.
  3842. * </p>
  3843. *
  3844. * <p>
  3845. * Because bitwise ops clear this out-of-band data, these arrays can be passed
  3846. * to ciphers like AES which want arrays of words.
  3847. * </p>
  3848. */
  3849. const bitArray = {
  3850. /**
  3851. * Concatenate two bit arrays.
  3852. * @param {bitArray} a1 The first array.
  3853. * @param {bitArray} a2 The second array.
  3854. * @return {bitArray} The concatenation of a1 and a2.
  3855. */
  3856. concat(a1, a2) {
  3857. if (a1.length === 0 || a2.length === 0) {
  3858. return a1.concat(a2);
  3859. }
  3860. const last = a1[a1.length - 1], shift = bitArray.getPartial(last);
  3861. if (shift === 32) {
  3862. return a1.concat(a2);
  3863. } else {
  3864. return bitArray._shiftRight(a2, shift, last | 0, a1.slice(0, a1.length - 1));
  3865. }
  3866. },
  3867. /**
  3868. * Find the length of an array of bits.
  3869. * @param {bitArray} a The array.
  3870. * @return {Number} The length of a, in bits.
  3871. */
  3872. bitLength(a) {
  3873. const l = a.length;
  3874. if (l === 0) {
  3875. return 0;
  3876. }
  3877. const x = a[l - 1];
  3878. return (l - 1) * 32 + bitArray.getPartial(x);
  3879. },
  3880. /**
  3881. * Truncate an array.
  3882. * @param {bitArray} a The array.
  3883. * @param {Number} len The length to truncate to, in bits.
  3884. * @return {bitArray} A new array, truncated to len bits.
  3885. */
  3886. clamp(a, len) {
  3887. if (a.length * 32 < len) {
  3888. return a;
  3889. }
  3890. a = a.slice(0, Math.ceil(len / 32));
  3891. const l = a.length;
  3892. len = len & 31;
  3893. if (l > 0 && len) {
  3894. a[l - 1] = bitArray.partial(len, a[l - 1] & 0x80000000 >> (len - 1), 1);
  3895. }
  3896. return a;
  3897. },
  3898. /**
  3899. * Make a partial word for a bit array.
  3900. * @param {Number} len The number of bits in the word.
  3901. * @param {Number} x The bits.
  3902. * @param {Number} [_end=0] Pass 1 if x has already been shifted to the high side.
  3903. * @return {Number} The partial word.
  3904. */
  3905. partial(len, x, _end) {
  3906. if (len === 32) {
  3907. return x;
  3908. }
  3909. return (_end ? x | 0 : x << (32 - len)) + len * 0x10000000000;
  3910. },
  3911. /**
  3912. * Get the number of bits used by a partial word.
  3913. * @param {Number} x The partial word.
  3914. * @return {Number} The number of bits used by the partial word.
  3915. */
  3916. getPartial(x) {
  3917. return Math.round(x / 0x10000000000) || 32;
  3918. },
  3919. /** Shift an array right.
  3920. * @param {bitArray} a The array to shift.
  3921. * @param {Number} shift The number of bits to shift.
  3922. * @param {Number} [carry=0] A byte to carry in
  3923. * @param {bitArray} [out=[]] An array to prepend to the output.
  3924. * @private
  3925. */
  3926. _shiftRight(a, shift, carry, out) {
  3927. if (out === undefined) {
  3928. out = [];
  3929. }
  3930. for (; shift >= 32; shift -= 32) {
  3931. out.push(carry);
  3932. carry = 0;
  3933. }
  3934. if (shift === 0) {
  3935. return out.concat(a);
  3936. }
  3937. for (let i = 0; i < a.length; i++) {
  3938. out.push(carry | a[i] >>> shift);
  3939. carry = a[i] << (32 - shift);
  3940. }
  3941. const last2 = a.length ? a[a.length - 1] : 0;
  3942. const shift2 = bitArray.getPartial(last2);
  3943. out.push(bitArray.partial(shift + shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(), 1));
  3944. return out;
  3945. }
  3946. };
  3947. /** @fileOverview Bit array codec implementations.
  3948. *
  3949. * @author Emily Stark
  3950. * @author Mike Hamburg
  3951. * @author Dan Boneh
  3952. */
  3953. /**
  3954. * Arrays of bytes
  3955. * @namespace
  3956. */
  3957. const codec = {
  3958. bytes: {
  3959. /** Convert from a bitArray to an array of bytes. */
  3960. fromBits(arr) {
  3961. const bl = bitArray.bitLength(arr);
  3962. const byteLength = bl / 8;
  3963. const out = new Uint8Array(byteLength);
  3964. let tmp;
  3965. for (let i = 0; i < byteLength; i++) {
  3966. if ((i & 3) === 0) {
  3967. tmp = arr[i / 4];
  3968. }
  3969. out[i] = tmp >>> 24;
  3970. tmp <<= 8;
  3971. }
  3972. return out;
  3973. },
  3974. /** Convert from an array of bytes to a bitArray. */
  3975. toBits(bytes) {
  3976. const out = [];
  3977. let i;
  3978. let tmp = 0;
  3979. for (i = 0; i < bytes.length; i++) {
  3980. tmp = tmp << 8 | bytes[i];
  3981. if ((i & 3) === 3) {
  3982. out.push(tmp);
  3983. tmp = 0;
  3984. }
  3985. }
  3986. if (i & 3) {
  3987. out.push(bitArray.partial(8 * (i & 3), tmp));
  3988. }
  3989. return out;
  3990. }
  3991. }
  3992. };
  3993. const hash = {};
  3994. /**
  3995. * Context for a SHA-1 operation in progress.
  3996. * @constructor
  3997. */
  3998. hash.sha1 = function (hash) {
  3999. if (hash) {
  4000. this._h = hash._h.slice(0);
  4001. this._buffer = hash._buffer.slice(0);
  4002. this._length = hash._length;
  4003. } else {
  4004. this.reset();
  4005. }
  4006. };
  4007. hash.sha1.prototype = {
  4008. /**
  4009. * The hash's block size, in bits.
  4010. * @constant
  4011. */
  4012. blockSize: 512,
  4013. /**
  4014. * Reset the hash state.
  4015. * @return this
  4016. */
  4017. reset: function () {
  4018. const sha1 = this;
  4019. sha1._h = this._init.slice(0);
  4020. sha1._buffer = [];
  4021. sha1._length = 0;
  4022. return sha1;
  4023. },
  4024. /**
  4025. * Input several words to the hash.
  4026. * @param {bitArray|String} data the data to hash.
  4027. * @return this
  4028. */
  4029. update: function (data) {
  4030. const sha1 = this;
  4031. if (typeof data === "string") {
  4032. data = codec.utf8String.toBits(data);
  4033. }
  4034. const b = sha1._buffer = bitArray.concat(sha1._buffer, data);
  4035. const ol = sha1._length;
  4036. const nl = sha1._length = ol + bitArray.bitLength(data);
  4037. if (nl > 9007199254740991) {
  4038. throw new Error("Cannot hash more than 2^53 - 1 bits");
  4039. }
  4040. const c = new Uint32Array(b);
  4041. let j = 0;
  4042. for (let i = sha1.blockSize + ol - ((sha1.blockSize + ol) & (sha1.blockSize - 1)); i <= nl;
  4043. i += sha1.blockSize) {
  4044. sha1._block(c.subarray(16 * j, 16 * (j + 1)));
  4045. j += 1;
  4046. }
  4047. b.splice(0, 16 * j);
  4048. return sha1;
  4049. },
  4050. /**
  4051. * Complete hashing and output the hash value.
  4052. * @return {bitArray} The hash value, an array of 5 big-endian words. TODO
  4053. */
  4054. finalize: function () {
  4055. const sha1 = this;
  4056. let b = sha1._buffer;
  4057. const h = sha1._h;
  4058. // Round out and push the buffer
  4059. b = bitArray.concat(b, [bitArray.partial(1, 1)]);
  4060. // Round out the buffer to a multiple of 16 words, less the 2 length words.
  4061. for (let i = b.length + 2; i & 15; i++) {
  4062. b.push(0);
  4063. }
  4064. // append the length
  4065. b.push(Math.floor(sha1._length / 0x100000000));
  4066. b.push(sha1._length | 0);
  4067. while (b.length) {
  4068. sha1._block(b.splice(0, 16));
  4069. }
  4070. sha1.reset();
  4071. return h;
  4072. },
  4073. /**
  4074. * The SHA-1 initialization vector.
  4075. * @private
  4076. */
  4077. _init: [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0],
  4078. /**
  4079. * The SHA-1 hash key.
  4080. * @private
  4081. */
  4082. _key: [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6],
  4083. /**
  4084. * The SHA-1 logical functions f(0), f(1), ..., f(79).
  4085. * @private
  4086. */
  4087. _f: function (t, b, c, d) {
  4088. if (t <= 19) {
  4089. return (b & c) | (~b & d);
  4090. } else if (t <= 39) {
  4091. return b ^ c ^ d;
  4092. } else if (t <= 59) {
  4093. return (b & c) | (b & d) | (c & d);
  4094. } else if (t <= 79) {
  4095. return b ^ c ^ d;
  4096. }
  4097. },
  4098. /**
  4099. * Circular left-shift operator.
  4100. * @private
  4101. */
  4102. _S: function (n, x) {
  4103. return (x << n) | (x >>> 32 - n);
  4104. },
  4105. /**
  4106. * Perform one cycle of SHA-1.
  4107. * @param {Uint32Array|bitArray} words one block of words.
  4108. * @private
  4109. */
  4110. _block: function (words) {
  4111. const sha1 = this;
  4112. const h = sha1._h;
  4113. // When words is passed to _block, it has 16 elements. SHA1 _block
  4114. // function extends words with new elements (at the end there are 80 elements).
  4115. // The problem is that if we use Uint32Array instead of Array,
  4116. // the length of Uint32Array cannot be changed. Thus, we replace words with a
  4117. // normal Array here.
  4118. const w = Array(80); // do not use Uint32Array here as the instantiation is slower
  4119. for (let j = 0; j < 16; j++) {
  4120. w[j] = words[j];
  4121. }
  4122. let a = h[0];
  4123. let b = h[1];
  4124. let c = h[2];
  4125. let d = h[3];
  4126. let e = h[4];
  4127. for (let t = 0; t <= 79; t++) {
  4128. if (t >= 16) {
  4129. w[t] = sha1._S(1, w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]);
  4130. }
  4131. const tmp = (sha1._S(5, a) + sha1._f(t, b, c, d) + e + w[t] +
  4132. sha1._key[Math.floor(t / 20)]) | 0;
  4133. e = d;
  4134. d = c;
  4135. c = sha1._S(30, b);
  4136. b = a;
  4137. a = tmp;
  4138. }
  4139. h[0] = (h[0] + a) | 0;
  4140. h[1] = (h[1] + b) | 0;
  4141. h[2] = (h[2] + c) | 0;
  4142. h[3] = (h[3] + d) | 0;
  4143. h[4] = (h[4] + e) | 0;
  4144. }
  4145. };
  4146. /** @fileOverview Low-level AES implementation.
  4147. *
  4148. * This file contains a low-level implementation of AES, optimized for
  4149. * size and for efficiency on several browsers. It is based on
  4150. * OpenSSL's aes_core.c, a public-domain implementation by Vincent
  4151. * Rijmen, Antoon Bosselaers and Paulo Barreto.
  4152. *
  4153. * An older version of this implementation is available in the public
  4154. * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,
  4155. * Stanford University 2008-2010 and BSD-licensed for liability
  4156. * reasons.
  4157. *
  4158. * @author Emily Stark
  4159. * @author Mike Hamburg
  4160. * @author Dan Boneh
  4161. */
  4162. const cipher = {};
  4163. /**
  4164. * Schedule out an AES key for both encryption and decryption. This
  4165. * is a low-level class. Use a cipher mode to do bulk encryption.
  4166. *
  4167. * @constructor
  4168. * @param {Array} key The key as an array of 4, 6 or 8 words.
  4169. */
  4170. cipher.aes = class {
  4171. constructor(key) {
  4172. /**
  4173. * The expanded S-box and inverse S-box tables. These will be computed
  4174. * on the client so that we don't have to send them down the wire.
  4175. *
  4176. * There are two tables, _tables[0] is for encryption and
  4177. * _tables[1] is for decryption.
  4178. *
  4179. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  4180. * last (_tables[01][4]) is the S-box itself.
  4181. *
  4182. * @private
  4183. */
  4184. const aes = this;
  4185. aes._tables = [[[], [], [], [], []], [[], [], [], [], []]];
  4186. if (!aes._tables[0][0][0]) {
  4187. aes._precompute();
  4188. }
  4189. const sbox = aes._tables[0][4];
  4190. const decTable = aes._tables[1];
  4191. const keyLen = key.length;
  4192. let i, encKey, decKey, rcon = 1;
  4193. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  4194. throw new Error("invalid aes key size");
  4195. }
  4196. aes._key = [encKey = key.slice(0), decKey = []];
  4197. // schedule encryption keys
  4198. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  4199. let tmp = encKey[i - 1];
  4200. // apply sbox
  4201. if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {
  4202. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
  4203. // shift rows and add rcon
  4204. if (i % keyLen === 0) {
  4205. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  4206. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  4207. }
  4208. }
  4209. encKey[i] = encKey[i - keyLen] ^ tmp;
  4210. }
  4211. // schedule decryption keys
  4212. for (let j = 0; i; j++, i--) {
  4213. const tmp = encKey[j & 3 ? i : i - 4];
  4214. if (i <= 4 || j < 4) {
  4215. decKey[j] = tmp;
  4216. } else {
  4217. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^
  4218. decTable[1][sbox[tmp >> 16 & 255]] ^
  4219. decTable[2][sbox[tmp >> 8 & 255]] ^
  4220. decTable[3][sbox[tmp & 255]];
  4221. }
  4222. }
  4223. }
  4224. // public
  4225. /* Something like this might appear here eventually
  4226. name: "AES",
  4227. blockSize: 4,
  4228. keySizes: [4,6,8],
  4229. */
  4230. /**
  4231. * Encrypt an array of 4 big-endian words.
  4232. * @param {Array} data The plaintext.
  4233. * @return {Array} The ciphertext.
  4234. */
  4235. encrypt(data) {
  4236. return this._crypt(data, 0);
  4237. }
  4238. /**
  4239. * Decrypt an array of 4 big-endian words.
  4240. * @param {Array} data The ciphertext.
  4241. * @return {Array} The plaintext.
  4242. */
  4243. decrypt(data) {
  4244. return this._crypt(data, 1);
  4245. }
  4246. /**
  4247. * Expand the S-box tables.
  4248. *
  4249. * @private
  4250. */
  4251. _precompute() {
  4252. const encTable = this._tables[0];
  4253. const decTable = this._tables[1];
  4254. const sbox = encTable[4];
  4255. const sboxInv = decTable[4];
  4256. const d = [];
  4257. const th = [];
  4258. let xInv, x2, x4, x8;
  4259. // Compute double and third tables
  4260. for (let i = 0; i < 256; i++) {
  4261. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  4262. }
  4263. for (let x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  4264. // Compute sbox
  4265. let s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  4266. s = s >> 8 ^ s & 255 ^ 99;
  4267. sbox[x] = s;
  4268. sboxInv[s] = x;
  4269. // Compute MixColumns
  4270. x8 = d[x4 = d[x2 = d[x]]];
  4271. let tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  4272. let tEnc = d[s] * 0x101 ^ s * 0x1010100;
  4273. for (let i = 0; i < 4; i++) {
  4274. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  4275. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  4276. }
  4277. }
  4278. // Compactify. Considerable speedup on Firefox.
  4279. for (let i = 0; i < 5; i++) {
  4280. encTable[i] = encTable[i].slice(0);
  4281. decTable[i] = decTable[i].slice(0);
  4282. }
  4283. }
  4284. /**
  4285. * Encryption and decryption core.
  4286. * @param {Array} input Four words to be encrypted or decrypted.
  4287. * @param dir The direction, 0 for encrypt and 1 for decrypt.
  4288. * @return {Array} The four encrypted or decrypted words.
  4289. * @private
  4290. */
  4291. _crypt(input, dir) {
  4292. if (input.length !== 4) {
  4293. throw new Error("invalid aes block size");
  4294. }
  4295. const key = this._key[dir];
  4296. const nInnerRounds = key.length / 4 - 2;
  4297. const out = [0, 0, 0, 0];
  4298. const table = this._tables[dir];
  4299. // load up the tables
  4300. const t0 = table[0];
  4301. const t1 = table[1];
  4302. const t2 = table[2];
  4303. const t3 = table[3];
  4304. const sbox = table[4];
  4305. // state variables a,b,c,d are loaded with pre-whitened data
  4306. let a = input[0] ^ key[0];
  4307. let b = input[dir ? 3 : 1] ^ key[1];
  4308. let c = input[2] ^ key[2];
  4309. let d = input[dir ? 1 : 3] ^ key[3];
  4310. let kIndex = 4;
  4311. let a2, b2, c2;
  4312. // Inner rounds. Cribbed from OpenSSL.
  4313. for (let i = 0; i < nInnerRounds; i++) {
  4314. a2 = t0[a >>> 24] ^ t1[b >> 16 & 255] ^ t2[c >> 8 & 255] ^ t3[d & 255] ^ key[kIndex];
  4315. b2 = t0[b >>> 24] ^ t1[c >> 16 & 255] ^ t2[d >> 8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];
  4316. c2 = t0[c >>> 24] ^ t1[d >> 16 & 255] ^ t2[a >> 8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
  4317. d = t0[d >>> 24] ^ t1[a >> 16 & 255] ^ t2[b >> 8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
  4318. kIndex += 4;
  4319. a = a2; b = b2; c = c2;
  4320. }
  4321. // Last round.
  4322. for (let i = 0; i < 4; i++) {
  4323. out[dir ? 3 & -i : i] =
  4324. sbox[a >>> 24] << 24 ^
  4325. sbox[b >> 16 & 255] << 16 ^
  4326. sbox[c >> 8 & 255] << 8 ^
  4327. sbox[d & 255] ^
  4328. key[kIndex++];
  4329. a2 = a; a = b; b = c; c = d; d = a2;
  4330. }
  4331. return out;
  4332. }
  4333. };
  4334. /**
  4335. * Random values
  4336. * @namespace
  4337. */
  4338. const random = {
  4339. /**
  4340. * Generate random words with pure js, cryptographically not as strong & safe as native implementation.
  4341. * @param {TypedArray} typedArray The array to fill.
  4342. * @return {TypedArray} The random values.
  4343. */
  4344. getRandomValues(typedArray) {
  4345. const words = new Uint32Array(typedArray.buffer);
  4346. const r = (m_w) => {
  4347. let m_z = 0x3ade68b1;
  4348. const mask = 0xffffffff;
  4349. return function () {
  4350. m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
  4351. m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
  4352. const result = ((((m_z << 0x10) + m_w) & mask) / 0x100000000) + .5;
  4353. return result * (Math.random() > .5 ? 1 : -1);
  4354. };
  4355. };
  4356. for (let i = 0, rcache; i < typedArray.length; i += 4) {
  4357. let _r = r((rcache || Math.random()) * 0x100000000);
  4358. rcache = _r() * 0x3ade67b7;
  4359. words[i / 4] = (_r() * 0x100000000) | 0;
  4360. }
  4361. return typedArray;
  4362. }
  4363. };
  4364. /** @fileOverview CTR mode implementation.
  4365. *
  4366. * Special thanks to Roy Nicholson for pointing out a bug in our
  4367. * implementation.
  4368. *
  4369. * @author Emily Stark
  4370. * @author Mike Hamburg
  4371. * @author Dan Boneh
  4372. */
  4373. /** Brian Gladman's CTR Mode.
  4374. * @constructor
  4375. * @param {Object} _prf The aes instance to generate key.
  4376. * @param {bitArray} _iv The iv for ctr mode, it must be 128 bits.
  4377. */
  4378. const mode = {};
  4379. /**
  4380. * Brian Gladman's CTR Mode.
  4381. * @namespace
  4382. */
  4383. mode.ctrGladman = class {
  4384. constructor(prf, iv) {
  4385. this._prf = prf;
  4386. this._initIv = iv;
  4387. this._iv = iv;
  4388. }
  4389. reset() {
  4390. this._iv = this._initIv;
  4391. }
  4392. /** Input some data to calculate.
  4393. * @param {bitArray} data the data to process, it must be intergral multiple of 128 bits unless it's the last.
  4394. */
  4395. update(data) {
  4396. return this.calculate(this._prf, data, this._iv);
  4397. }
  4398. incWord(word) {
  4399. if (((word >> 24) & 0xff) === 0xff) { //overflow
  4400. let b1 = (word >> 16) & 0xff;
  4401. let b2 = (word >> 8) & 0xff;
  4402. let b3 = word & 0xff;
  4403. if (b1 === 0xff) { // overflow b1
  4404. b1 = 0;
  4405. if (b2 === 0xff) {
  4406. b2 = 0;
  4407. if (b3 === 0xff) {
  4408. b3 = 0;
  4409. } else {
  4410. ++b3;
  4411. }
  4412. } else {
  4413. ++b2;
  4414. }
  4415. } else {
  4416. ++b1;
  4417. }
  4418. word = 0;
  4419. word += (b1 << 16);
  4420. word += (b2 << 8);
  4421. word += b3;
  4422. } else {
  4423. word += (0x01 << 24);
  4424. }
  4425. return word;
  4426. }
  4427. incCounter(counter) {
  4428. if ((counter[0] = this.incWord(counter[0])) === 0) {
  4429. // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
  4430. counter[1] = this.incWord(counter[1]);
  4431. }
  4432. }
  4433. calculate(prf, data, iv) {
  4434. let l;
  4435. if (!(l = data.length)) {
  4436. return [];
  4437. }
  4438. const bl = bitArray.bitLength(data);
  4439. for (let i = 0; i < l; i += 4) {
  4440. this.incCounter(iv);
  4441. const e = prf.encrypt(iv);
  4442. data[i] ^= e[0];
  4443. data[i + 1] ^= e[1];
  4444. data[i + 2] ^= e[2];
  4445. data[i + 3] ^= e[3];
  4446. }
  4447. return bitArray.clamp(data, bl);
  4448. }
  4449. };
  4450. const misc = {
  4451. importKey(password) {
  4452. return new misc.hmacSha1(codec.bytes.toBits(password));
  4453. },
  4454. pbkdf2(prf, salt, count, length) {
  4455. count = count || 10000;
  4456. if (length < 0 || count < 0) {
  4457. throw new Error("invalid params to pbkdf2");
  4458. }
  4459. const byteLength = ((length >> 5) + 1) << 2;
  4460. let u, ui, i, j, k;
  4461. const arrayBuffer = new ArrayBuffer(byteLength);
  4462. let out = new DataView(arrayBuffer);
  4463. let outLength = 0;
  4464. const b = bitArray;
  4465. salt = codec.bytes.toBits(salt);
  4466. for (k = 1; outLength < (byteLength || 1); k++) {
  4467. u = ui = prf.encrypt(b.concat(salt, [k]));
  4468. for (i = 1; i < count; i++) {
  4469. ui = prf.encrypt(ui);
  4470. for (j = 0; j < ui.length; j++) {
  4471. u[j] ^= ui[j];
  4472. }
  4473. }
  4474. for (i = 0; outLength < (byteLength || 1) && i < u.length; i++) {
  4475. out.setInt32(outLength, u[i]);
  4476. outLength += 4;
  4477. }
  4478. }
  4479. return arrayBuffer.slice(0, length / 8);
  4480. }
  4481. };
  4482. /** @fileOverview HMAC implementation.
  4483. *
  4484. * @author Emily Stark
  4485. * @author Mike Hamburg
  4486. * @author Dan Boneh
  4487. */
  4488. /** HMAC with the specified hash function.
  4489. * @constructor
  4490. * @param {bitArray} key the key for HMAC.
  4491. * @param {Object} [Hash=hash.sha1] The hash function to use.
  4492. */
  4493. misc.hmacSha1 = class {
  4494. constructor(key) {
  4495. const hmac = this;
  4496. const Hash = hmac._hash = hash.sha1;
  4497. const exKey = [[], []];
  4498. const bs = Hash.prototype.blockSize / 32;
  4499. hmac._baseHash = [new Hash(), new Hash()];
  4500. if (key.length > bs) {
  4501. key = Hash.hash(key);
  4502. }
  4503. for (let i = 0; i < bs; i++) {
  4504. exKey[0][i] = key[i] ^ 0x36363636;
  4505. exKey[1][i] = key[i] ^ 0x5C5C5C5C;
  4506. }
  4507. hmac._baseHash[0].update(exKey[0]);
  4508. hmac._baseHash[1].update(exKey[1]);
  4509. hmac._resultHash = new Hash(hmac._baseHash[0]);
  4510. }
  4511. reset() {
  4512. const hmac = this;
  4513. hmac._resultHash = new hmac._hash(hmac._baseHash[0]);
  4514. hmac._updated = false;
  4515. }
  4516. update(data) {
  4517. const hmac = this;
  4518. hmac._updated = true;
  4519. hmac._resultHash.update(data);
  4520. }
  4521. digest() {
  4522. const hmac = this;
  4523. const w = hmac._resultHash.finalize();
  4524. const result = new (hmac._hash)(hmac._baseHash[1]).update(w).finalize();
  4525. hmac.reset();
  4526. return result;
  4527. }
  4528. encrypt(data) {
  4529. if (!this._updated) {
  4530. this.update(data);
  4531. return this.digest(data);
  4532. } else {
  4533. throw new Error("encrypt on already updated hmac called!");
  4534. }
  4535. }
  4536. };
  4537. /*
  4538. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  4539. Redistribution and use in source and binary forms, with or without
  4540. modification, are permitted provided that the following conditions are met:
  4541. 1. Redistributions of source code must retain the above copyright notice,
  4542. this list of conditions and the following disclaimer.
  4543. 2. Redistributions in binary form must reproduce the above copyright
  4544. notice, this list of conditions and the following disclaimer in
  4545. the documentation and/or other materials provided with the distribution.
  4546. 3. The names of the authors may not be used to endorse or promote products
  4547. derived from this software without specific prior written permission.
  4548. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  4549. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  4550. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  4551. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  4552. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4553. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  4554. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  4555. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  4556. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  4557. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4558. */
  4559. const ERR_INVALID_PASSWORD = "Invalid pasword";
  4560. const BLOCK_LENGTH = 16;
  4561. const RAW_FORMAT = "raw";
  4562. const PBKDF2_ALGORITHM = { name: "PBKDF2" };
  4563. const HASH_ALGORITHM = { name: "HMAC" };
  4564. const HASH_FUNCTION = "SHA-1";
  4565. const BASE_KEY_ALGORITHM = Object.assign({ hash: HASH_ALGORITHM }, PBKDF2_ALGORITHM);
  4566. const DERIVED_BITS_ALGORITHM = Object.assign({ iterations: 1000, hash: { name: HASH_FUNCTION } }, PBKDF2_ALGORITHM);
  4567. const DERIVED_BITS_USAGE = ["deriveBits"];
  4568. const SALT_LENGTH = [8, 12, 16];
  4569. const KEY_LENGTH = [16, 24, 32];
  4570. const SIGNATURE_LENGTH = 10;
  4571. const COUNTER_DEFAULT_VALUE = [0, 0, 0, 0];
  4572. const CRYPTO_API_SUPPORTED = typeof crypto != "undefined";
  4573. const SUBTLE_API_SUPPORTED = CRYPTO_API_SUPPORTED && typeof crypto.subtle != "undefined";
  4574. const codecBytes = codec.bytes;
  4575. const Aes = cipher.aes;
  4576. const CtrGladman = mode.ctrGladman;
  4577. const HmacSha1 = misc.hmacSha1;
  4578. class AESDecrypt {
  4579. constructor(password, signed, strength) {
  4580. Object.assign(this, {
  4581. password,
  4582. signed,
  4583. strength: strength - 1,
  4584. pendingInput: new Uint8Array(0)
  4585. });
  4586. }
  4587. async append(input) {
  4588. const aesCrypto = this;
  4589. if (aesCrypto.password) {
  4590. const preamble = subarray(input, 0, SALT_LENGTH[aesCrypto.strength] + 2);
  4591. await createDecryptionKeys(aesCrypto, preamble, aesCrypto.password);
  4592. aesCrypto.password = null;
  4593. aesCrypto.aesCtrGladman = new CtrGladman(new Aes(aesCrypto.keys.key), Array.from(COUNTER_DEFAULT_VALUE));
  4594. aesCrypto.hmac = new HmacSha1(aesCrypto.keys.authentication);
  4595. input = subarray(input, SALT_LENGTH[aesCrypto.strength] + 2);
  4596. }
  4597. const output = new Uint8Array(input.length - SIGNATURE_LENGTH - ((input.length - SIGNATURE_LENGTH) % BLOCK_LENGTH));
  4598. return append(aesCrypto, input, output, 0, SIGNATURE_LENGTH, true);
  4599. }
  4600. flush() {
  4601. const aesCrypto = this;
  4602. const pendingInput = aesCrypto.pendingInput;
  4603. const chunkToDecrypt = subarray(pendingInput, 0, pendingInput.length - SIGNATURE_LENGTH);
  4604. const originalSignature = subarray(pendingInput, pendingInput.length - SIGNATURE_LENGTH);
  4605. let decryptedChunkArray = new Uint8Array(0);
  4606. if (chunkToDecrypt.length) {
  4607. const encryptedChunk = codecBytes.toBits(chunkToDecrypt);
  4608. aesCrypto.hmac.update(encryptedChunk);
  4609. const decryptedChunk = aesCrypto.aesCtrGladman.update(encryptedChunk);
  4610. decryptedChunkArray = codecBytes.fromBits(decryptedChunk);
  4611. }
  4612. let valid = true;
  4613. if (aesCrypto.signed) {
  4614. const signature = subarray(codecBytes.fromBits(aesCrypto.hmac.digest()), 0, SIGNATURE_LENGTH);
  4615. for (let indexSignature = 0; indexSignature < SIGNATURE_LENGTH; indexSignature++) {
  4616. if (signature[indexSignature] != originalSignature[indexSignature]) {
  4617. valid = false;
  4618. }
  4619. }
  4620. }
  4621. return {
  4622. valid,
  4623. data: decryptedChunkArray
  4624. };
  4625. }
  4626. }
  4627. class AESEncrypt {
  4628. constructor(password, strength) {
  4629. Object.assign(this, {
  4630. password,
  4631. strength: strength - 1,
  4632. pendingInput: new Uint8Array(0)
  4633. });
  4634. }
  4635. async append(input) {
  4636. const aesCrypto = this;
  4637. let preamble = new Uint8Array(0);
  4638. if (aesCrypto.password) {
  4639. preamble = await createEncryptionKeys(aesCrypto, aesCrypto.password);
  4640. aesCrypto.password = null;
  4641. aesCrypto.aesCtrGladman = new CtrGladman(new Aes(aesCrypto.keys.key), Array.from(COUNTER_DEFAULT_VALUE));
  4642. aesCrypto.hmac = new HmacSha1(aesCrypto.keys.authentication);
  4643. }
  4644. const output = new Uint8Array(preamble.length + input.length - (input.length % BLOCK_LENGTH));
  4645. output.set(preamble, 0);
  4646. return append(aesCrypto, input, output, preamble.length, 0);
  4647. }
  4648. flush() {
  4649. const aesCrypto = this;
  4650. let encryptedChunkArray = new Uint8Array(0);
  4651. if (aesCrypto.pendingInput.length) {
  4652. const encryptedChunk = aesCrypto.aesCtrGladman.update(codecBytes.toBits(aesCrypto.pendingInput));
  4653. aesCrypto.hmac.update(encryptedChunk);
  4654. encryptedChunkArray = codecBytes.fromBits(encryptedChunk);
  4655. }
  4656. const signature = subarray(codecBytes.fromBits(aesCrypto.hmac.digest()), 0, SIGNATURE_LENGTH);
  4657. return {
  4658. data: concat(encryptedChunkArray, signature),
  4659. signature
  4660. };
  4661. }
  4662. }
  4663. function append(aesCrypto, input, output, paddingStart, paddingEnd, verifySignature) {
  4664. const inputLength = input.length - paddingEnd;
  4665. if (aesCrypto.pendingInput.length) {
  4666. input = concat(aesCrypto.pendingInput, input);
  4667. output = expand(output, inputLength - (inputLength % BLOCK_LENGTH));
  4668. }
  4669. let offset;
  4670. for (offset = 0; offset <= inputLength - BLOCK_LENGTH; offset += BLOCK_LENGTH) {
  4671. const inputChunk = codecBytes.toBits(subarray(input, offset, offset + BLOCK_LENGTH));
  4672. if (verifySignature) {
  4673. aesCrypto.hmac.update(inputChunk);
  4674. }
  4675. const outputChunk = aesCrypto.aesCtrGladman.update(inputChunk);
  4676. if (!verifySignature) {
  4677. aesCrypto.hmac.update(outputChunk);
  4678. }
  4679. output.set(codecBytes.fromBits(outputChunk), offset + paddingStart);
  4680. }
  4681. aesCrypto.pendingInput = subarray(input, offset);
  4682. return output;
  4683. }
  4684. async function createDecryptionKeys(decrypt, preambleArray, password) {
  4685. await createKeys$1(decrypt, password, subarray(preambleArray, 0, SALT_LENGTH[decrypt.strength]));
  4686. const passwordVerification = subarray(preambleArray, SALT_LENGTH[decrypt.strength]);
  4687. const passwordVerificationKey = decrypt.keys.passwordVerification;
  4688. if (passwordVerificationKey[0] != passwordVerification[0] || passwordVerificationKey[1] != passwordVerification[1]) {
  4689. throw new Error(ERR_INVALID_PASSWORD);
  4690. }
  4691. }
  4692. async function createEncryptionKeys(encrypt, password) {
  4693. const salt = getRandomValues(new Uint8Array(SALT_LENGTH[encrypt.strength]));
  4694. await createKeys$1(encrypt, password, salt);
  4695. return concat(salt, encrypt.keys.passwordVerification);
  4696. }
  4697. async function createKeys$1(target, password, salt) {
  4698. const encodedPassword = encodeText(password);
  4699. const basekey = await importKey(RAW_FORMAT, encodedPassword, BASE_KEY_ALGORITHM, false, DERIVED_BITS_USAGE);
  4700. const derivedBits = await deriveBits(Object.assign({ salt }, DERIVED_BITS_ALGORITHM), basekey, 8 * ((KEY_LENGTH[target.strength] * 2) + 2));
  4701. const compositeKey = new Uint8Array(derivedBits);
  4702. target.keys = {
  4703. key: codecBytes.toBits(subarray(compositeKey, 0, KEY_LENGTH[target.strength])),
  4704. authentication: codecBytes.toBits(subarray(compositeKey, KEY_LENGTH[target.strength], KEY_LENGTH[target.strength] * 2)),
  4705. passwordVerification: subarray(compositeKey, KEY_LENGTH[target.strength] * 2)
  4706. };
  4707. }
  4708. function getRandomValues(array) {
  4709. if (CRYPTO_API_SUPPORTED && typeof crypto.getRandomValues == "function") {
  4710. return crypto.getRandomValues(array);
  4711. } else {
  4712. return random.getRandomValues(array);
  4713. }
  4714. }
  4715. async function importKey(format, password, algorithm, extractable, keyUsages) {
  4716. if (CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof crypto.subtle.importKey == "function") {
  4717. return crypto.subtle.importKey(format, password, algorithm, extractable, keyUsages);
  4718. } else {
  4719. return misc.importKey(password);
  4720. }
  4721. }
  4722. async function deriveBits(algorithm, baseKey, length) {
  4723. if (CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof crypto.subtle.deriveBits == "function") {
  4724. return await crypto.subtle.deriveBits(algorithm, baseKey, length);
  4725. } else {
  4726. return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length);
  4727. }
  4728. }
  4729. function concat(leftArray, rightArray) {
  4730. let array = leftArray;
  4731. if (leftArray.length + rightArray.length) {
  4732. array = new Uint8Array(leftArray.length + rightArray.length);
  4733. array.set(leftArray, 0);
  4734. array.set(rightArray, leftArray.length);
  4735. }
  4736. return array;
  4737. }
  4738. function expand(inputArray, length) {
  4739. if (length && length > inputArray.length) {
  4740. const array = inputArray;
  4741. inputArray = new Uint8Array(length);
  4742. inputArray.set(array, 0);
  4743. }
  4744. return inputArray;
  4745. }
  4746. function subarray(array, begin, end) {
  4747. return array.subarray(begin, end);
  4748. }
  4749. /*
  4750. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  4751. Redistribution and use in source and binary forms, with or without
  4752. modification, are permitted provided that the following conditions are met:
  4753. 1. Redistributions of source code must retain the above copyright notice,
  4754. this list of conditions and the following disclaimer.
  4755. 2. Redistributions in binary form must reproduce the above copyright
  4756. notice, this list of conditions and the following disclaimer in
  4757. the documentation and/or other materials provided with the distribution.
  4758. 3. The names of the authors may not be used to endorse or promote products
  4759. derived from this software without specific prior written permission.
  4760. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  4761. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  4762. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  4763. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  4764. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4765. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  4766. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  4767. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  4768. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  4769. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4770. */
  4771. const HEADER_LENGTH = 12;
  4772. class ZipCryptoDecrypt {
  4773. constructor(password, passwordVerification) {
  4774. const zipCrypto = this;
  4775. Object.assign(zipCrypto, {
  4776. password,
  4777. passwordVerification
  4778. });
  4779. createKeys(zipCrypto, password);
  4780. }
  4781. append(input) {
  4782. const zipCrypto = this;
  4783. if (zipCrypto.password) {
  4784. const decryptedHeader = decrypt(zipCrypto, input.subarray(0, HEADER_LENGTH));
  4785. zipCrypto.password = null;
  4786. if (decryptedHeader[HEADER_LENGTH - 1] != zipCrypto.passwordVerification) {
  4787. throw new Error(ERR_INVALID_PASSWORD);
  4788. }
  4789. input = input.subarray(HEADER_LENGTH);
  4790. }
  4791. return decrypt(zipCrypto, input);
  4792. }
  4793. flush() {
  4794. return {
  4795. valid: true,
  4796. data: new Uint8Array(0)
  4797. };
  4798. }
  4799. }
  4800. class ZipCryptoEncrypt {
  4801. constructor(password, passwordVerification) {
  4802. const zipCrypto = this;
  4803. Object.assign(zipCrypto, {
  4804. password,
  4805. passwordVerification
  4806. });
  4807. createKeys(zipCrypto, password);
  4808. }
  4809. append(input) {
  4810. const zipCrypto = this;
  4811. let output;
  4812. let offset;
  4813. if (zipCrypto.password) {
  4814. zipCrypto.password = null;
  4815. const header = crypto.getRandomValues(new Uint8Array(HEADER_LENGTH));
  4816. header[HEADER_LENGTH - 1] = zipCrypto.passwordVerification;
  4817. output = new Uint8Array(input.length + header.length);
  4818. output.set(encrypt(zipCrypto, header), 0);
  4819. offset = HEADER_LENGTH;
  4820. } else {
  4821. output = new Uint8Array(input.length);
  4822. offset = 0;
  4823. }
  4824. output.set(encrypt(zipCrypto, input), offset);
  4825. return output;
  4826. }
  4827. flush() {
  4828. return {
  4829. data: new Uint8Array(0)
  4830. };
  4831. }
  4832. }
  4833. function decrypt(target, input) {
  4834. const output = new Uint8Array(input.length);
  4835. for (let index = 0; index < input.length; index++) {
  4836. output[index] = getByte(target) ^ input[index];
  4837. updateKeys(target, output[index]);
  4838. }
  4839. return output;
  4840. }
  4841. function encrypt(target, input) {
  4842. const output = new Uint8Array(input.length);
  4843. for (let index = 0; index < input.length; index++) {
  4844. output[index] = getByte(target) ^ input[index];
  4845. updateKeys(target, input[index]);
  4846. }
  4847. return output;
  4848. }
  4849. function createKeys(target, password) {
  4850. target.keys = [0x12345678, 0x23456789, 0x34567890];
  4851. target.crcKey0 = new Crc32(target.keys[0]);
  4852. target.crcKey2 = new Crc32(target.keys[2]);
  4853. for (let index = 0; index < password.length; index++) {
  4854. updateKeys(target, password.charCodeAt(index));
  4855. }
  4856. }
  4857. function updateKeys(target, byte) {
  4858. target.crcKey0.append([byte]);
  4859. target.keys[0] = ~target.crcKey0.get();
  4860. target.keys[1] = getInt32(target.keys[1] + getInt8(target.keys[0]));
  4861. target.keys[1] = getInt32(Math.imul(target.keys[1], 134775813) + 1);
  4862. target.crcKey2.append([target.keys[1] >>> 24]);
  4863. target.keys[2] = ~target.crcKey2.get();
  4864. }
  4865. function getByte(target) {
  4866. const temp = target.keys[2] | 2;
  4867. return getInt8(Math.imul(temp, (temp ^ 1)) >>> 8);
  4868. }
  4869. function getInt8(number) {
  4870. return number & 0xFF;
  4871. }
  4872. function getInt32(number) {
  4873. return number & 0xFFFFFFFF;
  4874. }
  4875. /*
  4876. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  4877. Redistribution and use in source and binary forms, with or without
  4878. modification, are permitted provided that the following conditions are met:
  4879. 1. Redistributions of source code must retain the above copyright notice,
  4880. this list of conditions and the following disclaimer.
  4881. 2. Redistributions in binary form must reproduce the above copyright
  4882. notice, this list of conditions and the following disclaimer in
  4883. the documentation and/or other materials provided with the distribution.
  4884. 3. The names of the authors may not be used to endorse or promote products
  4885. derived from this software without specific prior written permission.
  4886. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  4887. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  4888. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  4889. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  4890. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4891. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  4892. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  4893. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  4894. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  4895. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4896. */
  4897. const CODEC_DEFLATE = "deflate";
  4898. const CODEC_INFLATE = "inflate";
  4899. const ERR_INVALID_SIGNATURE = "Invalid signature";
  4900. class Inflate {
  4901. constructor(codecConstructor, {
  4902. signature,
  4903. password,
  4904. signed,
  4905. compressed,
  4906. zipCrypto,
  4907. passwordVerification,
  4908. encryptionStrength
  4909. }, { chunkSize }) {
  4910. const encrypted = Boolean(password);
  4911. Object.assign(this, {
  4912. signature,
  4913. encrypted,
  4914. signed,
  4915. compressed,
  4916. inflate: compressed && new codecConstructor({ chunkSize }),
  4917. crc32: signed && new Crc32(),
  4918. zipCrypto,
  4919. decrypt: encrypted && zipCrypto ?
  4920. new ZipCryptoDecrypt(password, passwordVerification) :
  4921. new AESDecrypt(password, signed, encryptionStrength)
  4922. });
  4923. }
  4924. async append(data) {
  4925. const codec = this;
  4926. if (codec.encrypted && data.length) {
  4927. data = await codec.decrypt.append(data);
  4928. }
  4929. if (codec.compressed && data.length) {
  4930. data = await codec.inflate.append(data);
  4931. }
  4932. if ((!codec.encrypted || codec.zipCrypto) && codec.signed && data.length) {
  4933. codec.crc32.append(data);
  4934. }
  4935. return data;
  4936. }
  4937. async flush() {
  4938. const codec = this;
  4939. let signature;
  4940. let data = new Uint8Array(0);
  4941. if (codec.encrypted) {
  4942. const result = codec.decrypt.flush();
  4943. if (!result.valid) {
  4944. throw new Error(ERR_INVALID_SIGNATURE);
  4945. }
  4946. data = result.data;
  4947. }
  4948. if ((!codec.encrypted || codec.zipCrypto) && codec.signed) {
  4949. const dataViewSignature = new DataView(new Uint8Array(4).buffer);
  4950. signature = codec.crc32.get();
  4951. dataViewSignature.setUint32(0, signature);
  4952. if (codec.signature != dataViewSignature.getUint32(0, false)) {
  4953. throw new Error(ERR_INVALID_SIGNATURE);
  4954. }
  4955. }
  4956. if (codec.compressed) {
  4957. data = (await codec.inflate.append(data)) || new Uint8Array(0);
  4958. await codec.inflate.flush();
  4959. }
  4960. return { data, signature };
  4961. }
  4962. }
  4963. class Deflate {
  4964. constructor(codecConstructor, {
  4965. encrypted,
  4966. signed,
  4967. compressed,
  4968. level,
  4969. zipCrypto,
  4970. password,
  4971. passwordVerification,
  4972. encryptionStrength
  4973. }, { chunkSize }) {
  4974. Object.assign(this, {
  4975. encrypted,
  4976. signed,
  4977. compressed,
  4978. deflate: compressed && new codecConstructor({ level: level || 5, chunkSize }),
  4979. crc32: signed && new Crc32(),
  4980. zipCrypto,
  4981. encrypt: encrypted && zipCrypto ?
  4982. new ZipCryptoEncrypt(password, passwordVerification) :
  4983. new AESEncrypt(password, encryptionStrength)
  4984. });
  4985. }
  4986. async append(inputData) {
  4987. const codec = this;
  4988. let data = inputData;
  4989. if (codec.compressed && inputData.length) {
  4990. data = await codec.deflate.append(inputData);
  4991. }
  4992. if (codec.encrypted && data.length) {
  4993. data = await codec.encrypt.append(data);
  4994. }
  4995. if ((!codec.encrypted || codec.zipCrypto) && codec.signed && inputData.length) {
  4996. codec.crc32.append(inputData);
  4997. }
  4998. return data;
  4999. }
  5000. async flush() {
  5001. const codec = this;
  5002. let signature;
  5003. let data = new Uint8Array(0);
  5004. if (codec.compressed) {
  5005. data = (await codec.deflate.flush()) || new Uint8Array(0);
  5006. }
  5007. if (codec.encrypted) {
  5008. data = await codec.encrypt.append(data);
  5009. const result = codec.encrypt.flush();
  5010. signature = result.signature;
  5011. const newData = new Uint8Array(data.length + result.data.length);
  5012. newData.set(data, 0);
  5013. newData.set(result.data, data.length);
  5014. data = newData;
  5015. }
  5016. if ((!codec.encrypted || codec.zipCrypto) && codec.signed) {
  5017. signature = codec.crc32.get();
  5018. }
  5019. return { data, signature };
  5020. }
  5021. }
  5022. function createCodec$1(codecConstructor, options, config) {
  5023. if (options.codecType.startsWith(CODEC_DEFLATE)) {
  5024. return new Deflate(codecConstructor, options, config);
  5025. } else if (options.codecType.startsWith(CODEC_INFLATE)) {
  5026. return new Inflate(codecConstructor, options, config);
  5027. }
  5028. }
  5029. /*
  5030. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  5031. Redistribution and use in source and binary forms, with or without
  5032. modification, are permitted provided that the following conditions are met:
  5033. 1. Redistributions of source code must retain the above copyright notice,
  5034. this list of conditions and the following disclaimer.
  5035. 2. Redistributions in binary form must reproduce the above copyright
  5036. notice, this list of conditions and the following disclaimer in
  5037. the documentation and/or other materials provided with the distribution.
  5038. 3. The names of the authors may not be used to endorse or promote products
  5039. derived from this software without specific prior written permission.
  5040. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  5041. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  5042. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  5043. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  5044. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5045. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  5046. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  5047. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  5048. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  5049. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5050. */
  5051. const MESSAGE_INIT = "init";
  5052. const MESSAGE_APPEND = "append";
  5053. const MESSAGE_FLUSH = "flush";
  5054. const MESSAGE_EVENT_TYPE = "message";
  5055. let classicWorkersSupported = true;
  5056. var getWorker = (workerData, codecConstructor, options, config, onTaskFinished, webWorker, scripts) => {
  5057. Object.assign(workerData, {
  5058. busy: true,
  5059. codecConstructor,
  5060. options: Object.assign({}, options),
  5061. scripts,
  5062. terminate() {
  5063. if (workerData.worker && !workerData.busy) {
  5064. workerData.worker.terminate();
  5065. workerData.interface = null;
  5066. }
  5067. },
  5068. onTaskFinished() {
  5069. workerData.busy = false;
  5070. onTaskFinished(workerData);
  5071. }
  5072. });
  5073. return webWorker ? createWebWorkerInterface(workerData, config) : createWorkerInterface(workerData, config);
  5074. };
  5075. function createWorkerInterface(workerData, config) {
  5076. const interfaceCodec = createCodec$1(workerData.codecConstructor, workerData.options, config);
  5077. return {
  5078. async append(data) {
  5079. try {
  5080. return await interfaceCodec.append(data);
  5081. } catch (error) {
  5082. workerData.onTaskFinished();
  5083. throw error;
  5084. }
  5085. },
  5086. async flush() {
  5087. try {
  5088. return await interfaceCodec.flush();
  5089. } finally {
  5090. workerData.onTaskFinished();
  5091. }
  5092. },
  5093. abort() {
  5094. workerData.onTaskFinished();
  5095. }
  5096. };
  5097. }
  5098. function createWebWorkerInterface(workerData, config) {
  5099. let messageTask;
  5100. const workerOptions = { type: "module" };
  5101. if (!workerData.interface) {
  5102. if (!classicWorkersSupported) {
  5103. workerData.worker = getWorker(workerOptions, config.baseURL);
  5104. } else {
  5105. try {
  5106. workerData.worker = getWorker({}, config.baseURL);
  5107. } catch (error) {
  5108. classicWorkersSupported = false;
  5109. workerData.worker = getWorker(workerOptions, config.baseURL);
  5110. }
  5111. }
  5112. workerData.worker.addEventListener(MESSAGE_EVENT_TYPE, onMessage, false);
  5113. workerData.interface = {
  5114. append(data) {
  5115. return initAndSendMessage({ type: MESSAGE_APPEND, data });
  5116. },
  5117. flush() {
  5118. return initAndSendMessage({ type: MESSAGE_FLUSH });
  5119. },
  5120. abort() {
  5121. workerData.onTaskFinished();
  5122. }
  5123. };
  5124. }
  5125. return workerData.interface;
  5126. function getWorker(options, baseURL) {
  5127. let url, scriptUrl;
  5128. url = workerData.scripts[0];
  5129. if (typeof url == "function") {
  5130. url = url();
  5131. }
  5132. try {
  5133. scriptUrl = new URL(url, baseURL);
  5134. } catch (error) {
  5135. scriptUrl = url;
  5136. }
  5137. return new Worker(scriptUrl, options);
  5138. }
  5139. async function initAndSendMessage(message) {
  5140. if (!messageTask) {
  5141. const options = workerData.options;
  5142. const scripts = workerData.scripts.slice(1);
  5143. await sendMessage({ scripts, type: MESSAGE_INIT, options, config: { chunkSize: config.chunkSize } });
  5144. }
  5145. return sendMessage(message);
  5146. }
  5147. function sendMessage(message) {
  5148. const worker = workerData.worker;
  5149. const result = new Promise((resolve, reject) => messageTask = { resolve, reject });
  5150. try {
  5151. if (message.data) {
  5152. try {
  5153. message.data = message.data.buffer;
  5154. worker.postMessage(message, [message.data]);
  5155. } catch (error) {
  5156. worker.postMessage(message);
  5157. }
  5158. } else {
  5159. worker.postMessage(message);
  5160. }
  5161. } catch (error) {
  5162. messageTask.reject(error);
  5163. messageTask = null;
  5164. workerData.onTaskFinished();
  5165. }
  5166. return result;
  5167. }
  5168. function onMessage(event) {
  5169. const message = event.data;
  5170. if (messageTask) {
  5171. const reponseError = message.error;
  5172. const type = message.type;
  5173. if (reponseError) {
  5174. const error = new Error(reponseError.message);
  5175. error.stack = reponseError.stack;
  5176. messageTask.reject(error);
  5177. messageTask = null;
  5178. workerData.onTaskFinished();
  5179. } else if (type == MESSAGE_INIT || type == MESSAGE_FLUSH || type == MESSAGE_APPEND) {
  5180. const data = message.data;
  5181. if (type == MESSAGE_FLUSH) {
  5182. messageTask.resolve({ data: new Uint8Array(data), signature: message.signature });
  5183. messageTask = null;
  5184. workerData.onTaskFinished();
  5185. } else {
  5186. messageTask.resolve(data && new Uint8Array(data));
  5187. }
  5188. }
  5189. }
  5190. }
  5191. }
  5192. /*
  5193. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  5194. Redistribution and use in source and binary forms, with or without
  5195. modification, are permitted provided that the following conditions are met:
  5196. 1. Redistributions of source code must retain the above copyright notice,
  5197. this list of conditions and the following disclaimer.
  5198. 2. Redistributions in binary form must reproduce the above copyright
  5199. notice, this list of conditions and the following disclaimer in
  5200. the documentation and/or other materials provided with the distribution.
  5201. 3. The names of the authors may not be used to endorse or promote products
  5202. derived from this software without specific prior written permission.
  5203. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  5204. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  5205. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  5206. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  5207. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5208. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  5209. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  5210. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  5211. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  5212. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5213. */
  5214. let pool = [];
  5215. let pendingRequests = [];
  5216. function createCodec(codecConstructor, options, config) {
  5217. const streamCopy = !options.compressed && !options.signed && !options.encrypted;
  5218. const webWorker = !streamCopy && (options.useWebWorkers || (options.useWebWorkers === undefined && config.useWebWorkers));
  5219. const scripts = webWorker && config.workerScripts ? config.workerScripts[options.codecType] : [];
  5220. if (pool.length < config.maxWorkers) {
  5221. const workerData = {};
  5222. pool.push(workerData);
  5223. return getWorker(workerData, codecConstructor, options, config, onTaskFinished, webWorker, scripts);
  5224. } else {
  5225. const workerData = pool.find(workerData => !workerData.busy);
  5226. if (workerData) {
  5227. clearTerminateTimeout(workerData);
  5228. return getWorker(workerData, codecConstructor, options, config, onTaskFinished, webWorker, scripts);
  5229. } else {
  5230. return new Promise(resolve => pendingRequests.push({ resolve, codecConstructor, options, webWorker, scripts }));
  5231. }
  5232. }
  5233. function onTaskFinished(workerData) {
  5234. if (pendingRequests.length) {
  5235. const [{ resolve, codecConstructor, options, webWorker, scripts }] = pendingRequests.splice(0, 1);
  5236. resolve(getWorker(workerData, codecConstructor, options, config, onTaskFinished, webWorker, scripts));
  5237. } else if (workerData.worker) {
  5238. clearTerminateTimeout(workerData);
  5239. if (Number.isFinite(config.terminateWorkerTimeout) && config.terminateWorkerTimeout >= 0) {
  5240. workerData.terminateTimeout = setTimeout(() => {
  5241. pool = pool.filter(data => data != workerData);
  5242. workerData.terminate();
  5243. }, config.terminateWorkerTimeout);
  5244. }
  5245. } else {
  5246. pool = pool.filter(data => data != workerData);
  5247. }
  5248. }
  5249. }
  5250. function clearTerminateTimeout(workerData) {
  5251. if (workerData.terminateTimeout) {
  5252. clearTimeout(workerData.terminateTimeout);
  5253. workerData.terminateTimeout = null;
  5254. }
  5255. }
  5256. function terminateWorkers() {
  5257. pool.forEach(workerData => {
  5258. clearTerminateTimeout(workerData);
  5259. workerData.terminate();
  5260. });
  5261. }
  5262. /*
  5263. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  5264. Redistribution and use in source and binary forms, with or without
  5265. modification, are permitted provided that the following conditions are met:
  5266. 1. Redistributions of source code must retain the above copyright notice,
  5267. this list of conditions and the following disclaimer.
  5268. 2. Redistributions in binary form must reproduce the above copyright
  5269. notice, this list of conditions and the following disclaimer in
  5270. the documentation and/or other materials provided with the distribution.
  5271. 3. The names of the authors may not be used to endorse or promote products
  5272. derived from this software without specific prior written permission.
  5273. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  5274. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  5275. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  5276. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  5277. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5278. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  5279. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  5280. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  5281. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  5282. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5283. */
  5284. const MINIMUM_CHUNK_SIZE = 64;
  5285. const ERR_ABORT = "Abort error";
  5286. async function processData(codec, reader, writer, offset, inputLength, config, options) {
  5287. const chunkSize = Math.max(config.chunkSize, MINIMUM_CHUNK_SIZE);
  5288. return processChunk();
  5289. async function processChunk(chunkOffset = 0, outputLength = 0) {
  5290. const signal = options.signal;
  5291. if (chunkOffset < inputLength) {
  5292. testAborted(signal, codec);
  5293. const inputData = await reader.readUint8Array(chunkOffset + offset, Math.min(chunkSize, inputLength - chunkOffset));
  5294. const chunkLength = inputData.length;
  5295. testAborted(signal, codec);
  5296. const data = await codec.append(inputData);
  5297. testAborted(signal, codec);
  5298. outputLength += await writeData(writer, data);
  5299. if (options.onprogress) {
  5300. try {
  5301. options.onprogress(chunkOffset + chunkLength, inputLength);
  5302. } catch (error) {
  5303. // ignored
  5304. }
  5305. }
  5306. return processChunk(chunkOffset + chunkSize, outputLength);
  5307. } else {
  5308. const result = await codec.flush();
  5309. outputLength += await writeData(writer, result.data);
  5310. return { signature: result.signature, length: outputLength };
  5311. }
  5312. }
  5313. }
  5314. function testAborted(signal, codec) {
  5315. if (signal && signal.aborted) {
  5316. codec.abort();
  5317. throw new Error(ERR_ABORT);
  5318. }
  5319. }
  5320. async function writeData(writer, data) {
  5321. if (data.length) {
  5322. await writer.writeUint8Array(data);
  5323. }
  5324. return data.length;
  5325. }
  5326. /*
  5327. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  5328. Redistribution and use in source and binary forms, with or without
  5329. modification, are permitted provided that the following conditions are met:
  5330. 1. Redistributions of source code must retain the above copyright notice,
  5331. this list of conditions and the following disclaimer.
  5332. 2. Redistributions in binary form must reproduce the above copyright
  5333. notice, this list of conditions and the following disclaimer in
  5334. the documentation and/or other materials provided with the distribution.
  5335. 3. The names of the authors may not be used to endorse or promote products
  5336. derived from this software without specific prior written permission.
  5337. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  5338. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  5339. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  5340. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  5341. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5342. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  5343. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  5344. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  5345. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  5346. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5347. */
  5348. /* global Blob, FileReader, atob, btoa, XMLHttpRequest, document, fetch */
  5349. const ERR_HTTP_STATUS = "HTTP error ";
  5350. const ERR_HTTP_RANGE = "HTTP Range not supported";
  5351. const CONTENT_TYPE_TEXT_PLAIN = "text/plain";
  5352. const HTTP_HEADER_CONTENT_LENGTH = "Content-Length";
  5353. const HTTP_HEADER_CONTENT_RANGE = "Content-Range";
  5354. const HTTP_HEADER_ACCEPT_RANGES = "Accept-Ranges";
  5355. const HTTP_HEADER_RANGE = "Range";
  5356. const HTTP_METHOD_HEAD = "HEAD";
  5357. const HTTP_METHOD_GET = "GET";
  5358. const HTTP_RANGE_UNIT = "bytes";
  5359. class Stream {
  5360. constructor() {
  5361. this.size = 0;
  5362. }
  5363. init() {
  5364. this.initialized = true;
  5365. }
  5366. }
  5367. class Reader extends Stream {
  5368. }
  5369. class Writer extends Stream {
  5370. writeUint8Array(array) {
  5371. this.size += array.length;
  5372. }
  5373. }
  5374. class TextReader extends Reader {
  5375. constructor(text) {
  5376. super();
  5377. this.blobReader = new BlobReader(new Blob([text], { type: CONTENT_TYPE_TEXT_PLAIN }));
  5378. }
  5379. async init() {
  5380. super.init();
  5381. this.blobReader.init();
  5382. this.size = this.blobReader.size;
  5383. }
  5384. async readUint8Array(offset, length) {
  5385. return this.blobReader.readUint8Array(offset, length);
  5386. }
  5387. }
  5388. class TextWriter extends Writer {
  5389. constructor(encoding) {
  5390. super();
  5391. this.encoding = encoding;
  5392. this.blob = new Blob([], { type: CONTENT_TYPE_TEXT_PLAIN });
  5393. }
  5394. async writeUint8Array(array) {
  5395. super.writeUint8Array(array);
  5396. this.blob = new Blob([this.blob, array.buffer], { type: CONTENT_TYPE_TEXT_PLAIN });
  5397. }
  5398. getData() {
  5399. if (this.blob.text) {
  5400. return this.blob.text();
  5401. } else {
  5402. const reader = new FileReader();
  5403. return new Promise((resolve, reject) => {
  5404. reader.onload = event => resolve(event.target.result);
  5405. reader.onerror = () => reject(reader.error);
  5406. reader.readAsText(this.blob, this.encoding);
  5407. });
  5408. }
  5409. }
  5410. }
  5411. class Data64URIReader extends Reader {
  5412. constructor(dataURI) {
  5413. super();
  5414. this.dataURI = dataURI;
  5415. let dataEnd = dataURI.length;
  5416. while (dataURI.charAt(dataEnd - 1) == "=") {
  5417. dataEnd--;
  5418. }
  5419. this.dataStart = dataURI.indexOf(",") + 1;
  5420. this.size = Math.floor((dataEnd - this.dataStart) * 0.75);
  5421. }
  5422. async readUint8Array(offset, length) {
  5423. const dataArray = new Uint8Array(length);
  5424. const start = Math.floor(offset / 3) * 4;
  5425. const bytes = atob(this.dataURI.substring(start + this.dataStart, Math.ceil((offset + length) / 3) * 4 + this.dataStart));
  5426. const delta = offset - Math.floor(start / 4) * 3;
  5427. for (let indexByte = delta; indexByte < delta + length; indexByte++) {
  5428. dataArray[indexByte - delta] = bytes.charCodeAt(indexByte);
  5429. }
  5430. return dataArray;
  5431. }
  5432. }
  5433. class Data64URIWriter extends Writer {
  5434. constructor(contentType) {
  5435. super();
  5436. this.data = "data:" + (contentType || "") + ";base64,";
  5437. this.pending = [];
  5438. }
  5439. async writeUint8Array(array) {
  5440. super.writeUint8Array(array);
  5441. let indexArray = 0;
  5442. let dataString = this.pending;
  5443. const delta = this.pending.length;
  5444. this.pending = "";
  5445. for (indexArray = 0; indexArray < (Math.floor((delta + array.length) / 3) * 3) - delta; indexArray++) {
  5446. dataString += String.fromCharCode(array[indexArray]);
  5447. }
  5448. for (; indexArray < array.length; indexArray++) {
  5449. this.pending += String.fromCharCode(array[indexArray]);
  5450. }
  5451. if (dataString.length > 2) {
  5452. this.data += btoa(dataString);
  5453. } else {
  5454. this.pending = dataString;
  5455. }
  5456. }
  5457. getData() {
  5458. return this.data + btoa(this.pending);
  5459. }
  5460. }
  5461. class BlobReader extends Reader {
  5462. constructor(blob) {
  5463. super();
  5464. this.blob = blob;
  5465. this.size = blob.size;
  5466. }
  5467. async readUint8Array(offset, length) {
  5468. if (this.blob.arrayBuffer) {
  5469. return new Uint8Array(await this.blob.slice(offset, offset + length).arrayBuffer());
  5470. } else {
  5471. const reader = new FileReader();
  5472. return new Promise((resolve, reject) => {
  5473. reader.onload = event => resolve(new Uint8Array(event.target.result));
  5474. reader.onerror = () => reject(reader.error);
  5475. reader.readAsArrayBuffer(this.blob.slice(offset, offset + length));
  5476. });
  5477. }
  5478. }
  5479. }
  5480. class BlobWriter extends Writer {
  5481. constructor(contentType) {
  5482. super();
  5483. this.contentType = contentType;
  5484. this.arrayBuffersMaxlength = 8;
  5485. initArrayBuffers(this);
  5486. }
  5487. async writeUint8Array(array) {
  5488. super.writeUint8Array(array);
  5489. if (this.arrayBuffers.length == this.arrayBuffersMaxlength) {
  5490. flushArrayBuffers(this);
  5491. }
  5492. this.arrayBuffers.push(array.buffer);
  5493. }
  5494. getData() {
  5495. if (!this.blob) {
  5496. if (this.arrayBuffers.length) {
  5497. flushArrayBuffers(this);
  5498. }
  5499. this.blob = this.pendingBlob;
  5500. initArrayBuffers(this);
  5501. }
  5502. return this.blob;
  5503. }
  5504. }
  5505. function initArrayBuffers(blobWriter) {
  5506. blobWriter.pendingBlob = new Blob([], { type: blobWriter.contentType });
  5507. blobWriter.arrayBuffers = [];
  5508. }
  5509. function flushArrayBuffers(blobWriter) {
  5510. blobWriter.pendingBlob = new Blob([blobWriter.pendingBlob, ...blobWriter.arrayBuffers], { type: blobWriter.contentType });
  5511. blobWriter.arrayBuffers = [];
  5512. }
  5513. class WritableStreamWriter extends Writer {
  5514. constructor(writableStream) {
  5515. super();
  5516. this.writableStream = writableStream;
  5517. this.writer = writableStream.getWriter();
  5518. }
  5519. async writeUint8Array(array) {
  5520. await this.writer.ready;
  5521. return this.writer.write(array);
  5522. }
  5523. async getData() {
  5524. await this.writer.ready;
  5525. await this.writer.close();
  5526. return this.writableStream;
  5527. }
  5528. }
  5529. class FetchReader extends Reader {
  5530. constructor(url, options) {
  5531. super();
  5532. this.url = url;
  5533. this.preventHeadRequest = options.preventHeadRequest;
  5534. this.useRangeHeader = options.useRangeHeader;
  5535. this.forceRangeRequests = options.forceRangeRequests;
  5536. this.options = Object.assign({}, options);
  5537. delete this.options.preventHeadRequest;
  5538. delete this.options.useRangeHeader;
  5539. delete this.options.forceRangeRequests;
  5540. delete this.options.useXHR;
  5541. }
  5542. async init() {
  5543. super.init();
  5544. await initHttpReader(this, sendFetchRequest, getFetchRequestData);
  5545. }
  5546. async readUint8Array(index, length) {
  5547. return readUint8ArrayHttpReader(this, index, length, sendFetchRequest, getFetchRequestData);
  5548. }
  5549. }
  5550. class XHRReader extends Reader {
  5551. constructor(url, options) {
  5552. super();
  5553. this.url = url;
  5554. this.preventHeadRequest = options.preventHeadRequest;
  5555. this.useRangeHeader = options.useRangeHeader;
  5556. this.forceRangeRequests = options.forceRangeRequests;
  5557. this.options = options;
  5558. }
  5559. async init() {
  5560. super.init();
  5561. await initHttpReader(this, sendXMLHttpRequest, getXMLHttpRequestData);
  5562. }
  5563. async readUint8Array(index, length) {
  5564. return readUint8ArrayHttpReader(this, index, length, sendXMLHttpRequest, getXMLHttpRequestData);
  5565. }
  5566. }
  5567. async function initHttpReader(httpReader, sendRequest, getRequestData) {
  5568. if (isHttpFamily(httpReader.url) && (httpReader.useRangeHeader || httpReader.forceRangeRequests)) {
  5569. const response = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader));
  5570. if (!httpReader.forceRangeRequests && response.headers.get(HTTP_HEADER_ACCEPT_RANGES) != HTTP_RANGE_UNIT) {
  5571. throw new Error(ERR_HTTP_RANGE);
  5572. } else {
  5573. let contentSize;
  5574. const contentRangeHeader = response.headers.get(HTTP_HEADER_CONTENT_RANGE);
  5575. if (contentRangeHeader) {
  5576. const splitHeader = contentRangeHeader.trim().split(/\s*\/\s*/);
  5577. if (splitHeader.length) {
  5578. const headerValue = splitHeader[1];
  5579. if (headerValue && headerValue != "*") {
  5580. contentSize = Number(headerValue);
  5581. }
  5582. }
  5583. }
  5584. if (contentSize === undefined) {
  5585. await getContentLength(httpReader, sendRequest, getRequestData);
  5586. } else {
  5587. httpReader.size = contentSize;
  5588. }
  5589. }
  5590. } else {
  5591. await getContentLength(httpReader, sendRequest, getRequestData);
  5592. }
  5593. }
  5594. async function readUint8ArrayHttpReader(httpReader, index, length, sendRequest, getRequestData) {
  5595. if (httpReader.useRangeHeader || httpReader.forceRangeRequests) {
  5596. const response = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader, index, length));
  5597. if (response.status != 206) {
  5598. throw new Error(ERR_HTTP_RANGE);
  5599. }
  5600. return new Uint8Array(await response.arrayBuffer());
  5601. } else {
  5602. if (!httpReader.data) {
  5603. await getRequestData(httpReader, httpReader.options);
  5604. }
  5605. return new Uint8Array(httpReader.data.subarray(index, index + length));
  5606. }
  5607. }
  5608. function getRangeHeaders(httpReader, index = 0, length = 1) {
  5609. return Object.assign({}, getHeaders(httpReader), { [HTTP_HEADER_RANGE]: HTTP_RANGE_UNIT + "=" + index + "-" + (index + length - 1) });
  5610. }
  5611. function getHeaders(httpReader) {
  5612. let headers = httpReader.options.headers;
  5613. if (headers) {
  5614. if (Symbol.iterator in headers) {
  5615. return Object.fromEntries(headers);
  5616. } else {
  5617. return headers;
  5618. }
  5619. }
  5620. }
  5621. async function getFetchRequestData(httpReader) {
  5622. await getRequestData(httpReader, sendFetchRequest);
  5623. }
  5624. async function getXMLHttpRequestData(httpReader) {
  5625. await getRequestData(httpReader, sendXMLHttpRequest);
  5626. }
  5627. async function getRequestData(httpReader, sendRequest) {
  5628. const response = await sendRequest(HTTP_METHOD_GET, httpReader, getHeaders(httpReader));
  5629. httpReader.data = new Uint8Array(await response.arrayBuffer());
  5630. if (!httpReader.size) {
  5631. httpReader.size = httpReader.data.length;
  5632. }
  5633. }
  5634. async function getContentLength(httpReader, sendRequest, getRequestData) {
  5635. if (httpReader.preventHeadRequest) {
  5636. await getRequestData(httpReader, httpReader.options);
  5637. } else {
  5638. const response = await sendRequest(HTTP_METHOD_HEAD, httpReader, getHeaders(httpReader));
  5639. const contentLength = response.headers.get(HTTP_HEADER_CONTENT_LENGTH);
  5640. if (contentLength) {
  5641. httpReader.size = Number(contentLength);
  5642. } else {
  5643. await getRequestData(httpReader, httpReader.options);
  5644. }
  5645. }
  5646. }
  5647. async function sendFetchRequest(method, { options, url }, headers) {
  5648. const response = await fetch(url, Object.assign({}, options, { method, headers }));
  5649. if (response.status < 400) {
  5650. return response;
  5651. } else {
  5652. throw new Error(ERR_HTTP_STATUS + (response.statusText || response.status));
  5653. }
  5654. }
  5655. function sendXMLHttpRequest(method, { url }, headers) {
  5656. return new Promise((resolve, reject) => {
  5657. const request = new XMLHttpRequest();
  5658. request.addEventListener("load", () => {
  5659. if (request.status < 400) {
  5660. const headers = [];
  5661. request.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(header => {
  5662. const splitHeader = header.trim().split(/\s*:\s*/);
  5663. splitHeader[0] = splitHeader[0].trim().replace(/^[a-z]|-[a-z]/g, value => value.toUpperCase());
  5664. headers.push(splitHeader);
  5665. });
  5666. resolve({
  5667. status: request.status,
  5668. arrayBuffer: () => request.response,
  5669. headers: new Map(headers)
  5670. });
  5671. } else {
  5672. reject(new Error(ERR_HTTP_STATUS + (request.statusText || request.status)));
  5673. }
  5674. }, false);
  5675. request.addEventListener("error", event => reject(event.detail.error), false);
  5676. request.open(method, url);
  5677. if (headers) {
  5678. for (const entry of Object.entries(headers)) {
  5679. request.setRequestHeader(entry[0], entry[1]);
  5680. }
  5681. }
  5682. request.responseType = "arraybuffer";
  5683. request.send();
  5684. });
  5685. }
  5686. class HttpReader extends Reader {
  5687. constructor(url, options = {}) {
  5688. super();
  5689. this.url = url;
  5690. if (options.useXHR) {
  5691. this.reader = new XHRReader(url, options);
  5692. } else {
  5693. this.reader = new FetchReader(url, options);
  5694. }
  5695. }
  5696. set size(value) {
  5697. // ignored
  5698. }
  5699. get size() {
  5700. return this.reader.size;
  5701. }
  5702. async init() {
  5703. super.init();
  5704. await this.reader.init();
  5705. }
  5706. async readUint8Array(index, length) {
  5707. return this.reader.readUint8Array(index, length);
  5708. }
  5709. }
  5710. class HttpRangeReader extends HttpReader {
  5711. constructor(url, options = {}) {
  5712. options.useRangeHeader = true;
  5713. super(url, options);
  5714. }
  5715. }
  5716. class Uint8ArrayReader extends Reader {
  5717. constructor(array) {
  5718. super();
  5719. this.array = array;
  5720. this.size = array.length;
  5721. }
  5722. async readUint8Array(index, length) {
  5723. return this.array.slice(index, index + length);
  5724. }
  5725. }
  5726. class Uint8ArrayWriter extends Writer {
  5727. constructor() {
  5728. super();
  5729. this.array = new Uint8Array(0);
  5730. }
  5731. async writeUint8Array(array) {
  5732. super.writeUint8Array(array);
  5733. const previousArray = this.array;
  5734. this.array = new Uint8Array(previousArray.length + array.length);
  5735. this.array.set(previousArray);
  5736. this.array.set(array, previousArray.length);
  5737. }
  5738. getData() {
  5739. return this.array;
  5740. }
  5741. }
  5742. function isHttpFamily(url) {
  5743. if (typeof document != "undefined") {
  5744. const anchor = document.createElement("a");
  5745. anchor.href = url;
  5746. return anchor.protocol == "http:" || anchor.protocol == "https:";
  5747. } else {
  5748. return /^https?:\/\//i.test(url);
  5749. }
  5750. }
  5751. /*
  5752. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  5753. Redistribution and use in source and binary forms, with or without
  5754. modification, are permitted provided that the following conditions are met:
  5755. 1. Redistributions of source code must retain the above copyright notice,
  5756. this list of conditions and the following disclaimer.
  5757. 2. Redistributions in binary form must reproduce the above copyright
  5758. notice, this list of conditions and the following disclaimer in
  5759. the documentation and/or other materials provided with the distribution.
  5760. 3. The names of the authors may not be used to endorse or promote products
  5761. derived from this software without specific prior written permission.
  5762. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  5763. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  5764. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  5765. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  5766. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5767. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  5768. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  5769. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  5770. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  5771. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5772. */
  5773. const MAX_32_BITS = 0xffffffff;
  5774. const MAX_16_BITS = 0xffff;
  5775. const COMPRESSION_METHOD_DEFLATE = 0x08;
  5776. const COMPRESSION_METHOD_STORE = 0x00;
  5777. const COMPRESSION_METHOD_AES = 0x63;
  5778. const LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50;
  5779. const DATA_DESCRIPTOR_RECORD_SIGNATURE = 0x08074b50;
  5780. const CENTRAL_FILE_HEADER_SIGNATURE = 0x02014b50;
  5781. const END_OF_CENTRAL_DIR_SIGNATURE = 0x06054b50;
  5782. const ZIP64_END_OF_CENTRAL_DIR_SIGNATURE = 0x06064b50;
  5783. const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE = 0x07064b50;
  5784. const END_OF_CENTRAL_DIR_LENGTH = 22;
  5785. const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH = 20;
  5786. const ZIP64_END_OF_CENTRAL_DIR_LENGTH = 56;
  5787. const ZIP64_END_OF_CENTRAL_DIR_TOTAL_LENGTH = END_OF_CENTRAL_DIR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LENGTH;
  5788. const ZIP64_TOTAL_NUMBER_OF_DISKS = 1;
  5789. const EXTRAFIELD_TYPE_ZIP64 = 0x0001;
  5790. const EXTRAFIELD_TYPE_AES = 0x9901;
  5791. const EXTRAFIELD_TYPE_NTFS = 0x000a;
  5792. const EXTRAFIELD_TYPE_NTFS_TAG1 = 0x0001;
  5793. const EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP = 0x5455;
  5794. const EXTRAFIELD_TYPE_UNICODE_PATH = 0x7075;
  5795. const EXTRAFIELD_TYPE_UNICODE_COMMENT = 0x6375;
  5796. const BITFLAG_ENCRYPTED = 0x01;
  5797. const BITFLAG_LEVEL = 0x06;
  5798. const BITFLAG_DATA_DESCRIPTOR = 0x0008;
  5799. const BITFLAG_LANG_ENCODING_FLAG = 0x0800;
  5800. const FILE_ATTR_MSDOS_DIR_MASK = 0x10;
  5801. const VERSION_DEFLATE = 0x14;
  5802. const VERSION_ZIP64 = 0x2D;
  5803. const VERSION_AES = 0x33;
  5804. const DIRECTORY_SIGNATURE = "/";
  5805. const MAX_DATE = new Date(2107, 11, 31);
  5806. const MIN_DATE = new Date(1980, 0, 1);
  5807. /*
  5808. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  5809. Redistribution and use in source and binary forms, with or without
  5810. modification, are permitted provided that the following conditions are met:
  5811. 1. Redistributions of source code must retain the above copyright notice,
  5812. this list of conditions and the following disclaimer.
  5813. 2. Redistributions in binary form must reproduce the above copyright
  5814. notice, this list of conditions and the following disclaimer in
  5815. the documentation and/or other materials provided with the distribution.
  5816. 3. The names of the authors may not be used to endorse or promote products
  5817. derived from this software without specific prior written permission.
  5818. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  5819. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  5820. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  5821. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  5822. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5823. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  5824. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  5825. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  5826. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  5827. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5828. */
  5829. const CP437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ".split("");
  5830. var decodeCP437 = stringValue => {
  5831. let result = "";
  5832. for (let indexCharacter = 0; indexCharacter < stringValue.length; indexCharacter++) {
  5833. result += CP437[stringValue[indexCharacter]];
  5834. }
  5835. return result;
  5836. };
  5837. /*
  5838. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  5839. Redistribution and use in source and binary forms, with or without
  5840. modification, are permitted provided that the following conditions are met:
  5841. 1. Redistributions of source code must retain the above copyright notice,
  5842. this list of conditions and the following disclaimer.
  5843. 2. Redistributions in binary form must reproduce the above copyright
  5844. notice, this list of conditions and the following disclaimer in
  5845. the documentation and/or other materials provided with the distribution.
  5846. 3. The names of the authors may not be used to endorse or promote products
  5847. derived from this software without specific prior written permission.
  5848. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  5849. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  5850. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  5851. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  5852. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5853. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  5854. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  5855. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  5856. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  5857. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5858. */
  5859. async function decodeText(value, encoding) {
  5860. if (encoding && encoding.trim().toLowerCase() == "cp437") {
  5861. return decodeCP437(value);
  5862. } else if (typeof TextDecoder == "undefined") {
  5863. const fileReader = new FileReader();
  5864. return new Promise((resolve, reject) => {
  5865. fileReader.onload = event => resolve(event.target.result);
  5866. fileReader.onerror = () => reject(fileReader.error);
  5867. fileReader.readAsText(new Blob([value]));
  5868. });
  5869. } else {
  5870. return new TextDecoder(encoding).decode(value);
  5871. }
  5872. }
  5873. /*
  5874. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  5875. Redistribution and use in source and binary forms, with or without
  5876. modification, are permitted provided that the following conditions are met:
  5877. 1. Redistributions of source code must retain the above copyright notice,
  5878. this list of conditions and the following disclaimer.
  5879. 2. Redistributions in binary form must reproduce the above copyright
  5880. notice, this list of conditions and the following disclaimer in
  5881. the documentation and/or other materials provided with the distribution.
  5882. 3. The names of the authors may not be used to endorse or promote products
  5883. derived from this software without specific prior written permission.
  5884. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  5885. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  5886. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  5887. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  5888. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5889. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  5890. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  5891. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  5892. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  5893. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5894. */
  5895. const PROPERTY_NAMES = [
  5896. "filename", "rawFilename", "directory", "encrypted", "compressedSize", "uncompressedSize",
  5897. "lastModDate", "rawLastModDate", "comment", "rawComment", "signature", "extraField",
  5898. "rawExtraField", "bitFlag", "extraFieldZip64", "extraFieldUnicodePath", "extraFieldUnicodeComment",
  5899. "extraFieldAES", "filenameUTF8", "commentUTF8", "offset", "zip64", "compressionMethod",
  5900. "extraFieldNTFS", "lastAccessDate", "creationDate", "extraFieldExtendedTimestamp",
  5901. "version", "versionMadeBy", "msDosCompatible", "internalFileAttribute", "externalFileAttribute"];
  5902. class Entry {
  5903. constructor(data) {
  5904. PROPERTY_NAMES.forEach(name => this[name] = data[name]);
  5905. }
  5906. }
  5907. /*
  5908. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  5909. Redistribution and use in source and binary forms, with or without
  5910. modification, are permitted provided that the following conditions are met:
  5911. 1. Redistributions of source code must retain the above copyright notice,
  5912. this list of conditions and the following disclaimer.
  5913. 2. Redistributions in binary form must reproduce the above copyright
  5914. notice, this list of conditions and the following disclaimer in
  5915. the documentation and/or other materials provided with the distribution.
  5916. 3. The names of the authors may not be used to endorse or promote products
  5917. derived from this software without specific prior written permission.
  5918. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  5919. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  5920. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  5921. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  5922. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  5923. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  5924. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  5925. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  5926. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  5927. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  5928. */
  5929. const ERR_BAD_FORMAT = "File format is not recognized";
  5930. const ERR_EOCDR_NOT_FOUND = "End of central directory not found";
  5931. const ERR_EOCDR_ZIP64_NOT_FOUND = "End of Zip64 central directory not found";
  5932. const ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND = "End of Zip64 central directory locator not found";
  5933. const ERR_CENTRAL_DIRECTORY_NOT_FOUND = "Central directory header not found";
  5934. const ERR_LOCAL_FILE_HEADER_NOT_FOUND = "Local file header not found";
  5935. const ERR_EXTRAFIELD_ZIP64_NOT_FOUND = "Zip64 extra field not found";
  5936. const ERR_ENCRYPTED = "File contains encrypted entry";
  5937. const ERR_UNSUPPORTED_ENCRYPTION = "Encryption method not supported";
  5938. const ERR_UNSUPPORTED_COMPRESSION = "Compression method not supported";
  5939. const CHARSET_UTF8 = "utf-8";
  5940. const CHARSET_CP437 = "cp437";
  5941. const ZIP64_PROPERTIES = ["uncompressedSize", "compressedSize", "offset"];
  5942. class ZipReader {
  5943. constructor(reader, options = {}) {
  5944. Object.assign(this, {
  5945. reader,
  5946. options,
  5947. config: getConfiguration()
  5948. });
  5949. }
  5950. async getEntries(options = {}) {
  5951. const zipReader = this;
  5952. const reader = zipReader.reader;
  5953. if (!reader.initialized) {
  5954. await reader.init();
  5955. }
  5956. if (reader.size < END_OF_CENTRAL_DIR_LENGTH) {
  5957. throw new Error(ERR_BAD_FORMAT);
  5958. }
  5959. const endOfDirectoryInfo = await seekSignature(reader, END_OF_CENTRAL_DIR_SIGNATURE, reader.size, END_OF_CENTRAL_DIR_LENGTH, MAX_16_BITS * 16);
  5960. if (!endOfDirectoryInfo) {
  5961. throw new Error(ERR_EOCDR_NOT_FOUND);
  5962. }
  5963. const endOfDirectoryView = getDataView$1(endOfDirectoryInfo);
  5964. let directoryDataLength = getUint32(endOfDirectoryView, 12);
  5965. let directoryDataOffset = getUint32(endOfDirectoryView, 16);
  5966. let filesLength = getUint16(endOfDirectoryView, 8);
  5967. let prependedDataLength = 0;
  5968. if (directoryDataOffset == MAX_32_BITS || directoryDataLength == MAX_32_BITS || filesLength == MAX_16_BITS) {
  5969. const endOfDirectoryLocatorArray = await readUint8Array(reader, endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH);
  5970. const endOfDirectoryLocatorView = getDataView$1(endOfDirectoryLocatorArray);
  5971. if (getUint32(endOfDirectoryLocatorView, 0) != ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE) {
  5972. throw new Error(ERR_EOCDR_ZIP64_NOT_FOUND);
  5973. }
  5974. directoryDataOffset = getBigUint64(endOfDirectoryLocatorView, 8);
  5975. let endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH);
  5976. let endOfDirectoryView = getDataView$1(endOfDirectoryArray);
  5977. const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH - ZIP64_END_OF_CENTRAL_DIR_LENGTH;
  5978. if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
  5979. const originalDirectoryDataOffset = directoryDataOffset;
  5980. directoryDataOffset = expectedDirectoryDataOffset;
  5981. prependedDataLength = directoryDataOffset - originalDirectoryDataOffset;
  5982. endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH);
  5983. endOfDirectoryView = getDataView$1(endOfDirectoryArray);
  5984. }
  5985. if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE) {
  5986. throw new Error(ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND);
  5987. }
  5988. filesLength = getBigUint64(endOfDirectoryView, 32);
  5989. directoryDataLength = getBigUint64(endOfDirectoryView, 40);
  5990. directoryDataOffset -= directoryDataLength;
  5991. }
  5992. if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) {
  5993. throw new Error(ERR_BAD_FORMAT);
  5994. }
  5995. let offset = 0;
  5996. let directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength);
  5997. let directoryView = getDataView$1(directoryArray);
  5998. if (directoryDataLength) {
  5999. const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - directoryDataLength;
  6000. if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
  6001. const originalDirectoryDataOffset = directoryDataOffset;
  6002. directoryDataOffset = expectedDirectoryDataOffset;
  6003. prependedDataLength = directoryDataOffset - originalDirectoryDataOffset;
  6004. directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength);
  6005. directoryView = getDataView$1(directoryArray);
  6006. }
  6007. }
  6008. if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) {
  6009. throw new Error(ERR_BAD_FORMAT);
  6010. }
  6011. const entries = [];
  6012. for (let indexFile = 0; indexFile < filesLength; indexFile++) {
  6013. const fileEntry = new ZipEntry(reader, zipReader.config, zipReader.options);
  6014. if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE) {
  6015. throw new Error(ERR_CENTRAL_DIRECTORY_NOT_FOUND);
  6016. }
  6017. readCommonHeader(fileEntry, directoryView, offset + 6);
  6018. const languageEncodingFlag = Boolean(fileEntry.bitFlag.languageEncodingFlag);
  6019. const filenameOffset = offset + 46;
  6020. const extraFieldOffset = filenameOffset + fileEntry.filenameLength;
  6021. const commentOffset = extraFieldOffset + fileEntry.extraFieldLength;
  6022. const versionMadeBy = getUint16(directoryView, offset + 4);
  6023. const msDosCompatible = (versionMadeBy & 0) == 0;
  6024. Object.assign(fileEntry, {
  6025. versionMadeBy,
  6026. msDosCompatible,
  6027. compressedSize: 0,
  6028. uncompressedSize: 0,
  6029. commentLength: getUint16(directoryView, offset + 32),
  6030. directory: msDosCompatible && ((getUint8(directoryView, offset + 38) & FILE_ATTR_MSDOS_DIR_MASK) == FILE_ATTR_MSDOS_DIR_MASK),
  6031. offset: getUint32(directoryView, offset + 42) + prependedDataLength,
  6032. internalFileAttribute: getUint32(directoryView, offset + 34),
  6033. externalFileAttribute: getUint32(directoryView, offset + 38),
  6034. rawFilename: directoryArray.subarray(filenameOffset, extraFieldOffset),
  6035. filenameUTF8: languageEncodingFlag,
  6036. commentUTF8: languageEncodingFlag,
  6037. rawExtraField: directoryArray.subarray(extraFieldOffset, commentOffset)
  6038. });
  6039. const endOffset = commentOffset + fileEntry.commentLength;
  6040. fileEntry.rawComment = directoryArray.subarray(commentOffset, endOffset);
  6041. const filenameEncoding = getOptionValue$1(zipReader, options, "filenameEncoding");
  6042. const commentEncoding = getOptionValue$1(zipReader, options, "commentEncoding");
  6043. const [filename, comment] = await Promise.all([
  6044. decodeText(fileEntry.rawFilename, fileEntry.filenameUTF8 ? CHARSET_UTF8 : filenameEncoding || CHARSET_CP437),
  6045. decodeText(fileEntry.rawComment, fileEntry.commentUTF8 ? CHARSET_UTF8 : commentEncoding || CHARSET_CP437)
  6046. ]);
  6047. fileEntry.filename = filename;
  6048. fileEntry.comment = comment;
  6049. if (!fileEntry.directory && fileEntry.filename.endsWith(DIRECTORY_SIGNATURE)) {
  6050. fileEntry.directory = true;
  6051. }
  6052. await readCommonFooter(fileEntry, fileEntry, directoryView, offset + 6);
  6053. const entry = new Entry(fileEntry);
  6054. entry.getData = (writer, options) => fileEntry.getData(writer, entry, options);
  6055. entries.push(entry);
  6056. offset = endOffset;
  6057. if (options.onprogress) {
  6058. try {
  6059. options.onprogress(indexFile + 1, filesLength, new Entry(fileEntry));
  6060. } catch (error) {
  6061. // ignored
  6062. }
  6063. }
  6064. }
  6065. return entries;
  6066. }
  6067. async close() {
  6068. }
  6069. }
  6070. class ZipEntry {
  6071. constructor(reader, config, options) {
  6072. Object.assign(this, {
  6073. reader,
  6074. config,
  6075. options
  6076. });
  6077. }
  6078. async getData(writer, fileEntry, options = {}) {
  6079. const zipEntry = this;
  6080. const {
  6081. reader,
  6082. offset,
  6083. extraFieldAES,
  6084. compressionMethod,
  6085. config,
  6086. bitFlag,
  6087. signature,
  6088. rawLastModDate,
  6089. compressedSize
  6090. } = zipEntry;
  6091. const localDirectory = zipEntry.localDirectory = {};
  6092. if (!reader.initialized) {
  6093. await reader.init();
  6094. }
  6095. let dataArray = await readUint8Array(reader, offset, 30);
  6096. const dataView = getDataView$1(dataArray);
  6097. let password = getOptionValue$1(zipEntry, options, "password");
  6098. password = password && password.length && password;
  6099. if (extraFieldAES) {
  6100. if (extraFieldAES.originalCompressionMethod != COMPRESSION_METHOD_AES) {
  6101. throw new Error(ERR_UNSUPPORTED_COMPRESSION);
  6102. }
  6103. }
  6104. if (compressionMethod != COMPRESSION_METHOD_STORE && compressionMethod != COMPRESSION_METHOD_DEFLATE) {
  6105. throw new Error(ERR_UNSUPPORTED_COMPRESSION);
  6106. }
  6107. if (getUint32(dataView, 0) != LOCAL_FILE_HEADER_SIGNATURE) {
  6108. throw new Error(ERR_LOCAL_FILE_HEADER_NOT_FOUND);
  6109. }
  6110. readCommonHeader(localDirectory, dataView, 4);
  6111. dataArray = await readUint8Array(reader, offset, 30 + localDirectory.filenameLength + localDirectory.extraFieldLength);
  6112. localDirectory.rawExtraField = dataArray.subarray(30 + localDirectory.filenameLength);
  6113. await readCommonFooter(zipEntry, localDirectory, dataView, 4);
  6114. fileEntry.lastAccessDate = localDirectory.lastAccessDate;
  6115. fileEntry.creationDate = localDirectory.creationDate;
  6116. const encrypted = zipEntry.encrypted && localDirectory.encrypted;
  6117. const zipCrypto = encrypted && !extraFieldAES;
  6118. if (encrypted) {
  6119. if (!zipCrypto && extraFieldAES.strength === undefined) {
  6120. throw new Error(ERR_UNSUPPORTED_ENCRYPTION);
  6121. } else if (!password) {
  6122. throw new Error(ERR_ENCRYPTED);
  6123. }
  6124. }
  6125. const codec = await createCodec(config.Inflate, {
  6126. codecType: CODEC_INFLATE,
  6127. password,
  6128. zipCrypto,
  6129. encryptionStrength: extraFieldAES && extraFieldAES.strength,
  6130. signed: getOptionValue$1(zipEntry, options, "checkSignature"),
  6131. passwordVerification: zipCrypto && (bitFlag.dataDescriptor ? ((rawLastModDate >>> 8) & 0xFF) : ((signature >>> 24) & 0xFF)),
  6132. signature,
  6133. compressed: compressionMethod != 0,
  6134. encrypted,
  6135. useWebWorkers: getOptionValue$1(zipEntry, options, "useWebWorkers")
  6136. }, config);
  6137. if (!writer.initialized) {
  6138. await writer.init();
  6139. }
  6140. const signal = getOptionValue$1(zipEntry, options, "signal");
  6141. const dataOffset = offset + 30 + localDirectory.filenameLength + localDirectory.extraFieldLength;
  6142. await processData(codec, reader, writer, dataOffset, compressedSize, config, { onprogress: options.onprogress, signal });
  6143. return writer.getData();
  6144. }
  6145. }
  6146. function readCommonHeader(directory, dataView, offset) {
  6147. const rawBitFlag = directory.rawBitFlag = getUint16(dataView, offset + 2);
  6148. const encrypted = (rawBitFlag & BITFLAG_ENCRYPTED) == BITFLAG_ENCRYPTED;
  6149. const rawLastModDate = getUint32(dataView, offset + 6);
  6150. Object.assign(directory, {
  6151. encrypted,
  6152. version: getUint16(dataView, offset),
  6153. bitFlag: {
  6154. level: (rawBitFlag & BITFLAG_LEVEL) >> 1,
  6155. dataDescriptor: (rawBitFlag & BITFLAG_DATA_DESCRIPTOR) == BITFLAG_DATA_DESCRIPTOR,
  6156. languageEncodingFlag: (rawBitFlag & BITFLAG_LANG_ENCODING_FLAG) == BITFLAG_LANG_ENCODING_FLAG
  6157. },
  6158. rawLastModDate,
  6159. lastModDate: getDate(rawLastModDate),
  6160. filenameLength: getUint16(dataView, offset + 22),
  6161. extraFieldLength: getUint16(dataView, offset + 24)
  6162. });
  6163. }
  6164. async function readCommonFooter(fileEntry, directory, dataView, offset) {
  6165. const rawExtraField = directory.rawExtraField;
  6166. const extraField = directory.extraField = new Map();
  6167. const rawExtraFieldView = getDataView$1(new Uint8Array(rawExtraField));
  6168. let offsetExtraField = 0;
  6169. try {
  6170. while (offsetExtraField < rawExtraField.length) {
  6171. const type = getUint16(rawExtraFieldView, offsetExtraField);
  6172. const size = getUint16(rawExtraFieldView, offsetExtraField + 2);
  6173. extraField.set(type, {
  6174. type,
  6175. data: rawExtraField.slice(offsetExtraField + 4, offsetExtraField + 4 + size)
  6176. });
  6177. offsetExtraField += 4 + size;
  6178. }
  6179. } catch (error) {
  6180. // ignored
  6181. }
  6182. const compressionMethod = getUint16(dataView, offset + 4);
  6183. directory.signature = getUint32(dataView, offset + 10);
  6184. directory.uncompressedSize = getUint32(dataView, offset + 18);
  6185. directory.compressedSize = getUint32(dataView, offset + 14);
  6186. const extraFieldZip64 = extraField.get(EXTRAFIELD_TYPE_ZIP64);
  6187. if (extraFieldZip64) {
  6188. readExtraFieldZip64(extraFieldZip64, directory);
  6189. directory.extraFieldZip64 = extraFieldZip64;
  6190. }
  6191. const extraFieldUnicodePath = extraField.get(EXTRAFIELD_TYPE_UNICODE_PATH);
  6192. if (extraFieldUnicodePath) {
  6193. await readExtraFieldUnicode(extraFieldUnicodePath, "filename", "rawFilename", directory, fileEntry);
  6194. directory.extraFieldUnicodePath = extraFieldUnicodePath;
  6195. }
  6196. const extraFieldUnicodeComment = extraField.get(EXTRAFIELD_TYPE_UNICODE_COMMENT);
  6197. if (extraFieldUnicodeComment) {
  6198. await readExtraFieldUnicode(extraFieldUnicodeComment, "comment", "rawComment", directory, fileEntry);
  6199. directory.extraFieldUnicodeComment = extraFieldUnicodeComment;
  6200. }
  6201. const extraFieldAES = extraField.get(EXTRAFIELD_TYPE_AES);
  6202. if (extraFieldAES) {
  6203. readExtraFieldAES(extraFieldAES, directory, compressionMethod);
  6204. directory.extraFieldAES = extraFieldAES;
  6205. } else {
  6206. directory.compressionMethod = compressionMethod;
  6207. }
  6208. const extraFieldNTFS = extraField.get(EXTRAFIELD_TYPE_NTFS);
  6209. if (extraFieldNTFS) {
  6210. readExtraFieldNTFS(extraFieldNTFS, directory);
  6211. directory.extraFieldNTFS = extraFieldNTFS;
  6212. }
  6213. const extraFieldExtendedTimestamp = extraField.get(EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  6214. if (extraFieldExtendedTimestamp) {
  6215. readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory);
  6216. directory.extraFieldExtendedTimestamp = extraFieldExtendedTimestamp;
  6217. }
  6218. }
  6219. function readExtraFieldZip64(extraFieldZip64, directory) {
  6220. directory.zip64 = true;
  6221. const extraFieldView = getDataView$1(extraFieldZip64.data);
  6222. extraFieldZip64.values = [];
  6223. for (let indexValue = 0; indexValue < Math.floor(extraFieldZip64.data.length / 8); indexValue++) {
  6224. extraFieldZip64.values.push(getBigUint64(extraFieldView, 0 + indexValue * 8));
  6225. }
  6226. const missingProperties = ZIP64_PROPERTIES.filter(propertyName => directory[propertyName] == MAX_32_BITS);
  6227. for (let indexMissingProperty = 0; indexMissingProperty < missingProperties.length; indexMissingProperty++) {
  6228. extraFieldZip64[missingProperties[indexMissingProperty]] = extraFieldZip64.values[indexMissingProperty];
  6229. }
  6230. ZIP64_PROPERTIES.forEach(propertyName => {
  6231. if (directory[propertyName] == MAX_32_BITS) {
  6232. if (extraFieldZip64[propertyName] !== undefined) {
  6233. directory[propertyName] = extraFieldZip64[propertyName];
  6234. } else {
  6235. throw new Error(ERR_EXTRAFIELD_ZIP64_NOT_FOUND);
  6236. }
  6237. }
  6238. });
  6239. }
  6240. async function readExtraFieldUnicode(extraFieldUnicode, propertyName, rawPropertyName, directory, fileEntry) {
  6241. const extraFieldView = getDataView$1(extraFieldUnicode.data);
  6242. extraFieldUnicode.version = getUint8(extraFieldView, 0);
  6243. extraFieldUnicode.signature = getUint32(extraFieldView, 1);
  6244. const crc32 = new Crc32();
  6245. crc32.append(fileEntry[rawPropertyName]);
  6246. const dataViewSignature = getDataView$1(new Uint8Array(4));
  6247. dataViewSignature.setUint32(0, crc32.get(), true);
  6248. extraFieldUnicode[propertyName] = await decodeText(extraFieldUnicode.data.subarray(5));
  6249. extraFieldUnicode.valid = !fileEntry.bitFlag.languageEncodingFlag && extraFieldUnicode.signature == getUint32(dataViewSignature, 0);
  6250. if (extraFieldUnicode.valid) {
  6251. directory[propertyName] = extraFieldUnicode[propertyName];
  6252. directory[propertyName + "UTF8"] = true;
  6253. }
  6254. }
  6255. function readExtraFieldAES(extraFieldAES, directory, compressionMethod) {
  6256. const extraFieldView = getDataView$1(extraFieldAES.data);
  6257. extraFieldAES.vendorVersion = getUint8(extraFieldView, 0);
  6258. extraFieldAES.vendorId = getUint8(extraFieldView, 2);
  6259. const strength = getUint8(extraFieldView, 4);
  6260. extraFieldAES.strength = strength;
  6261. extraFieldAES.originalCompressionMethod = compressionMethod;
  6262. directory.compressionMethod = extraFieldAES.compressionMethod = getUint16(extraFieldView, 5);
  6263. }
  6264. function readExtraFieldNTFS(extraFieldNTFS, directory) {
  6265. const extraFieldView = getDataView$1(extraFieldNTFS.data);
  6266. let offsetExtraField = 4;
  6267. let tag1Data;
  6268. try {
  6269. while (offsetExtraField < extraFieldNTFS.data.length && !tag1Data) {
  6270. const tagValue = getUint16(extraFieldView, offsetExtraField);
  6271. const attributeSize = getUint16(extraFieldView, offsetExtraField + 2);
  6272. if (tagValue == EXTRAFIELD_TYPE_NTFS_TAG1) {
  6273. tag1Data = extraFieldNTFS.data.slice(offsetExtraField + 4, offsetExtraField + 4 + attributeSize);
  6274. }
  6275. offsetExtraField += 4 + attributeSize;
  6276. }
  6277. } catch (error) {
  6278. // ignored
  6279. }
  6280. try {
  6281. if (tag1Data && tag1Data.length == 24) {
  6282. const tag1View = getDataView$1(tag1Data);
  6283. const rawLastModDate = tag1View.getBigUint64(0, true);
  6284. const rawLastAccessDate = tag1View.getBigUint64(8, true);
  6285. const rawCreationDate = tag1View.getBigUint64(16, true);
  6286. Object.assign(extraFieldNTFS, {
  6287. rawLastModDate,
  6288. rawLastAccessDate,
  6289. rawCreationDate
  6290. });
  6291. const lastModDate = getDateNTFS(rawLastModDate);
  6292. const lastAccessDate = getDateNTFS(rawLastAccessDate);
  6293. const creationDate = getDateNTFS(rawCreationDate);
  6294. const extraFieldData = { lastModDate, lastAccessDate, creationDate };
  6295. Object.assign(extraFieldNTFS, extraFieldData);
  6296. Object.assign(directory, extraFieldData);
  6297. }
  6298. } catch (error) {
  6299. // ignored
  6300. }
  6301. }
  6302. function readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory) {
  6303. const extraFieldView = getDataView$1(extraFieldExtendedTimestamp.data);
  6304. const flags = getUint8(extraFieldView, 0);
  6305. const timeProperties = [];
  6306. const timeRawProperties = [];
  6307. if ((flags & 0x1) == 0x1) {
  6308. timeProperties.push("lastModDate");
  6309. timeRawProperties.push("rawLastModDate");
  6310. }
  6311. if ((flags & 0x2) == 0x2) {
  6312. timeProperties.push("lastAccessDate");
  6313. timeRawProperties.push("rawLastAccessDate");
  6314. }
  6315. if ((flags & 0x4) == 0x4) {
  6316. timeProperties.push("creationDate");
  6317. timeRawProperties.push("rawCreationDate");
  6318. }
  6319. let offset = 1;
  6320. timeProperties.forEach((propertyName, indexProperty) => {
  6321. if (extraFieldExtendedTimestamp.data.length >= offset + 4) {
  6322. const time = getUint32(extraFieldView, offset);
  6323. directory[propertyName] = extraFieldExtendedTimestamp[propertyName] = new Date(time * 1000);
  6324. const rawPropertyName = timeRawProperties[indexProperty];
  6325. extraFieldExtendedTimestamp[rawPropertyName] = time;
  6326. }
  6327. offset += 4;
  6328. });
  6329. }
  6330. async function seekSignature(reader, signature, startOffset, minimumBytes, maximumLength) {
  6331. const signatureArray = new Uint8Array(4);
  6332. const signatureView = getDataView$1(signatureArray);
  6333. setUint32$1(signatureView, 0, signature);
  6334. const maximumBytes = minimumBytes + maximumLength;
  6335. return (await seek(minimumBytes)) || await seek(Math.min(maximumBytes, startOffset));
  6336. async function seek(length) {
  6337. const offset = startOffset - length;
  6338. const bytes = await readUint8Array(reader, offset, length);
  6339. for (let indexByte = bytes.length - minimumBytes; indexByte >= 0; indexByte--) {
  6340. if (bytes[indexByte] == signatureArray[0] && bytes[indexByte + 1] == signatureArray[1] &&
  6341. bytes[indexByte + 2] == signatureArray[2] && bytes[indexByte + 3] == signatureArray[3]) {
  6342. return {
  6343. offset: offset + indexByte,
  6344. buffer: bytes.slice(indexByte, indexByte + minimumBytes).buffer
  6345. };
  6346. }
  6347. }
  6348. }
  6349. }
  6350. function getOptionValue$1(zipReader, options, name) {
  6351. return options[name] === undefined ? zipReader.options[name] : options[name];
  6352. }
  6353. function getDate(timeRaw) {
  6354. const date = (timeRaw & 0xffff0000) >> 16, time = timeRaw & 0x0000ffff;
  6355. try {
  6356. return new Date(1980 + ((date & 0xFE00) >> 9), ((date & 0x01E0) >> 5) - 1, date & 0x001F, (time & 0xF800) >> 11, (time & 0x07E0) >> 5, (time & 0x001F) * 2, 0);
  6357. } catch (error) {
  6358. // ignored
  6359. }
  6360. }
  6361. function getDateNTFS(timeRaw) {
  6362. return new Date((Number((timeRaw / BigInt(10000)) - BigInt(11644473600000))));
  6363. }
  6364. function getUint8(view, offset) {
  6365. return view.getUint8(offset);
  6366. }
  6367. function getUint16(view, offset) {
  6368. return view.getUint16(offset, true);
  6369. }
  6370. function getUint32(view, offset) {
  6371. return view.getUint32(offset, true);
  6372. }
  6373. function getBigUint64(view, offset) {
  6374. return Number(view.getBigUint64(offset, true));
  6375. }
  6376. function setUint32$1(view, offset, value) {
  6377. view.setUint32(offset, value, true);
  6378. }
  6379. function getDataView$1(array) {
  6380. return new DataView(array.buffer);
  6381. }
  6382. function readUint8Array(reader, offset, size) {
  6383. return reader.readUint8Array(offset, size);
  6384. }
  6385. /*
  6386. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  6387. Redistribution and use in source and binary forms, with or without
  6388. modification, are permitted provided that the following conditions are met:
  6389. 1. Redistributions of source code must retain the above copyright notice,
  6390. this list of conditions and the following disclaimer.
  6391. 2. Redistributions in binary form must reproduce the above copyright
  6392. notice, this list of conditions and the following disclaimer in
  6393. the documentation and/or other materials provided with the distribution.
  6394. 3. The names of the authors may not be used to endorse or promote products
  6395. derived from this software without specific prior written permission.
  6396. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  6397. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  6398. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  6399. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  6400. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  6401. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  6402. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  6403. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  6404. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  6405. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  6406. */
  6407. const ERR_DUPLICATED_NAME = "File already exists";
  6408. const ERR_INVALID_COMMENT = "Zip file comment exceeds 64KB";
  6409. const ERR_INVALID_ENTRY_COMMENT = "File entry comment exceeds 64KB";
  6410. const ERR_INVALID_ENTRY_NAME = "File entry name exceeds 64KB";
  6411. const ERR_INVALID_VERSION = "Version exceeds 65535";
  6412. const ERR_INVALID_ENCRYPTION_STRENGTH = "The strength must equal 1, 2, or 3";
  6413. const ERR_INVALID_EXTRAFIELD_TYPE = "Extra field type exceeds 65535";
  6414. const ERR_INVALID_EXTRAFIELD_DATA = "Extra field data exceeds 64KB";
  6415. const ERR_UNSUPPORTED_FORMAT = "Zip64 is not supported";
  6416. const EXTRAFIELD_DATA_AES = new Uint8Array([0x07, 0x00, 0x02, 0x00, 0x41, 0x45, 0x03, 0x00, 0x00]);
  6417. const EXTRAFIELD_LENGTH_ZIP64 = 24;
  6418. let workers = 0;
  6419. class ZipWriter {
  6420. constructor(writer, options = {}) {
  6421. Object.assign(this, {
  6422. writer,
  6423. options,
  6424. config: getConfiguration(),
  6425. files: new Map(),
  6426. offset: writer.size,
  6427. pendingCompressedSize: 0,
  6428. pendingEntries: []
  6429. });
  6430. }
  6431. async add(name = "", reader, options = {}) {
  6432. const zipWriter = this;
  6433. if (workers < zipWriter.config.maxWorkers) {
  6434. workers++;
  6435. try {
  6436. return await addFile(zipWriter, name, reader, options);
  6437. } finally {
  6438. workers--;
  6439. const pendingEntry = zipWriter.pendingEntries.shift();
  6440. if (pendingEntry) {
  6441. zipWriter.add(pendingEntry.name, pendingEntry.reader, pendingEntry.options)
  6442. .then(pendingEntry.resolve)
  6443. .catch(pendingEntry.reject);
  6444. }
  6445. }
  6446. } else {
  6447. return new Promise((resolve, reject) => zipWriter.pendingEntries.push({ name, reader, options, resolve, reject }));
  6448. }
  6449. }
  6450. async close(comment = new Uint8Array(0), options = {}) {
  6451. await closeFile(this, comment, options);
  6452. return this.writer.getData();
  6453. }
  6454. }
  6455. async function addFile(zipWriter, name, reader, options) {
  6456. name = name.trim();
  6457. if (options.directory && (!name.endsWith(DIRECTORY_SIGNATURE))) {
  6458. name += DIRECTORY_SIGNATURE;
  6459. } else {
  6460. options.directory = name.endsWith(DIRECTORY_SIGNATURE);
  6461. }
  6462. if (zipWriter.files.has(name)) {
  6463. throw new Error(ERR_DUPLICATED_NAME);
  6464. }
  6465. const rawFilename = encodeText(name);
  6466. if (rawFilename.length > MAX_16_BITS) {
  6467. throw new Error(ERR_INVALID_ENTRY_NAME);
  6468. }
  6469. const comment = options.comment || "";
  6470. const rawComment = encodeText(comment);
  6471. if (rawComment.length > MAX_16_BITS) {
  6472. throw new Error(ERR_INVALID_ENTRY_COMMENT);
  6473. }
  6474. const version = zipWriter.options.version || options.version || 0;
  6475. if (version > MAX_16_BITS) {
  6476. throw new Error(ERR_INVALID_VERSION);
  6477. }
  6478. const versionMadeBy = zipWriter.options.versionMadeBy || options.versionMadeBy || 20;
  6479. if (versionMadeBy > MAX_16_BITS) {
  6480. throw new Error(ERR_INVALID_VERSION);
  6481. }
  6482. const lastModDate = getOptionValue(zipWriter, options, "lastModDate") || new Date();
  6483. const lastAccessDate = getOptionValue(zipWriter, options, "lastAccessDate");
  6484. const creationDate = getOptionValue(zipWriter, options, "creationDate");
  6485. const password = getOptionValue(zipWriter, options, "password");
  6486. const encryptionStrength = getOptionValue(zipWriter, options, "encryptionStrength") || 3;
  6487. const zipCrypto = getOptionValue(zipWriter, options, "zipCrypto");
  6488. if (password !== undefined && encryptionStrength !== undefined && (encryptionStrength < 1 || encryptionStrength > 3)) {
  6489. throw new Error(ERR_INVALID_ENCRYPTION_STRENGTH);
  6490. }
  6491. let rawExtraField = new Uint8Array(0);
  6492. const extraField = options.extraField;
  6493. if (extraField) {
  6494. let extraFieldSize = 0;
  6495. let offset = 0;
  6496. extraField.forEach(data => extraFieldSize += 4 + data.length);
  6497. rawExtraField = new Uint8Array(extraFieldSize);
  6498. extraField.forEach((data, type) => {
  6499. if (type > MAX_16_BITS) {
  6500. throw new Error(ERR_INVALID_EXTRAFIELD_TYPE);
  6501. }
  6502. if (data.length > MAX_16_BITS) {
  6503. throw new Error(ERR_INVALID_EXTRAFIELD_DATA);
  6504. }
  6505. arraySet(rawExtraField, new Uint16Array([type]), offset);
  6506. arraySet(rawExtraField, new Uint16Array([data.length]), offset + 2);
  6507. arraySet(rawExtraField, data, offset + 4);
  6508. offset += 4 + data.length;
  6509. });
  6510. }
  6511. let extendedTimestamp = getOptionValue(zipWriter, options, "extendedTimestamp");
  6512. if (extendedTimestamp === undefined) {
  6513. extendedTimestamp = true;
  6514. }
  6515. let maximumCompressedSize = 0;
  6516. let keepOrder = getOptionValue(zipWriter, options, "keepOrder");
  6517. if (keepOrder === undefined) {
  6518. keepOrder = true;
  6519. }
  6520. let uncompressedSize = 0;
  6521. let msDosCompatible = getOptionValue(zipWriter, options, "msDosCompatible");
  6522. if (msDosCompatible === undefined) {
  6523. msDosCompatible = true;
  6524. }
  6525. const internalFileAttribute = getOptionValue(zipWriter, options, "internalFileAttribute") || 0;
  6526. const externalFileAttribute = getOptionValue(zipWriter, options, "externalFileAttribute") || 0;
  6527. if (reader) {
  6528. if (!reader.initialized) {
  6529. await reader.init();
  6530. }
  6531. uncompressedSize = reader.size;
  6532. maximumCompressedSize = getMaximumCompressedSize(uncompressedSize);
  6533. }
  6534. let zip64 = options.zip64 || zipWriter.options.zip64 || false;
  6535. if (zipWriter.offset + zipWriter.pendingCompressedSize >= MAX_32_BITS ||
  6536. uncompressedSize >= MAX_32_BITS ||
  6537. maximumCompressedSize >= MAX_32_BITS) {
  6538. if (options.zip64 === false || zipWriter.options.zip64 === false || !keepOrder) {
  6539. throw new Error(ERR_UNSUPPORTED_FORMAT);
  6540. } else {
  6541. zip64 = true;
  6542. }
  6543. }
  6544. zipWriter.pendingCompressedSize += maximumCompressedSize;
  6545. await Promise.resolve();
  6546. const level = getOptionValue(zipWriter, options, "level");
  6547. const useWebWorkers = getOptionValue(zipWriter, options, "useWebWorkers");
  6548. const bufferedWrite = getOptionValue(zipWriter, options, "bufferedWrite");
  6549. let dataDescriptor = getOptionValue(zipWriter, options, "dataDescriptor");
  6550. let dataDescriptorSignature = getOptionValue(zipWriter, options, "dataDescriptorSignature");
  6551. const signal = getOptionValue(zipWriter, options, "signal");
  6552. if (dataDescriptor === undefined) {
  6553. dataDescriptor = true;
  6554. }
  6555. if (dataDescriptor && dataDescriptorSignature === undefined) {
  6556. dataDescriptorSignature = true;
  6557. }
  6558. const fileEntry = await getFileEntry(zipWriter, name, reader, Object.assign({}, options, {
  6559. rawFilename,
  6560. rawComment,
  6561. version,
  6562. versionMadeBy,
  6563. lastModDate,
  6564. lastAccessDate,
  6565. creationDate,
  6566. rawExtraField,
  6567. zip64,
  6568. password,
  6569. level,
  6570. useWebWorkers,
  6571. encryptionStrength,
  6572. extendedTimestamp,
  6573. zipCrypto,
  6574. bufferedWrite,
  6575. keepOrder,
  6576. dataDescriptor,
  6577. dataDescriptorSignature,
  6578. signal,
  6579. msDosCompatible,
  6580. internalFileAttribute,
  6581. externalFileAttribute
  6582. }));
  6583. if (maximumCompressedSize) {
  6584. zipWriter.pendingCompressedSize -= maximumCompressedSize;
  6585. }
  6586. Object.assign(fileEntry, { name, comment, extraField });
  6587. return new Entry(fileEntry);
  6588. }
  6589. async function getFileEntry(zipWriter, name, reader, options) {
  6590. const files = zipWriter.files;
  6591. const writer = zipWriter.writer;
  6592. const previousFileEntry = Array.from(files.values()).pop();
  6593. let fileEntry = {};
  6594. let bufferedWrite;
  6595. let resolveLockUnbufferedWrite;
  6596. let resolveLockCurrentFileEntry;
  6597. files.set(name, fileEntry);
  6598. try {
  6599. let lockPreviousFileEntry;
  6600. let fileWriter;
  6601. let lockCurrentFileEntry;
  6602. if (options.keepOrder) {
  6603. lockPreviousFileEntry = previousFileEntry && previousFileEntry.lock;
  6604. }
  6605. fileEntry.lock = lockCurrentFileEntry = new Promise(resolve => resolveLockCurrentFileEntry = resolve);
  6606. if (options.bufferedWrite || zipWriter.lockWrite || !options.dataDescriptor) {
  6607. fileWriter = new BlobWriter();
  6608. fileWriter.init();
  6609. bufferedWrite = true;
  6610. } else {
  6611. zipWriter.lockWrite = new Promise(resolve => resolveLockUnbufferedWrite = resolve);
  6612. if (!writer.initialized) {
  6613. await writer.init();
  6614. }
  6615. fileWriter = writer;
  6616. }
  6617. fileEntry = await createFileEntry(reader, fileWriter, zipWriter.config, options);
  6618. fileEntry.lock = lockCurrentFileEntry;
  6619. files.set(name, fileEntry);
  6620. fileEntry.filename = name;
  6621. if (bufferedWrite) {
  6622. let indexWrittenData = 0;
  6623. const blob = fileWriter.getData();
  6624. await Promise.all([zipWriter.lockWrite, lockPreviousFileEntry]);
  6625. let pendingFileEntry;
  6626. do {
  6627. pendingFileEntry = Array.from(files.values()).find(fileEntry => fileEntry.writingBufferedData);
  6628. if (pendingFileEntry) {
  6629. await pendingFileEntry.lock;
  6630. }
  6631. } while (pendingFileEntry && pendingFileEntry.lock);
  6632. fileEntry.writingBufferedData = true;
  6633. if (!options.dataDescriptor) {
  6634. const headerLength = 26;
  6635. const arrayBuffer = await sliceAsArrayBuffer(blob, 0, headerLength);
  6636. const arrayBufferView = new DataView(arrayBuffer);
  6637. if (!fileEntry.encrypted || options.zipCrypto) {
  6638. setUint32(arrayBufferView, 14, fileEntry.signature);
  6639. }
  6640. if (fileEntry.zip64) {
  6641. setUint32(arrayBufferView, 18, MAX_32_BITS);
  6642. setUint32(arrayBufferView, 22, MAX_32_BITS);
  6643. } else {
  6644. setUint32(arrayBufferView, 18, fileEntry.compressedSize);
  6645. setUint32(arrayBufferView, 22, fileEntry.uncompressedSize);
  6646. }
  6647. await writer.writeUint8Array(new Uint8Array(arrayBuffer));
  6648. indexWrittenData = headerLength;
  6649. }
  6650. await writeBlob(writer, blob, indexWrittenData);
  6651. delete fileEntry.writingBufferedData;
  6652. }
  6653. fileEntry.offset = zipWriter.offset;
  6654. if (fileEntry.zip64) {
  6655. const rawExtraFieldZip64View = getDataView(fileEntry.rawExtraFieldZip64);
  6656. setBigUint64(rawExtraFieldZip64View, 20, BigInt(fileEntry.offset));
  6657. } else if (fileEntry.offset >= MAX_32_BITS) {
  6658. throw new Error(ERR_UNSUPPORTED_FORMAT);
  6659. }
  6660. zipWriter.offset += fileEntry.length;
  6661. return fileEntry;
  6662. } catch (error) {
  6663. if ((bufferedWrite && fileEntry.writingBufferedData) || (!bufferedWrite && fileEntry.dataWritten)) {
  6664. error.corruptedEntry = zipWriter.hasCorruptedEntries = true;
  6665. if (fileEntry.uncompressedSize) {
  6666. zipWriter.offset += fileEntry.uncompressedSize;
  6667. }
  6668. }
  6669. files.delete(name);
  6670. throw error;
  6671. } finally {
  6672. resolveLockCurrentFileEntry();
  6673. if (resolveLockUnbufferedWrite) {
  6674. resolveLockUnbufferedWrite();
  6675. }
  6676. }
  6677. }
  6678. async function createFileEntry(reader, writer, config, options) {
  6679. const {
  6680. rawFilename,
  6681. lastAccessDate,
  6682. creationDate,
  6683. password,
  6684. level,
  6685. zip64,
  6686. zipCrypto,
  6687. dataDescriptor,
  6688. dataDescriptorSignature,
  6689. directory,
  6690. version,
  6691. versionMadeBy,
  6692. rawComment,
  6693. rawExtraField,
  6694. useWebWorkers,
  6695. onprogress,
  6696. signal,
  6697. encryptionStrength,
  6698. extendedTimestamp,
  6699. msDosCompatible,
  6700. internalFileAttribute,
  6701. externalFileAttribute
  6702. } = options;
  6703. const encrypted = Boolean(password && password.length);
  6704. const compressed = level !== 0 && !directory;
  6705. let rawExtraFieldAES;
  6706. if (encrypted && !zipCrypto) {
  6707. rawExtraFieldAES = new Uint8Array(EXTRAFIELD_DATA_AES.length + 2);
  6708. const extraFieldAESView = getDataView(rawExtraFieldAES);
  6709. setUint16(extraFieldAESView, 0, EXTRAFIELD_TYPE_AES);
  6710. arraySet(rawExtraFieldAES, EXTRAFIELD_DATA_AES, 2);
  6711. setUint8(extraFieldAESView, 8, encryptionStrength);
  6712. } else {
  6713. rawExtraFieldAES = new Uint8Array(0);
  6714. }
  6715. let rawExtraFieldNTFS;
  6716. let rawExtraFieldExtendedTimestamp;
  6717. if (extendedTimestamp) {
  6718. rawExtraFieldExtendedTimestamp = new Uint8Array(9 + (lastAccessDate ? 4 : 0) + (creationDate ? 4 : 0));
  6719. const extraFieldExtendedTimestampView = getDataView(rawExtraFieldExtendedTimestamp);
  6720. setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  6721. setUint16(extraFieldExtendedTimestampView, 2, rawExtraFieldExtendedTimestamp.length - 4);
  6722. const extraFieldExtendedTimestampFlag = 0x1 + (lastAccessDate ? 0x2 : 0) + (creationDate ? 0x4 : 0);
  6723. setUint8(extraFieldExtendedTimestampView, 4, extraFieldExtendedTimestampFlag);
  6724. setUint32(extraFieldExtendedTimestampView, 5, Math.floor(options.lastModDate.getTime() / 1000));
  6725. if (lastAccessDate) {
  6726. setUint32(extraFieldExtendedTimestampView, 9, Math.floor(lastAccessDate.getTime() / 1000));
  6727. }
  6728. if (creationDate) {
  6729. setUint32(extraFieldExtendedTimestampView, 13, Math.floor(creationDate.getTime() / 1000));
  6730. }
  6731. try {
  6732. rawExtraFieldNTFS = new Uint8Array(36);
  6733. const extraFieldNTFSView = getDataView(rawExtraFieldNTFS);
  6734. const lastModTimeNTFS = getTimeNTFS(options.lastModDate);
  6735. setUint16(extraFieldNTFSView, 0, EXTRAFIELD_TYPE_NTFS);
  6736. setUint16(extraFieldNTFSView, 2, 32);
  6737. setUint16(extraFieldNTFSView, 8, EXTRAFIELD_TYPE_NTFS_TAG1);
  6738. setUint16(extraFieldNTFSView, 10, 24);
  6739. setBigUint64(extraFieldNTFSView, 12, lastModTimeNTFS);
  6740. setBigUint64(extraFieldNTFSView, 20, getTimeNTFS(lastAccessDate) || lastModTimeNTFS);
  6741. setBigUint64(extraFieldNTFSView, 28, getTimeNTFS(creationDate) || lastModTimeNTFS);
  6742. } catch (error) {
  6743. rawExtraFieldNTFS = new Uint8Array(0);
  6744. }
  6745. } else {
  6746. rawExtraFieldNTFS = rawExtraFieldExtendedTimestamp = new Uint8Array(0);
  6747. }
  6748. const fileEntry = {
  6749. version: version || VERSION_DEFLATE,
  6750. versionMadeBy,
  6751. zip64,
  6752. directory: Boolean(directory),
  6753. filenameUTF8: true,
  6754. rawFilename,
  6755. commentUTF8: true,
  6756. rawComment,
  6757. rawExtraFieldZip64: zip64 ? new Uint8Array(EXTRAFIELD_LENGTH_ZIP64 + 4) : new Uint8Array(0),
  6758. rawExtraFieldExtendedTimestamp,
  6759. rawExtraFieldNTFS,
  6760. rawExtraFieldAES,
  6761. rawExtraField,
  6762. extendedTimestamp,
  6763. msDosCompatible,
  6764. internalFileAttribute,
  6765. externalFileAttribute
  6766. };
  6767. let uncompressedSize = fileEntry.uncompressedSize = 0;
  6768. let bitFlag = BITFLAG_LANG_ENCODING_FLAG;
  6769. if (dataDescriptor) {
  6770. bitFlag = bitFlag | BITFLAG_DATA_DESCRIPTOR;
  6771. }
  6772. let compressionMethod = COMPRESSION_METHOD_STORE;
  6773. if (compressed) {
  6774. compressionMethod = COMPRESSION_METHOD_DEFLATE;
  6775. }
  6776. if (zip64) {
  6777. fileEntry.version = fileEntry.version > VERSION_ZIP64 ? fileEntry.version : VERSION_ZIP64;
  6778. }
  6779. if (encrypted) {
  6780. bitFlag = bitFlag | BITFLAG_ENCRYPTED;
  6781. if (!zipCrypto) {
  6782. fileEntry.version = fileEntry.version > VERSION_AES ? fileEntry.version : VERSION_AES;
  6783. compressionMethod = COMPRESSION_METHOD_AES;
  6784. if (compressed) {
  6785. fileEntry.rawExtraFieldAES[9] = COMPRESSION_METHOD_DEFLATE;
  6786. }
  6787. }
  6788. }
  6789. fileEntry.compressionMethod = compressionMethod;
  6790. const headerArray = fileEntry.headerArray = new Uint8Array(26);
  6791. const headerView = getDataView(headerArray);
  6792. setUint16(headerView, 0, fileEntry.version);
  6793. setUint16(headerView, 2, bitFlag);
  6794. setUint16(headerView, 4, compressionMethod);
  6795. const dateArray = new Uint32Array(1);
  6796. const dateView = getDataView(dateArray);
  6797. let lastModDate;
  6798. if (options.lastModDate < MIN_DATE) {
  6799. lastModDate = MIN_DATE;
  6800. } else if (options.lastModDate > MAX_DATE) {
  6801. lastModDate = MAX_DATE;
  6802. } else {
  6803. lastModDate = options.lastModDate;
  6804. }
  6805. setUint16(dateView, 0, (((lastModDate.getHours() << 6) | lastModDate.getMinutes()) << 5) | lastModDate.getSeconds() / 2);
  6806. setUint16(dateView, 2, ((((lastModDate.getFullYear() - 1980) << 4) | (lastModDate.getMonth() + 1)) << 5) | lastModDate.getDate());
  6807. const rawLastModDate = dateArray[0];
  6808. setUint32(headerView, 6, rawLastModDate);
  6809. setUint16(headerView, 22, rawFilename.length);
  6810. const extraFieldLength = rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length + rawExtraFieldNTFS.length + fileEntry.rawExtraField.length;
  6811. setUint16(headerView, 24, extraFieldLength);
  6812. const localHeaderArray = new Uint8Array(30 + rawFilename.length + extraFieldLength);
  6813. const localHeaderView = getDataView(localHeaderArray);
  6814. setUint32(localHeaderView, 0, LOCAL_FILE_HEADER_SIGNATURE);
  6815. arraySet(localHeaderArray, headerArray, 4);
  6816. arraySet(localHeaderArray, rawFilename, 30);
  6817. arraySet(localHeaderArray, rawExtraFieldAES, 30 + rawFilename.length);
  6818. arraySet(localHeaderArray, rawExtraFieldExtendedTimestamp, 30 + rawFilename.length + rawExtraFieldAES.length);
  6819. arraySet(localHeaderArray, rawExtraFieldNTFS, 30 + rawFilename.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length);
  6820. arraySet(localHeaderArray, fileEntry.rawExtraField, 30 + rawFilename.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length + rawExtraFieldNTFS.length);
  6821. let result;
  6822. let compressedSize = 0;
  6823. if (reader) {
  6824. uncompressedSize = fileEntry.uncompressedSize = reader.size;
  6825. const codec = await createCodec(config.Deflate, {
  6826. codecType: CODEC_DEFLATE,
  6827. level,
  6828. password,
  6829. encryptionStrength,
  6830. zipCrypto: encrypted && zipCrypto,
  6831. passwordVerification: encrypted && zipCrypto && (rawLastModDate >> 8) & 0xFF,
  6832. signed: true,
  6833. compressed,
  6834. encrypted,
  6835. useWebWorkers
  6836. }, config);
  6837. await writer.writeUint8Array(localHeaderArray);
  6838. fileEntry.dataWritten = true;
  6839. result = await processData(codec, reader, writer, 0, uncompressedSize, config, { onprogress, signal });
  6840. compressedSize = result.length;
  6841. } else {
  6842. await writer.writeUint8Array(localHeaderArray);
  6843. fileEntry.dataWritten = true;
  6844. }
  6845. let dataDescriptorArray = new Uint8Array(0);
  6846. let dataDescriptorView, dataDescriptorOffset = 0;
  6847. if (dataDescriptor) {
  6848. dataDescriptorArray = new Uint8Array(zip64 ? (dataDescriptorSignature ? 24 : 20) : (dataDescriptorSignature ? 16 : 12));
  6849. dataDescriptorView = getDataView(dataDescriptorArray);
  6850. if (dataDescriptorSignature) {
  6851. dataDescriptorOffset = 4;
  6852. setUint32(dataDescriptorView, 0, DATA_DESCRIPTOR_RECORD_SIGNATURE);
  6853. }
  6854. }
  6855. if (reader) {
  6856. const signature = result.signature;
  6857. if ((!encrypted || zipCrypto) && signature !== undefined) {
  6858. setUint32(headerView, 10, signature);
  6859. fileEntry.signature = signature;
  6860. if (dataDescriptor) {
  6861. setUint32(dataDescriptorView, dataDescriptorOffset, signature);
  6862. }
  6863. }
  6864. if (zip64) {
  6865. const rawExtraFieldZip64View = getDataView(fileEntry.rawExtraFieldZip64);
  6866. setUint16(rawExtraFieldZip64View, 0, EXTRAFIELD_TYPE_ZIP64);
  6867. setUint16(rawExtraFieldZip64View, 2, EXTRAFIELD_LENGTH_ZIP64);
  6868. setUint32(headerView, 14, MAX_32_BITS);
  6869. setBigUint64(rawExtraFieldZip64View, 12, BigInt(compressedSize));
  6870. setUint32(headerView, 18, MAX_32_BITS);
  6871. setBigUint64(rawExtraFieldZip64View, 4, BigInt(uncompressedSize));
  6872. if (dataDescriptor) {
  6873. setBigUint64(dataDescriptorView, dataDescriptorOffset + 4, BigInt(compressedSize));
  6874. setBigUint64(dataDescriptorView, dataDescriptorOffset + 12, BigInt(uncompressedSize));
  6875. }
  6876. } else {
  6877. setUint32(headerView, 14, compressedSize);
  6878. setUint32(headerView, 18, uncompressedSize);
  6879. if (dataDescriptor) {
  6880. setUint32(dataDescriptorView, dataDescriptorOffset + 4, compressedSize);
  6881. setUint32(dataDescriptorView, dataDescriptorOffset + 8, uncompressedSize);
  6882. }
  6883. }
  6884. }
  6885. if (dataDescriptor) {
  6886. await writer.writeUint8Array(dataDescriptorArray);
  6887. }
  6888. const length = localHeaderArray.length + compressedSize + dataDescriptorArray.length;
  6889. Object.assign(fileEntry, { compressedSize, lastModDate, rawLastModDate, creationDate, lastAccessDate, encrypted, length });
  6890. return fileEntry;
  6891. }
  6892. async function closeFile(zipWriter, comment, options) {
  6893. const writer = zipWriter.writer;
  6894. const files = zipWriter.files;
  6895. let offset = 0;
  6896. let directoryDataLength = 0;
  6897. let directoryOffset = zipWriter.offset;
  6898. let filesLength = files.size;
  6899. for (const [, fileEntry] of files) {
  6900. directoryDataLength += 46 +
  6901. fileEntry.rawFilename.length +
  6902. fileEntry.rawComment.length +
  6903. fileEntry.rawExtraFieldZip64.length +
  6904. fileEntry.rawExtraFieldAES.length +
  6905. fileEntry.rawExtraFieldExtendedTimestamp.length +
  6906. fileEntry.rawExtraFieldNTFS.length +
  6907. fileEntry.rawExtraField.length;
  6908. }
  6909. let zip64 = options.zip64 || zipWriter.options.zip64 || false;
  6910. if (directoryOffset >= MAX_32_BITS || directoryDataLength >= MAX_32_BITS || filesLength >= MAX_16_BITS) {
  6911. if (options.zip64 === false || zipWriter.options.zip64 === false) {
  6912. throw new Error(ERR_UNSUPPORTED_FORMAT);
  6913. } else {
  6914. zip64 = true;
  6915. }
  6916. }
  6917. const directoryArray = new Uint8Array(directoryDataLength + (zip64 ? ZIP64_END_OF_CENTRAL_DIR_TOTAL_LENGTH : END_OF_CENTRAL_DIR_LENGTH));
  6918. const directoryView = getDataView(directoryArray);
  6919. if (comment && comment.length) {
  6920. if (comment.length <= MAX_16_BITS) {
  6921. setUint16(directoryView, offset + 20, comment.length);
  6922. } else {
  6923. throw new Error(ERR_INVALID_COMMENT);
  6924. }
  6925. }
  6926. for (const [indexFileEntry, fileEntry] of Array.from(files.values()).entries()) {
  6927. const {
  6928. rawFilename,
  6929. rawExtraFieldZip64,
  6930. rawExtraFieldAES,
  6931. rawExtraField,
  6932. rawComment,
  6933. versionMadeBy,
  6934. headerArray,
  6935. directory,
  6936. zip64,
  6937. msDosCompatible,
  6938. internalFileAttribute,
  6939. externalFileAttribute
  6940. } = fileEntry;
  6941. let rawExtraFieldExtendedTimestamp;
  6942. let rawExtraFieldNTFS;
  6943. if (fileEntry.extendedTimestamp) {
  6944. rawExtraFieldNTFS = fileEntry.rawExtraFieldNTFS;
  6945. rawExtraFieldExtendedTimestamp = new Uint8Array(9);
  6946. const extraFieldExtendedTimestampView = getDataView(rawExtraFieldExtendedTimestamp);
  6947. setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  6948. setUint16(extraFieldExtendedTimestampView, 2, rawExtraFieldExtendedTimestamp.length - 4);
  6949. setUint8(extraFieldExtendedTimestampView, 4, 0x1);
  6950. setUint32(extraFieldExtendedTimestampView, 5, Math.floor(fileEntry.lastModDate.getTime() / 1000));
  6951. } else {
  6952. rawExtraFieldNTFS = rawExtraFieldExtendedTimestamp = new Uint8Array(0);
  6953. }
  6954. const extraFieldLength = rawExtraFieldZip64.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length + rawExtraFieldNTFS.length + rawExtraField.length;
  6955. setUint32(directoryView, offset, CENTRAL_FILE_HEADER_SIGNATURE);
  6956. setUint16(directoryView, offset + 4, versionMadeBy);
  6957. arraySet(directoryArray, headerArray, offset + 6);
  6958. setUint16(directoryView, offset + 30, extraFieldLength);
  6959. setUint16(directoryView, offset + 32, rawComment.length);
  6960. setUint32(directoryView, offset + 34, internalFileAttribute);
  6961. if (externalFileAttribute) {
  6962. setUint32(directoryView, offset + 38, externalFileAttribute);
  6963. } else if (directory && msDosCompatible) {
  6964. setUint8(directoryView, offset + 38, FILE_ATTR_MSDOS_DIR_MASK);
  6965. }
  6966. if (zip64) {
  6967. setUint32(directoryView, offset + 42, MAX_32_BITS);
  6968. } else {
  6969. setUint32(directoryView, offset + 42, fileEntry.offset);
  6970. }
  6971. arraySet(directoryArray, rawFilename, offset + 46);
  6972. arraySet(directoryArray, rawExtraFieldZip64, offset + 46 + rawFilename.length);
  6973. arraySet(directoryArray, rawExtraFieldAES, offset + 46 + rawFilename.length + rawExtraFieldZip64.length);
  6974. arraySet(directoryArray, rawExtraFieldExtendedTimestamp, offset + 46 + rawFilename.length + rawExtraFieldZip64.length + rawExtraFieldAES.length);
  6975. arraySet(directoryArray, rawExtraFieldNTFS, offset + 46 + rawFilename.length + rawExtraFieldZip64.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length);
  6976. arraySet(directoryArray, rawExtraField, offset + 46 + rawFilename.length + rawExtraFieldZip64.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length + rawExtraFieldNTFS.length);
  6977. arraySet(directoryArray, rawComment, offset + 46 + rawFilename.length + extraFieldLength);
  6978. offset += 46 + rawFilename.length + extraFieldLength + rawComment.length;
  6979. if (options.onprogress) {
  6980. try {
  6981. options.onprogress(indexFileEntry + 1, files.size, new Entry(fileEntry));
  6982. } catch (error) {
  6983. // ignored
  6984. }
  6985. }
  6986. }
  6987. if (zip64) {
  6988. setUint32(directoryView, offset, ZIP64_END_OF_CENTRAL_DIR_SIGNATURE);
  6989. setBigUint64(directoryView, offset + 4, BigInt(44));
  6990. setUint16(directoryView, offset + 12, 45);
  6991. setUint16(directoryView, offset + 14, 45);
  6992. setBigUint64(directoryView, offset + 24, BigInt(filesLength));
  6993. setBigUint64(directoryView, offset + 32, BigInt(filesLength));
  6994. setBigUint64(directoryView, offset + 40, BigInt(directoryDataLength));
  6995. setBigUint64(directoryView, offset + 48, BigInt(directoryOffset));
  6996. setUint32(directoryView, offset + 56, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE);
  6997. setBigUint64(directoryView, offset + 64, BigInt(directoryOffset) + BigInt(directoryDataLength));
  6998. setUint32(directoryView, offset + 72, ZIP64_TOTAL_NUMBER_OF_DISKS);
  6999. filesLength = MAX_16_BITS;
  7000. directoryOffset = MAX_32_BITS;
  7001. directoryDataLength = MAX_32_BITS;
  7002. offset += 76;
  7003. }
  7004. setUint32(directoryView, offset, END_OF_CENTRAL_DIR_SIGNATURE);
  7005. setUint16(directoryView, offset + 8, filesLength);
  7006. setUint16(directoryView, offset + 10, filesLength);
  7007. setUint32(directoryView, offset + 12, directoryDataLength);
  7008. setUint32(directoryView, offset + 16, directoryOffset);
  7009. await writer.writeUint8Array(directoryArray);
  7010. if (comment && comment.length) {
  7011. await writer.writeUint8Array(comment);
  7012. }
  7013. }
  7014. function sliceAsArrayBuffer(blob, start, end) {
  7015. if (blob.arrayBuffer) {
  7016. if (start || end) {
  7017. return blob.slice(start, end).arrayBuffer();
  7018. } else {
  7019. return blob.arrayBuffer();
  7020. }
  7021. } else {
  7022. const fileReader = new FileReader();
  7023. return new Promise((resolve, reject) => {
  7024. fileReader.onload = event => resolve(event.target.result);
  7025. fileReader.onerror = () => reject(fileReader.error);
  7026. fileReader.readAsArrayBuffer(start || end ? blob.slice(start, end) : blob);
  7027. });
  7028. }
  7029. }
  7030. async function writeBlob(writer, blob, start = 0) {
  7031. const blockSize = 512 * 1024 * 1024;
  7032. await writeSlice();
  7033. async function writeSlice() {
  7034. if (start < blob.size) {
  7035. const arrayBuffer = await sliceAsArrayBuffer(blob, start, start + blockSize);
  7036. await writer.writeUint8Array(new Uint8Array(arrayBuffer));
  7037. start += blockSize;
  7038. await writeSlice();
  7039. }
  7040. }
  7041. }
  7042. function getTimeNTFS(date) {
  7043. if (date) {
  7044. return ((BigInt(date.getTime()) + BigInt(11644473600000)) * BigInt(10000));
  7045. }
  7046. }
  7047. function getOptionValue(zipWriter, options, name) {
  7048. return options[name] === undefined ? zipWriter.options[name] : options[name];
  7049. }
  7050. function getMaximumCompressedSize(uncompressedSize) {
  7051. return uncompressedSize + (5 * (Math.floor(uncompressedSize / 16383) + 1));
  7052. }
  7053. function setUint8(view, offset, value) {
  7054. view.setUint8(offset, value);
  7055. }
  7056. function setUint16(view, offset, value) {
  7057. view.setUint16(offset, value, true);
  7058. }
  7059. function setUint32(view, offset, value) {
  7060. view.setUint32(offset, value, true);
  7061. }
  7062. function setBigUint64(view, offset, value) {
  7063. view.setBigUint64(offset, value, true);
  7064. }
  7065. function arraySet(array, typedArray, offset) {
  7066. array.set(typedArray, offset);
  7067. }
  7068. function getDataView(array) {
  7069. return new DataView(array.buffer);
  7070. }
  7071. /*
  7072. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  7073. Redistribution and use in source and binary forms, with or without
  7074. modification, are permitted provided that the following conditions are met:
  7075. 1. Redistributions of source code must retain the above copyright notice,
  7076. this list of conditions and the following disclaimer.
  7077. 2. Redistributions in binary form must reproduce the above copyright
  7078. notice, this list of conditions and the following disclaimer in
  7079. the documentation and/or other materials provided with the distribution.
  7080. 3. The names of the authors may not be used to endorse or promote products
  7081. derived from this software without specific prior written permission.
  7082. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  7083. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  7084. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  7085. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  7086. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7087. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  7088. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  7089. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  7090. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  7091. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7092. */
  7093. configure({ Deflate: ZipDeflate, Inflate: ZipInflate });
  7094. var zipNoWorker = /*#__PURE__*/Object.freeze({
  7095. __proto__: null,
  7096. configure: configure,
  7097. getMimeType: getMimeType,
  7098. terminateWorkers: terminateWorkers,
  7099. ERR_ABORT: ERR_ABORT,
  7100. Reader: Reader,
  7101. Writer: Writer,
  7102. TextReader: TextReader,
  7103. TextWriter: TextWriter,
  7104. Data64URIReader: Data64URIReader,
  7105. Data64URIWriter: Data64URIWriter,
  7106. BlobReader: BlobReader,
  7107. BlobWriter: BlobWriter,
  7108. Uint8ArrayReader: Uint8ArrayReader,
  7109. Uint8ArrayWriter: Uint8ArrayWriter,
  7110. HttpReader: HttpReader,
  7111. HttpRangeReader: HttpRangeReader,
  7112. WritableStreamWriter: WritableStreamWriter,
  7113. ERR_HTTP_RANGE: ERR_HTTP_RANGE,
  7114. ZipReader: ZipReader,
  7115. ERR_BAD_FORMAT: ERR_BAD_FORMAT,
  7116. ERR_EOCDR_NOT_FOUND: ERR_EOCDR_NOT_FOUND,
  7117. ERR_EOCDR_ZIP64_NOT_FOUND: ERR_EOCDR_ZIP64_NOT_FOUND,
  7118. ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND: ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND,
  7119. ERR_CENTRAL_DIRECTORY_NOT_FOUND: ERR_CENTRAL_DIRECTORY_NOT_FOUND,
  7120. ERR_LOCAL_FILE_HEADER_NOT_FOUND: ERR_LOCAL_FILE_HEADER_NOT_FOUND,
  7121. ERR_EXTRAFIELD_ZIP64_NOT_FOUND: ERR_EXTRAFIELD_ZIP64_NOT_FOUND,
  7122. ERR_ENCRYPTED: ERR_ENCRYPTED,
  7123. ERR_UNSUPPORTED_ENCRYPTION: ERR_UNSUPPORTED_ENCRYPTION,
  7124. ERR_UNSUPPORTED_COMPRESSION: ERR_UNSUPPORTED_COMPRESSION,
  7125. ERR_INVALID_SIGNATURE: ERR_INVALID_SIGNATURE,
  7126. ERR_INVALID_PASSWORD: ERR_INVALID_PASSWORD,
  7127. ZipWriter: ZipWriter,
  7128. ERR_DUPLICATED_NAME: ERR_DUPLICATED_NAME,
  7129. ERR_INVALID_COMMENT: ERR_INVALID_COMMENT,
  7130. ERR_INVALID_ENTRY_NAME: ERR_INVALID_ENTRY_NAME,
  7131. ERR_INVALID_ENTRY_COMMENT: ERR_INVALID_ENTRY_COMMENT,
  7132. ERR_INVALID_VERSION: ERR_INVALID_VERSION,
  7133. ERR_INVALID_EXTRAFIELD_TYPE: ERR_INVALID_EXTRAFIELD_TYPE,
  7134. ERR_INVALID_EXTRAFIELD_DATA: ERR_INVALID_EXTRAFIELD_DATA,
  7135. ERR_INVALID_ENCRYPTION_STRENGTH: ERR_INVALID_ENCRYPTION_STRENGTH,
  7136. ERR_UNSUPPORTED_FORMAT: ERR_UNSUPPORTED_FORMAT
  7137. });
  7138. export { zipNoWorker as default };