single-file-extension-editor.js 282 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575
  1. (function () {
  2. 'use strict';
  3. const { Array: Array$1, Object: Object$1, String, Number: Number$1, BigInt, Math: Math$1, Date, Map, Set: Set$1, Response, URL: URL$1, Error, Uint8Array: Uint8Array$1, Uint16Array, Uint32Array, DataView, Blob: Blob$1, Promise: Promise$1, TextEncoder, TextDecoder: TextDecoder$1, document: document$1, crypto, btoa, TransformStream, ReadableStream, WritableStream, CompressionStream, DecompressionStream, navigator: navigator$1, Worker: Worker$1 } = globalThis;
  4. /*
  5. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are met:
  8. 1. Redistributions of source code must retain the above copyright notice,
  9. this list of conditions and the following disclaimer.
  10. 2. Redistributions in binary form must reproduce the above copyright
  11. notice, this list of conditions and the following disclaimer in
  12. the documentation and/or other materials provided with the distribution.
  13. 3. The names of the authors may not be used to endorse or promote products
  14. derived from this software without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  16. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  18. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  19. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  20. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  21. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  22. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  23. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  24. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. const MAX_32_BITS = 0xffffffff;
  27. const MAX_16_BITS = 0xffff;
  28. const COMPRESSION_METHOD_DEFLATE = 0x08;
  29. const COMPRESSION_METHOD_STORE = 0x00;
  30. const COMPRESSION_METHOD_AES = 0x63;
  31. const LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50;
  32. const SPLIT_ZIP_FILE_SIGNATURE = 0x08074b50;
  33. const DATA_DESCRIPTOR_RECORD_SIGNATURE = SPLIT_ZIP_FILE_SIGNATURE;
  34. const CENTRAL_FILE_HEADER_SIGNATURE = 0x02014b50;
  35. const END_OF_CENTRAL_DIR_SIGNATURE = 0x06054b50;
  36. const ZIP64_END_OF_CENTRAL_DIR_SIGNATURE = 0x06064b50;
  37. const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE = 0x07064b50;
  38. const END_OF_CENTRAL_DIR_LENGTH = 22;
  39. const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH = 20;
  40. const ZIP64_END_OF_CENTRAL_DIR_LENGTH = 56;
  41. 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;
  42. const EXTRAFIELD_TYPE_ZIP64 = 0x0001;
  43. const EXTRAFIELD_TYPE_AES = 0x9901;
  44. const EXTRAFIELD_TYPE_NTFS = 0x000a;
  45. const EXTRAFIELD_TYPE_NTFS_TAG1 = 0x0001;
  46. const EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP = 0x5455;
  47. const EXTRAFIELD_TYPE_UNICODE_PATH = 0x7075;
  48. const EXTRAFIELD_TYPE_UNICODE_COMMENT = 0x6375;
  49. const EXTRAFIELD_TYPE_USDZ = 0x1986;
  50. const BITFLAG_ENCRYPTED = 0x01;
  51. const BITFLAG_LEVEL = 0x06;
  52. const BITFLAG_DATA_DESCRIPTOR = 0x0008;
  53. const BITFLAG_LANG_ENCODING_FLAG = 0x0800;
  54. const FILE_ATTR_MSDOS_DIR_MASK = 0x10;
  55. const VERSION_DEFLATE = 0x14;
  56. const VERSION_ZIP64 = 0x2D;
  57. const VERSION_AES = 0x33;
  58. const DIRECTORY_SIGNATURE = "/";
  59. const MAX_DATE = new Date(2107, 11, 31);
  60. const MIN_DATE = new Date(1980, 0, 1);
  61. const UNDEFINED_VALUE = undefined;
  62. const UNDEFINED_TYPE$1 = "undefined";
  63. const FUNCTION_TYPE$1 = "function";
  64. /*
  65. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  66. Redistribution and use in source and binary forms, with or without
  67. modification, are permitted provided that the following conditions are met:
  68. 1. Redistributions of source code must retain the above copyright notice,
  69. this list of conditions and the following disclaimer.
  70. 2. Redistributions in binary form must reproduce the above copyright
  71. notice, this list of conditions and the following disclaimer in
  72. the documentation and/or other materials provided with the distribution.
  73. 3. The names of the authors may not be used to endorse or promote products
  74. derived from this software without specific prior written permission.
  75. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  76. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  77. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  78. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  79. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  80. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  81. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  82. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  83. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  84. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  85. */
  86. class StreamAdapter {
  87. constructor(Codec) {
  88. return class extends TransformStream {
  89. constructor(_format, options) {
  90. const codec = new Codec(options);
  91. super({
  92. transform(chunk, controller) {
  93. controller.enqueue(codec.append(chunk));
  94. },
  95. flush(controller) {
  96. const chunk = codec.flush();
  97. if (chunk) {
  98. controller.enqueue(chunk);
  99. }
  100. }
  101. });
  102. }
  103. };
  104. }
  105. }
  106. /*
  107. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  108. Redistribution and use in source and binary forms, with or without
  109. modification, are permitted provided that the following conditions are met:
  110. 1. Redistributions of source code must retain the above copyright notice,
  111. this list of conditions and the following disclaimer.
  112. 2. Redistributions in binary form must reproduce the above copyright
  113. notice, this list of conditions and the following disclaimer in
  114. the documentation and/or other materials provided with the distribution.
  115. 3. The names of the authors may not be used to endorse or promote products
  116. derived from this software without specific prior written permission.
  117. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  118. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  119. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  120. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  121. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  122. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  123. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  124. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  125. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  126. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  127. */
  128. const MINIMUM_CHUNK_SIZE = 64;
  129. let maxWorkers = 2;
  130. try {
  131. if (typeof navigator$1 != UNDEFINED_TYPE$1 && navigator$1.hardwareConcurrency) {
  132. maxWorkers = navigator$1.hardwareConcurrency;
  133. }
  134. } catch (_error) {
  135. // ignored
  136. }
  137. const DEFAULT_CONFIGURATION = {
  138. chunkSize: 512 * 1024,
  139. maxWorkers,
  140. terminateWorkerTimeout: 5000,
  141. useWebWorkers: true,
  142. useCompressionStream: true,
  143. workerScripts: UNDEFINED_VALUE,
  144. CompressionStreamNative: typeof CompressionStream != UNDEFINED_TYPE$1 && CompressionStream,
  145. DecompressionStreamNative: typeof DecompressionStream != UNDEFINED_TYPE$1 && DecompressionStream
  146. };
  147. const config = Object$1.assign({}, DEFAULT_CONFIGURATION);
  148. function getConfiguration() {
  149. return config;
  150. }
  151. function getChunkSize(config) {
  152. return Math$1.max(config.chunkSize, MINIMUM_CHUNK_SIZE);
  153. }
  154. function configure(configuration) {
  155. const {
  156. baseURL,
  157. chunkSize,
  158. maxWorkers,
  159. terminateWorkerTimeout,
  160. useCompressionStream,
  161. useWebWorkers,
  162. Deflate,
  163. Inflate,
  164. CompressionStream,
  165. DecompressionStream,
  166. workerScripts
  167. } = configuration;
  168. setIfDefined("baseURL", baseURL);
  169. setIfDefined("chunkSize", chunkSize);
  170. setIfDefined("maxWorkers", maxWorkers);
  171. setIfDefined("terminateWorkerTimeout", terminateWorkerTimeout);
  172. setIfDefined("useCompressionStream", useCompressionStream);
  173. setIfDefined("useWebWorkers", useWebWorkers);
  174. if (Deflate) {
  175. config.CompressionStream = new StreamAdapter(Deflate);
  176. }
  177. if (Inflate) {
  178. config.DecompressionStream = new StreamAdapter(Inflate);
  179. }
  180. setIfDefined("CompressionStream", CompressionStream);
  181. setIfDefined("DecompressionStream", DecompressionStream);
  182. if (workerScripts !== UNDEFINED_VALUE) {
  183. const { deflate, inflate } = workerScripts;
  184. if (deflate || inflate) {
  185. if (!config.workerScripts) {
  186. config.workerScripts = {};
  187. }
  188. }
  189. if (deflate) {
  190. if (!Array$1.isArray(deflate)) {
  191. throw new Error("workerScripts.deflate must be an array");
  192. }
  193. config.workerScripts.deflate = deflate;
  194. }
  195. if (inflate) {
  196. if (!Array$1.isArray(inflate)) {
  197. throw new Error("workerScripts.inflate must be an array");
  198. }
  199. config.workerScripts.inflate = inflate;
  200. }
  201. }
  202. }
  203. function setIfDefined(propertyName, propertyValue) {
  204. if (propertyValue !== UNDEFINED_VALUE) {
  205. config[propertyName] = propertyValue;
  206. }
  207. }
  208. function e(e){const t=()=>URL$1.createObjectURL(new Blob$1(['const{Array:e,Object:t,Number:n,Math:r,Error:s,Uint8Array:a,Uint16Array:i,Uint32Array:o,Int32Array:l,Map:c,DataView:h,Promise:f,TextEncoder:u,crypto:p,postMessage:d,TransformStream:g,ReadableStream:w,WritableStream:v,CompressionStream:y,DecompressionStream:b}=self;class m{constructor(e){return class extends g{constructor(t,n){const r=new e(n);super({transform(e,t){t.enqueue(r.append(e))},flush(e){const t=r.flush();t&&e.enqueue(t)}})}}}}const _=[];for(let e=0;256>e;e++){let t=e;for(let e=0;8>e;e++)1&t?t=t>>>1^3988292384:t>>>=1;_[e]=t}class k{constructor(e){this.crc=e||-1}append(e){let t=0|this.crc;for(let n=0,r=0|e.length;r>n;n++)t=t>>>8^_[255&(t^e[n])];this.crc=t}get(){return~this.crc}}class S extends g{constructor(){let e;const t=new k;super({transform(e,n){t.append(e),n.enqueue(e)},flush(){const n=new a(4);new h(n.buffer).setUint32(0,t.get()),e.value=n}}),e=this}}const z={concat(e,t){if(0===e.length||0===t.length)return e.concat(t);const n=e[e.length-1],r=z.getPartial(n);return 32===r?e.concat(t):z._shiftRight(t,r,0|n,e.slice(0,e.length-1))},bitLength(e){const t=e.length;if(0===t)return 0;const n=e[t-1];return 32*(t-1)+z.getPartial(n)},clamp(e,t){if(32*e.length<t)return e;const n=(e=e.slice(0,r.ceil(t/32))).length;return t&=31,n>0&&t&&(e[n-1]=z.partial(t,e[n-1]&2147483648>>t-1,1)),e},partial:(e,t,n)=>32===e?t:(n?0|t:t<<32-e)+1099511627776*e,getPartial:e=>r.round(e/1099511627776)||32,_shiftRight(e,t,n,r){for(void 0===r&&(r=[]);t>=32;t-=32)r.push(n),n=0;if(0===t)return r.concat(e);for(let s=0;s<e.length;s++)r.push(n|e[s]>>>t),n=e[s]<<32-t;const s=e.length?e[e.length-1]:0,a=z.getPartial(s);return r.push(z.partial(t+a&31,t+a>32?n:r.pop(),1)),r}},D={bytes:{fromBits(e){const t=z.bitLength(e)/8,n=new a(t);let r;for(let s=0;t>s;s++)0==(3&s)&&(r=e[s/4]),n[s]=r>>>24,r<<=8;return n},toBits(e){const t=[];let n,r=0;for(n=0;n<e.length;n++)r=r<<8|e[n],3==(3&n)&&(t.push(r),r=0);return 3&n&&t.push(z.partial(8*(3&n),r)),t}}},C=class{constructor(e){const t=this;t.blockSize=512,t._init=[1732584193,4023233417,2562383102,271733878,3285377520],t._key=[1518500249,1859775393,2400959708,3395469782],e?(t._h=e._h.slice(0),t._buffer=e._buffer.slice(0),t._length=e._length):t.reset()}reset(){const e=this;return e._h=e._init.slice(0),e._buffer=[],e._length=0,e}update(e){const t=this;"string"==typeof e&&(e=D.utf8String.toBits(e));const n=t._buffer=z.concat(t._buffer,e),r=t._length,a=t._length=r+z.bitLength(e);if(a>9007199254740991)throw new s("Cannot hash more than 2^53 - 1 bits");const i=new o(n);let l=0;for(let e=t.blockSize+r-(t.blockSize+r&t.blockSize-1);a>=e;e+=t.blockSize)t._block(i.subarray(16*l,16*(l+1))),l+=1;return n.splice(0,16*l),t}finalize(){const e=this;let t=e._buffer;const n=e._h;t=z.concat(t,[z.partial(1,1)]);for(let e=t.length+2;15&e;e++)t.push(0);for(t.push(r.floor(e._length/4294967296)),t.push(0|e._length);t.length;)e._block(t.splice(0,16));return e.reset(),n}_f(e,t,n,r){return e>19?e>39?e>59?e>79?void 0:t^n^r:t&n|t&r|n&r:t^n^r:t&n|~t&r}_S(e,t){return t<<e|t>>>32-e}_block(t){const n=this,s=n._h,a=e(80);for(let e=0;16>e;e++)a[e]=t[e];let i=s[0],o=s[1],l=s[2],c=s[3],h=s[4];for(let e=0;79>=e;e++){16>e||(a[e]=n._S(1,a[e-3]^a[e-8]^a[e-14]^a[e-16]));const t=n._S(5,i)+n._f(e,o,l,c)+h+a[e]+n._key[r.floor(e/20)]|0;h=c,c=l,l=n._S(30,o),o=i,i=t}s[0]=s[0]+i|0,s[1]=s[1]+o|0,s[2]=s[2]+l|0,s[3]=s[3]+c|0,s[4]=s[4]+h|0}},I={getRandomValues(e){const t=new o(e.buffer),n=e=>{let t=987654321;const n=4294967295;return()=>(t=36969*(65535&t)+(t>>16)&n,(((t<<16)+(e=18e3*(65535&e)+(e>>16)&n)&n)/4294967296+.5)*(r.random()>.5?1:-1))};for(let s,a=0;a<e.length;a+=4){const e=n(4294967296*(s||r.random()));s=987654071*e(),t[a/4]=4294967296*e()|0}return e}},x={importKey:e=>new x.hmacSha1(D.bytes.toBits(e)),pbkdf2(e,t,n,r){if(n=n||1e4,0>r||0>n)throw new s("invalid params to pbkdf2");const a=1+(r>>5)<<2;let i,o,l,c,f;const u=new ArrayBuffer(a),p=new h(u);let d=0;const g=z;for(t=D.bytes.toBits(t),f=1;(a||1)>d;f++){for(i=o=e.encrypt(g.concat(t,[f])),l=1;n>l;l++)for(o=e.encrypt(o),c=0;c<o.length;c++)i[c]^=o[c];for(l=0;(a||1)>d&&l<i.length;l++)p.setInt32(d,i[l]),d+=4}return u.slice(0,r/8)},hmacSha1:class{constructor(e){const t=this,n=t._hash=C,r=[[],[]];t._baseHash=[new n,new n];const s=t._baseHash[0].blockSize/32;e.length>s&&(e=(new n).update(e).finalize());for(let t=0;s>t;t++)r[0][t]=909522486^e[t],r[1][t]=1549556828^e[t];t._baseHash[0].update(r[0]),t._baseHash[1].update(r[1]),t._resultHash=new n(t._baseHash[0])}reset(){const e=this;e._resultHash=new e._hash(e._baseHash[0]),e._updated=!1}update(e){this._updated=!0,this._resultHash.update(e)}digest(){const e=this,t=e._resultHash.finalize(),n=new e._hash(e._baseHash[1]).update(t).finalize();return e.reset(),n}encrypt(e){if(this._updated)throw new s("encrypt on already updated hmac called!");return this.update(e),this.digest(e)}}},A=void 0!==p&&"function"==typeof p.getRandomValues,T="Invalid password",R="Invalid signature",H="zipjs-abort-check-password";function q(e){return A?p.getRandomValues(e):I.getRandomValues(e)}const B=16,K={name:"PBKDF2"},V=t.assign({hash:{name:"HMAC"}},K),P=t.assign({iterations:1e3,hash:{name:"SHA-1"}},K),E=["deriveBits"],U=[8,12,16],W=[16,24,32],M=10,N=[0,0,0,0],O="undefined",F="function",L=typeof p!=O,j=L&&p.subtle,G=L&&typeof j!=O,X=D.bytes,J=class{constructor(e){const t=this;t._tables=[[[],[],[],[],[]],[[],[],[],[],[]]],t._tables[0][0][0]||t._precompute();const n=t._tables[0][4],r=t._tables[1],a=e.length;let i,o,l,c=1;if(4!==a&&6!==a&&8!==a)throw new s("invalid aes key size");for(t._key=[o=e.slice(0),l=[]],i=a;4*a+28>i;i++){let e=o[i-1];(i%a==0||8===a&&i%a==4)&&(e=n[e>>>24]<<24^n[e>>16&255]<<16^n[e>>8&255]<<8^n[255&e],i%a==0&&(e=e<<8^e>>>24^c<<24,c=c<<1^283*(c>>7))),o[i]=o[i-a]^e}for(let e=0;i;e++,i--){const t=o[3&e?i:i-4];l[e]=4>=i||4>e?t:r[0][n[t>>>24]]^r[1][n[t>>16&255]]^r[2][n[t>>8&255]]^r[3][n[255&t]]}}encrypt(e){return this._crypt(e,0)}decrypt(e){return this._crypt(e,1)}_precompute(){const e=this._tables[0],t=this._tables[1],n=e[4],r=t[4],s=[],a=[];let i,o,l,c;for(let e=0;256>e;e++)a[(s[e]=e<<1^283*(e>>7))^e]=e;for(let h=i=0;!n[h];h^=o||1,i=a[i]||1){let a=i^i<<1^i<<2^i<<3^i<<4;a=a>>8^255&a^99,n[h]=a,r[a]=h,c=s[l=s[o=s[h]]];let f=16843009*c^65537*l^257*o^16843008*h,u=257*s[a]^16843008*a;for(let n=0;4>n;n++)e[n][h]=u=u<<24^u>>>8,t[n][a]=f=f<<24^f>>>8}for(let n=0;5>n;n++)e[n]=e[n].slice(0),t[n]=t[n].slice(0)}_crypt(e,t){if(4!==e.length)throw new s("invalid aes block size");const n=this._key[t],r=n.length/4-2,a=[0,0,0,0],i=this._tables[t],o=i[0],l=i[1],c=i[2],h=i[3],f=i[4];let u,p,d,g=e[0]^n[0],w=e[t?3:1]^n[1],v=e[2]^n[2],y=e[t?1:3]^n[3],b=4;for(let e=0;r>e;e++)u=o[g>>>24]^l[w>>16&255]^c[v>>8&255]^h[255&y]^n[b],p=o[w>>>24]^l[v>>16&255]^c[y>>8&255]^h[255&g]^n[b+1],d=o[v>>>24]^l[y>>16&255]^c[g>>8&255]^h[255&w]^n[b+2],y=o[y>>>24]^l[g>>16&255]^c[w>>8&255]^h[255&v]^n[b+3],b+=4,g=u,w=p,v=d;for(let e=0;4>e;e++)a[t?3&-e:e]=f[g>>>24]<<24^f[w>>16&255]<<16^f[v>>8&255]<<8^f[255&y]^n[b++],u=g,g=w,w=v,v=y,y=u;return a}},Q=class{constructor(e,t){this._prf=e,this._initIv=t,this._iv=t}reset(){this._iv=this._initIv}update(e){return this.calculate(this._prf,e,this._iv)}incWord(e){if(255==(e>>24&255)){let t=e>>16&255,n=e>>8&255,r=255&e;255===t?(t=0,255===n?(n=0,255===r?r=0:++r):++n):++t,e=0,e+=t<<16,e+=n<<8,e+=r}else e+=1<<24;return e}incCounter(e){0===(e[0]=this.incWord(e[0]))&&(e[1]=this.incWord(e[1]))}calculate(e,t,n){let r;if(!(r=t.length))return[];const s=z.bitLength(t);for(let s=0;r>s;s+=4){this.incCounter(n);const r=e.encrypt(n);t[s]^=r[0],t[s+1]^=r[1],t[s+2]^=r[2],t[s+3]^=r[3]}return z.clamp(t,s)}},Y=x.hmacSha1;let Z=L&&G&&typeof j.importKey==F,$=L&&G&&typeof j.deriveBits==F;class ee extends g{constructor({password:e,signed:n,encryptionStrength:r,checkPasswordOnly:i}){super({start(){t.assign(this,{ready:new f((e=>this.resolveReady=e)),password:e,signed:n,strength:r-1,pending:new a})},async transform(e,t){const n=this,{password:r,strength:o,resolveReady:l,ready:c}=n;r?(await(async(e,t,n,r)=>{const a=await re(e,t,n,ae(r,0,U[t])),i=ae(r,U[t]);if(a[0]!=i[0]||a[1]!=i[1])throw new s(T)})(n,o,r,ae(e,0,U[o]+2)),e=ae(e,U[o]+2),i?t.error(new s(H)):l()):await c;const h=new a(e.length-M-(e.length-M)%B);t.enqueue(ne(n,e,h,0,M,!0))},async flush(e){const{signed:t,ctr:n,hmac:r,pending:i,ready:o}=this;await o;const l=ae(i,0,i.length-M),c=ae(i,i.length-M);let h=new a;if(l.length){const e=oe(X,l);r.update(e);const t=n.update(e);h=ie(X,t)}if(t){const e=ae(ie(X,r.digest()),0,M);for(let t=0;M>t;t++)if(e[t]!=c[t])throw new s(R)}e.enqueue(h)}})}}class te extends g{constructor({password:e,encryptionStrength:n}){let r;super({start(){t.assign(this,{ready:new f((e=>this.resolveReady=e)),password:e,strength:n-1,pending:new a})},async transform(e,t){const n=this,{password:r,strength:s,resolveReady:i,ready:o}=n;let l=new a;r?(l=await(async(e,t,n)=>{const r=q(new a(U[t]));return se(r,await re(e,t,n,r))})(n,s,r),i()):await o;const c=new a(l.length+e.length-e.length%B);c.set(l,0),t.enqueue(ne(n,e,c,l.length,0))},async flush(e){const{ctr:t,hmac:n,pending:s,ready:i}=this;await i;let o=new a;if(s.length){const e=t.update(oe(X,s));n.update(e),o=ie(X,e)}r.signature=ie(X,n.digest()).slice(0,M),e.enqueue(se(o,r.signature))}}),r=this}}function ne(e,t,n,r,s,i){const{ctr:o,hmac:l,pending:c}=e,h=t.length-s;let f;for(c.length&&(t=se(c,t),n=((e,t)=>{if(t&&t>e.length){const n=e;(e=new a(t)).set(n,0)}return e})(n,h-h%B)),f=0;h-B>=f;f+=B){const e=oe(X,ae(t,f,f+B));i&&l.update(e);const s=o.update(e);i||l.update(s),n.set(ie(X,s),f+r)}return e.pending=ae(t,f),n}async function re(n,r,s,i){n.password=null;const o=(e=>{if(void 0===u){const t=new a((e=unescape(encodeURIComponent(e))).length);for(let n=0;n<t.length;n++)t[n]=e.charCodeAt(n);return t}return(new u).encode(e)})(s),l=await(async(e,t,n,r,s)=>{if(!Z)return x.importKey(t);try{return await j.importKey("raw",t,n,!1,s)}catch(e){return Z=!1,x.importKey(t)}})(0,o,V,0,E),c=await(async(e,t,n)=>{if(!$)return x.pbkdf2(t,e.salt,P.iterations,n);try{return await j.deriveBits(e,t,n)}catch(r){return $=!1,x.pbkdf2(t,e.salt,P.iterations,n)}})(t.assign({salt:i},P),l,8*(2*W[r]+2)),h=new a(c),f=oe(X,ae(h,0,W[r])),p=oe(X,ae(h,W[r],2*W[r])),d=ae(h,2*W[r]);return t.assign(n,{keys:{key:f,authentication:p,passwordVerification:d},ctr:new Q(new J(f),e.from(N)),hmac:new Y(p)}),d}function se(e,t){let n=e;return e.length+t.length&&(n=new a(e.length+t.length),n.set(e,0),n.set(t,e.length)),n}function ae(e,t,n){return e.subarray(t,n)}function ie(e,t){return e.fromBits(t)}function oe(e,t){return e.toBits(t)}class le extends g{constructor({password:e,passwordVerification:n,checkPasswordOnly:r}){super({start(){t.assign(this,{password:e,passwordVerification:n}),ue(this,e)},transform(e,t){const n=this;if(n.password){const t=he(n,e.subarray(0,12));if(n.password=null,t[11]!=n.passwordVerification)throw new s(T);e=e.subarray(12)}r?t.error(new s(H)):t.enqueue(he(n,e))}})}}class ce extends g{constructor({password:e,passwordVerification:n}){super({start(){t.assign(this,{password:e,passwordVerification:n}),ue(this,e)},transform(e,t){const n=this;let r,s;if(n.password){n.password=null;const t=q(new a(12));t[11]=n.passwordVerification,r=new a(e.length+t.length),r.set(fe(n,t),0),s=12}else r=new a(e.length),s=0;r.set(fe(n,e),s),t.enqueue(r)}})}}function he(e,t){const n=new a(t.length);for(let r=0;r<t.length;r++)n[r]=de(e)^t[r],pe(e,n[r]);return n}function fe(e,t){const n=new a(t.length);for(let r=0;r<t.length;r++)n[r]=de(e)^t[r],pe(e,t[r]);return n}function ue(e,n){const r=[305419896,591751049,878082192];t.assign(e,{keys:r,crcKey0:new k(r[0]),crcKey2:new k(r[2])});for(let t=0;t<n.length;t++)pe(e,n.charCodeAt(t))}function pe(e,t){let[n,s,a]=e.keys;e.crcKey0.append([t]),n=~e.crcKey0.get(),s=we(r.imul(we(s+ge(n)),134775813)+1),e.crcKey2.append([s>>>24]),a=~e.crcKey2.get(),e.keys=[n,s,a]}function de(e){const t=2|e.keys[2];return ge(r.imul(t,1^t)>>>8)}function ge(e){return 255&e}function we(e){return 4294967295&e}const ve="deflate-raw";class ye extends g{constructor(e,{chunkSize:t,CompressionStream:n,CompressionStreamNative:r}){super({});const{compressed:s,encrypted:a,useCompressionStream:i,zipCrypto:o,signed:l,level:c}=e,f=this;let u,p,d=me(super.readable);a&&!o||!l||(u=new S,d=Se(d,u)),s&&(d=ke(d,i,{level:c,chunkSize:t},r,n)),a&&(o?d=Se(d,new ce(e)):(p=new te(e),d=Se(d,p))),_e(f,d,(()=>{let e;a&&!o&&(e=p.signature),a&&!o||!l||(e=new h(u.value.buffer).getUint32(0)),f.signature=e}))}}class be extends g{constructor(e,{chunkSize:t,DecompressionStream:n,DecompressionStreamNative:r}){super({});const{zipCrypto:a,encrypted:i,signed:o,signature:l,compressed:c,useCompressionStream:f}=e;let u,p,d=me(super.readable);i&&(a?d=Se(d,new le(e)):(p=new ee(e),d=Se(d,p))),c&&(d=ke(d,f,{chunkSize:t},r,n)),i&&!a||!o||(u=new S,d=Se(d,u)),_e(this,d,(()=>{if((!i||a)&&o){const e=new h(u.value.buffer);if(l!=e.getUint32(0,!1))throw new s(R)}}))}}function me(e){return Se(e,new g({transform(e,t){e&&e.length&&t.enqueue(e)}}))}function _e(e,n,r){n=Se(n,new g({flush:r})),t.defineProperty(e,"readable",{get:()=>n})}function ke(e,t,n,r,s){try{e=Se(e,new(t&&r?r:s)(ve,n))}catch(r){if(!t)throw r;e=Se(e,new s(ve,n))}return e}function Se(e,t){return e.pipeThrough(t)}const ze="data";class De extends g{constructor(e,n){super({});const r=this,{codecType:s}=e;let a;s.startsWith("deflate")?a=ye:s.startsWith("inflate")&&(a=be);let i=0;const o=new a(e,n),l=super.readable,c=new g({transform(e,t){e&&e.length&&(i+=e.length,t.enqueue(e))},flush(){const{signature:e}=o;t.assign(r,{signature:e,size:i})}});t.defineProperty(r,"readable",{get:()=>l.pipeThrough(o).pipeThrough(c)})}}const Ce=new c,Ie=new c;let xe=0;async function Ae(e){try{const{options:t,scripts:r,config:s}=e;r&&r.length&&importScripts.apply(void 0,r),self.initCodec&&self.initCodec(),s.CompressionStreamNative=self.CompressionStream,s.DecompressionStreamNative=self.DecompressionStream,self.Deflate&&(s.CompressionStream=new m(self.Deflate)),self.Inflate&&(s.DecompressionStream=new m(self.Inflate));const a={highWaterMark:1,size:()=>s.chunkSize},i=e.readable||new w({async pull(e){const t=new f((e=>Ce.set(xe,e)));Te({type:"pull",messageId:xe}),xe=(xe+1)%n.MAX_SAFE_INTEGER;const{value:r,done:s}=await t;e.enqueue(r),s&&e.close()}},a),o=e.writable||new v({async write(e){let t;const r=new f((e=>t=e));Ie.set(xe,t),Te({type:ze,value:e,messageId:xe}),xe=(xe+1)%n.MAX_SAFE_INTEGER,await r}},a),l=new De(t,s);await i.pipeThrough(l).pipeTo(o,{preventClose:!0,preventAbort:!0});try{await o.getWriter().close()}catch(e){}const{signature:c,size:h}=l;Te({type:"close",result:{signature:c,size:h}})}catch(e){Re(e)}}function Te(e){let{value:t}=e;if(t)if(t.length)try{t=new a(t),e.value=t.buffer,d(e,[e.value])}catch(t){d(e)}else d(e);else d(e)}function Re(e=new s("Unknown error")){const{message:t,stack:n,code:r,name:a}=e;d({error:{message:t,stack:n,code:r,name:a}})}addEventListener("message",(({data:e})=>{const{type:t,messageId:n,value:r,done:s}=e;try{if("start"==t&&Ae(e),t==ze){const e=Ce.get(n);Ce.delete(n),e({value:new a(r),done:s})}if("ack"==t){const e=Ie.get(n);Ie.delete(n),e()}}catch(e){Re(e)}}));var He=a,qe=i,Be=l,Ke=new He([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,0,0,0]),Ve=new He([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,0,0]),Pe=new He([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ee=(e,t)=>{for(var n=new qe(31),r=0;31>r;++r)n[r]=t+=1<<e[r-1];var s=new Be(n[30]);for(r=1;30>r;++r)for(var a=n[r];a<n[r+1];++a)s[a]=a-n[r]<<5|r;return{b:n,r:s}},Ue=Ee(Ke,2),We=Ue.b,Me=Ue.r;We[28]=258,Me[258]=28;for(var Ne=Ee(Ve,0),Oe=Ne.b,Fe=Ne.r,Le=new qe(32768),je=0;32768>je;++je){var Ge=(43690&je)>>1|(21845&je)<<1;Ge=(61680&(Ge=(52428&Ge)>>2|(13107&Ge)<<2))>>4|(3855&Ge)<<4,Le[je]=((65280&Ge)>>8|(255&Ge)<<8)>>1}var Xe=(e,t,n)=>{for(var r=e.length,s=0,a=new qe(t);r>s;++s)e[s]&&++a[e[s]-1];var i,o=new qe(t);for(s=1;t>s;++s)o[s]=o[s-1]+a[s-1]<<1;if(n){i=new qe(1<<t);var l=15-t;for(s=0;r>s;++s)if(e[s])for(var c=s<<4|e[s],h=t-e[s],f=o[e[s]-1]++<<h,u=f|(1<<h)-1;u>=f;++f)i[Le[f]>>l]=c}else for(i=new qe(r),s=0;r>s;++s)e[s]&&(i[s]=Le[o[e[s]-1]++]>>15-e[s]);return i},Je=new He(288);for(je=0;144>je;++je)Je[je]=8;for(je=144;256>je;++je)Je[je]=9;for(je=256;280>je;++je)Je[je]=7;for(je=280;288>je;++je)Je[je]=8;var Qe=new He(32);for(je=0;32>je;++je)Qe[je]=5;var Ye=Xe(Je,9,0),Ze=Xe(Je,9,1),$e=Xe(Qe,5,0),et=Xe(Qe,5,1),tt=e=>{for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},nt=(e,t,n)=>{var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},rt=(e,t)=>{var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},st=e=>(e+7)/8|0,at=(e,t,n)=>{(null==t||0>t)&&(t=0),(null==n||n>e.length)&&(n=e.length);var r=new He(n-t);return r.set(e.subarray(t,n)),r},it=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ot=(e,t,n)=>{var r=new s(t||it[e]);if(r.code=e,s.captureStackTrace&&s.captureStackTrace(r,ot),!n)throw r;return r},lt=(e,t,n)=>{n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},ct=(e,t,n)=>{n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},ht=(e,t)=>{for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var s=n.length,a=n.slice();if(!s)return{t:vt,l:0};if(1==s){var i=new He(n[0].s+1);return i[n[0].s]=1,{t:i,l:1}}n.sort(((e,t)=>e.f-t.f)),n.push({s:-1,f:25001});var o=n[0],l=n[1],c=0,h=1,f=2;for(n[0]={s:-1,f:o.f+l.f,l:o,r:l};h!=s-1;)o=n[n[c].f<n[f].f?c++:f++],l=n[c!=h&&n[c].f<n[f].f?c++:f++],n[h++]={s:-1,f:o.f+l.f,l:o,r:l};var u=a[0].s;for(r=1;s>r;++r)a[r].s>u&&(u=a[r].s);var p=new qe(u+1),d=ft(n[h-1],p,0);if(d>t){r=0;var g=0,w=d-t,v=1<<w;for(a.sort(((e,t)=>p[t.s]-p[e.s]||e.f-t.f));s>r;++r){var y=a[r].s;if(p[y]<=t)break;g+=v-(1<<d-p[y]),p[y]=t}for(g>>=w;g>0;){var b=a[r].s;p[b]<t?g-=1<<t-p[b]++-1:++r}for(;r>=0&&g;--r){var m=a[r].s;p[m]==t&&(--p[m],++g)}d=t}return{t:new He(p),l:d}},ft=(e,t,n)=>-1==e.s?r.max(ft(e.l,t,n+1),ft(e.r,t,n+1)):t[e.s]=n,ut=e=>{for(var t=e.length;t&&!e[--t];);for(var n=new qe(++t),r=0,s=e[0],a=1,i=e=>{n[r++]=e},o=1;t>=o;++o)if(e[o]==s&&o!=t)++a;else{if(!s&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(s),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(s);a=1,s=e[o]}return{c:n.subarray(0,r),n:t}},pt=(e,t)=>{for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},dt=(e,t,n)=>{var r=n.length,s=st(t+2);e[s]=255&r,e[s+1]=r>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var a=0;r>a;++a)e[s+a+4]=n[a];return 8*(s+4+r)},gt=(e,t,n,r,s,a,i,o,l,c,h)=>{lt(t,h++,n),++s[256];for(var f=ht(s,15),u=f.t,p=f.l,d=ht(a,15),g=d.t,w=d.l,v=ut(u),y=v.c,b=v.n,m=ut(g),_=m.c,k=m.n,S=new qe(19),z=0;z<y.length;++z)++S[31&y[z]];for(z=0;z<_.length;++z)++S[31&_[z]];for(var D=ht(S,7),C=D.t,I=D.l,x=19;x>4&&!C[Pe[x-1]];--x);var A,T,R,H,q=c+5<<3,B=pt(s,Je)+pt(a,Qe)+i,K=pt(s,u)+pt(a,g)+i+14+3*x+pt(S,C)+2*S[16]+3*S[17]+7*S[18];if(l>=0&&B>=q&&K>=q)return dt(t,h,e.subarray(l,l+c));if(lt(t,h,1+(B>K)),h+=2,B>K){A=Xe(u,p,0),T=u,R=Xe(g,w,0),H=g;var V=Xe(C,I,0);for(lt(t,h,b-257),lt(t,h+5,k-1),lt(t,h+10,x-4),h+=14,z=0;x>z;++z)lt(t,h+3*z,C[Pe[z]]);h+=3*x;for(var P=[y,_],E=0;2>E;++E){var U=P[E];for(z=0;z<U.length;++z){var W=31&U[z];lt(t,h,V[W]),h+=C[W],W>15&&(lt(t,h,U[z]>>5&127),h+=U[z]>>12)}}}else A=Ye,T=Je,R=$e,H=Qe;for(z=0;o>z;++z){var M=r[z];if(M>255){ct(t,h,A[257+(W=M>>18&31)]),h+=T[W+257],W>7&&(lt(t,h,M>>23&31),h+=Ke[W]);var N=31&M;ct(t,h,R[N]),h+=H[N],N>3&&(ct(t,h,M>>5&8191),h+=Ve[N])}else ct(t,h,A[M]),h+=T[M]}return ct(t,h,A[256]),h+T[256]},wt=new Be([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),vt=new He(0),yt=function(){function e(e,t){if("function"==typeof e&&(t=e,e={}),this.ondata=t,this.o=e||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new He(98304),this.o.dictionary){var n=this.o.dictionary.subarray(-32768);this.b.set(n,32768-n.length),this.s.i=32768-n.length}}return e.prototype.p=function(e,t){this.ondata(((e,t,n,s,a)=>{if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),o=new He(i.length+e.length);o.set(i),o.set(e,i.length),e=o,a.w=i.length}return((e,t,n,s,a,i)=>{var o=i.z||e.length,l=new He(0+o+5*(1+r.ceil(o/7e3))+0),c=l.subarray(0,l.length-0),h=i.l,f=7&(i.r||0);if(t){f&&(c[0]=i.r>>3);for(var u=wt[t-1],p=u>>13,d=8191&u,g=(1<<n)-1,w=i.p||new qe(32768),v=i.h||new qe(g+1),y=r.ceil(n/3),b=2*y,m=t=>(e[t]^e[t+1]<<y^e[t+2]<<b)&g,_=new Be(25e3),k=new qe(288),S=new qe(32),z=0,D=0,C=i.i||0,I=0,x=i.w||0,A=0;o>C+2;++C){var T=m(C),R=32767&C,H=v[T];if(w[R]=H,v[T]=R,C>=x){var q=o-C;if((z>7e3||I>24576)&&(q>423||!h)){f=gt(e,c,0,_,k,S,D,I,A,C-A,f),I=z=D=0,A=C;for(var B=0;286>B;++B)k[B]=0;for(B=0;30>B;++B)S[B]=0}var K=2,V=0,P=d,E=R-H&32767;if(q>2&&T==m(C-E))for(var U=r.min(p,q)-1,W=r.min(32767,C),M=r.min(258,q);W>=E&&--P&&R!=H;){if(e[C+K]==e[C+K-E]){for(var N=0;M>N&&e[C+N]==e[C+N-E];++N);if(N>K){if(K=N,V=E,N>U)break;var O=r.min(E,N-2),F=0;for(B=0;O>B;++B){var L=C-E+B&32767,j=L-w[L]&32767;j>F&&(F=j,H=L)}}}E+=(R=H)-(H=w[R])&32767}if(V){_[I++]=268435456|Me[K]<<18|Fe[V];var G=31&Me[K],X=31&Fe[V];D+=Ke[G]+Ve[X],++k[257+G],++S[X],x=C+K,++z}else _[I++]=e[C],++k[e[C]]}}for(C=r.max(C,x);o>C;++C)_[I++]=e[C],++k[e[C]];f=gt(e,c,h,_,k,S,D,I,A,C-A,f),h||(i.r=7&f|c[f/8|0]<<3,f-=7,i.h=v,i.p=w,i.i=C,i.w=x)}else{for(C=i.w||0;o+h>C;C+=65535){var J=C+65535;o>J||(c[f/8|0]=h,J=o),f=dt(c,f+1,e.subarray(C,J))}i.i=o}return at(l,0,0+st(f)+0)})(e,null==t.level?6:t.level,null==t.mem?r.ceil(1.5*r.max(8,r.min(13,r.log(e.length)))):12+t.mem,0,0,a)})(e,this.o,0,0,this.s),t)},e.prototype.push=function(e,t){this.ondata||ot(5),this.s.l&&ot(4);var n=e.length+this.s.z;if(n>this.b.length){if(n>2*this.b.length-32768){var r=new He(-32768&n);r.set(this.b.subarray(0,this.s.z)),this.b=r}var s=this.b.length-this.s.z;s&&(this.b.set(e.subarray(0,s),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(e.subarray(s),32768),this.s.z=e.length-s+32768,this.s.i=32766,this.s.w=32768}else this.b.set(e,this.s.z),this.s.z+=e.length;this.s.l=1&t,(this.s.z>this.s.w+8191||t)&&(this.p(this.b,t||!1),this.s.w=this.s.i,this.s.i-=2)},e}(),bt=function(){function e(e,t){"function"==typeof e&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new He(32768),this.p=new He(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||ot(5),this.d&&ot(4),this.p.length){if(e.length){var t=new He(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}}else this.p=e},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=((e,t,n)=>{var s=e.length;if(!s||t.f&&!t.l)return n||new He(0);var a=!n||2!=t.i,i=t.i;n||(n=new He(3*s));var o=e=>{var t=n.length;if(e>t){var s=new He(r.max(2*t,e));s.set(n),n=s}},l=t.f||0,c=t.p||0,h=t.b||0,f=t.l,u=t.d,p=t.m,d=t.n,g=8*s;do{if(!f){l=nt(e,c,1);var w=nt(e,c+1,3);if(c+=3,!w){var v=e[(x=st(c)+4)-4]|e[x-3]<<8,y=x+v;if(y>s){i&&ot(0);break}a&&o(h+v),n.set(e.subarray(x,y),h),t.b=h+=v,t.p=c=8*y,t.f=l;continue}if(1==w)f=Ze,u=et,p=9,d=5;else if(2==w){var b=nt(e,c,31)+257,m=nt(e,c+10,15)+4,_=b+nt(e,c+5,31)+1;c+=14;for(var k=new He(_),S=new He(19),z=0;m>z;++z)S[Pe[z]]=nt(e,c+3*z,7);c+=3*m;var D=tt(S),C=(1<<D)-1,I=Xe(S,D,1);for(z=0;_>z;){var x,A=I[nt(e,c,C)];if(c+=15&A,16>(x=A>>4))k[z++]=x;else{var T=0,R=0;for(16==x?(R=3+nt(e,c,3),c+=2,T=k[z-1]):17==x?(R=3+nt(e,c,7),c+=3):18==x&&(R=11+nt(e,c,127),c+=7);R--;)k[z++]=T}}var H=k.subarray(0,b),q=k.subarray(b);p=tt(H),d=tt(q),f=Xe(H,p,1),u=Xe(q,d,1)}else ot(1);if(c>g){i&&ot(0);break}}a&&o(h+131072);for(var B=(1<<p)-1,K=(1<<d)-1,V=c;;V=c){var P=(T=f[rt(e,c)&B])>>4;if((c+=15&T)>g){i&&ot(0);break}if(T||ot(2),256>P)n[h++]=P;else{if(256==P){V=c,f=null;break}var E=P-254;if(P>264){var U=Ke[z=P-257];E=nt(e,c,(1<<U)-1)+We[z],c+=U}var W=u[rt(e,c)&K],M=W>>4;if(W||ot(3),c+=15&W,q=Oe[M],M>3&&(U=Ve[M],q+=rt(e,c)&(1<<U)-1,c+=U),c>g){i&&ot(0);break}a&&o(h+131072);var N=h+E;if(q>h){var O=0-q,F=r.min(q,N);for(0>O+h&&ot(3);F>h;++h)n[h]=undefined[O+h]}for(;N>h;h+=4)n[h]=n[h-q],n[h+1]=n[h+1-q],n[h+2]=n[h+2-q],n[h+3]=n[h+3-q];h=N}}t.l=f,t.p=V,t.b=h,t.f=l,f&&(l=1,t.m=p,t.d=u,t.n=d)}while(!l);return h==n.length?n:at(n,0,h)})(this.p,this.s,this.o);this.ondata(at(n,t,this.s.b),this.d),this.o=at(n,this.s.b-32768),this.s.b=this.o.length,this.p=at(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),mt="undefined"!=typeof TextDecoder&&new TextDecoder;try{mt.decode(vt,{stream:!0})}catch(e){}function _t(e,n,r){return class{constructor(s){const i=this;var o,l;o=s,l="level",("function"==typeof t.hasOwn?t.hasOwn(o,l):o.hasOwnProperty(l))&&void 0===s.level&&delete s.level,i.codec=new e(t.assign({},n,s)),r(i.codec,(e=>{if(i.pendingData){const t=i.pendingData;i.pendingData=new a(t.length+e.length);const{pendingData:n}=i;n.set(t,0),n.set(e,t.length)}else i.pendingData=new a(e)}))}append(e){return this.codec.push(e),s(this)}flush(){return this.codec.push(new a,!0),s(this)}};function s(e){if(e.pendingData){const t=e.pendingData;return e.pendingData=null,t}return new a}}const{Deflate:kt,Inflate:St}=((e,t={},n)=>({Deflate:_t(e.Deflate,t.deflate,n),Inflate:_t(e.Inflate,t.inflate,n)}))({Deflate:yt,Inflate:bt},void 0,((e,t)=>e.ondata=t));self.initCodec=()=>{self.Deflate=kt,self.Inflate=St};\n'],{type:"text/javascript"}));e({workerScripts:{inflate:[t],deflate:[t]}});}
  209. /*
  210. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  211. Redistribution and use in source and binary forms, with or without
  212. modification, are permitted provided that the following conditions are met:
  213. 1. Redistributions of source code must retain the above copyright notice,
  214. this list of conditions and the following disclaimer.
  215. 2. Redistributions in binary form must reproduce the above copyright
  216. notice, this list of conditions and the following disclaimer in
  217. the documentation and/or other materials provided with the distribution.
  218. 3. The names of the authors may not be used to endorse or promote products
  219. derived from this software without specific prior written permission.
  220. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  221. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  222. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  223. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  224. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  225. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  226. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  227. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  228. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  229. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  230. */
  231. function getMimeType() {
  232. return "application/octet-stream";
  233. }
  234. function initShimAsyncCodec(library, options = {}, registerDataHandler) {
  235. return {
  236. Deflate: createCodecClass(library.Deflate, options.deflate, registerDataHandler),
  237. Inflate: createCodecClass(library.Inflate, options.inflate, registerDataHandler)
  238. };
  239. }
  240. function objectHasOwn(object, propertyName) {
  241. // eslint-disable-next-line no-prototype-builtins
  242. return typeof Object$1.hasOwn === "function" ? Object$1.hasOwn(object, propertyName) : object.hasOwnProperty(propertyName);
  243. }
  244. function createCodecClass(constructor, constructorOptions, registerDataHandler) {
  245. return class {
  246. constructor(options) {
  247. const codecAdapter = this;
  248. const onData = data => {
  249. if (codecAdapter.pendingData) {
  250. const previousPendingData = codecAdapter.pendingData;
  251. codecAdapter.pendingData = new Uint8Array$1(previousPendingData.length + data.length);
  252. const { pendingData } = codecAdapter;
  253. pendingData.set(previousPendingData, 0);
  254. pendingData.set(data, previousPendingData.length);
  255. } else {
  256. codecAdapter.pendingData = new Uint8Array$1(data);
  257. }
  258. };
  259. if (objectHasOwn(options, "level") && options.level === undefined) {
  260. delete options.level;
  261. }
  262. codecAdapter.codec = new constructor(Object$1.assign({}, constructorOptions, options));
  263. registerDataHandler(codecAdapter.codec, onData);
  264. }
  265. append(data) {
  266. this.codec.push(data);
  267. return getResponse(this);
  268. }
  269. flush() {
  270. this.codec.push(new Uint8Array$1(), true);
  271. return getResponse(this);
  272. }
  273. };
  274. function getResponse(codec) {
  275. if (codec.pendingData) {
  276. const output = codec.pendingData;
  277. codec.pendingData = null;
  278. return output;
  279. } else {
  280. return new Uint8Array$1();
  281. }
  282. }
  283. }
  284. /*
  285. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  286. Redistribution and use in source and binary forms, with or without
  287. modification, are permitted provided that the following conditions are met:
  288. 1. Redistributions of source code must retain the above copyright notice,
  289. this list of conditions and the following disclaimer.
  290. 2. Redistributions in binary form must reproduce the above copyright
  291. notice, this list of conditions and the following disclaimer in
  292. the documentation and/or other materials provided with the distribution.
  293. 3. The names of the authors may not be used to endorse or promote products
  294. derived from this software without specific prior written permission.
  295. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  296. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  297. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  298. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  299. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  300. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  301. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  302. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  303. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  304. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  305. */
  306. const table = [];
  307. for (let i = 0; i < 256; i++) {
  308. let t = i;
  309. for (let j = 0; j < 8; j++) {
  310. if (t & 1) {
  311. t = (t >>> 1) ^ 0xEDB88320;
  312. } else {
  313. t = t >>> 1;
  314. }
  315. }
  316. table[i] = t;
  317. }
  318. class Crc32 {
  319. constructor(crc) {
  320. this.crc = crc || -1;
  321. }
  322. append(data) {
  323. let crc = this.crc | 0;
  324. for (let offset = 0, length = data.length | 0; offset < length; offset++) {
  325. crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF];
  326. }
  327. this.crc = crc;
  328. }
  329. get() {
  330. return ~this.crc;
  331. }
  332. }
  333. /*
  334. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  335. Redistribution and use in source and binary forms, with or without
  336. modification, are permitted provided that the following conditions are met:
  337. 1. Redistributions of source code must retain the above copyright notice,
  338. this list of conditions and the following disclaimer.
  339. 2. Redistributions in binary form must reproduce the above copyright
  340. notice, this list of conditions and the following disclaimer in
  341. the documentation and/or other materials provided with the distribution.
  342. 3. The names of the authors may not be used to endorse or promote products
  343. derived from this software without specific prior written permission.
  344. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  345. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  346. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  347. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  348. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  349. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  350. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  351. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  352. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  353. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  354. */
  355. class Crc32Stream extends TransformStream {
  356. constructor() {
  357. let stream;
  358. const crc32 = new Crc32();
  359. super({
  360. transform(chunk, controller) {
  361. crc32.append(chunk);
  362. controller.enqueue(chunk);
  363. },
  364. flush() {
  365. const value = new Uint8Array$1(4);
  366. const dataView = new DataView(value.buffer);
  367. dataView.setUint32(0, crc32.get());
  368. stream.value = value;
  369. }
  370. });
  371. stream = this;
  372. }
  373. }
  374. /*
  375. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  376. Redistribution and use in source and binary forms, with or without
  377. modification, are permitted provided that the following conditions are met:
  378. 1. Redistributions of source code must retain the above copyright notice,
  379. this list of conditions and the following disclaimer.
  380. 2. Redistributions in binary form must reproduce the above copyright
  381. notice, this list of conditions and the following disclaimer in
  382. the documentation and/or other materials provided with the distribution.
  383. 3. The names of the authors may not be used to endorse or promote products
  384. derived from this software without specific prior written permission.
  385. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  386. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  387. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  388. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  389. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  390. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  391. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  392. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  393. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  394. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  395. */
  396. function encodeText(value) {
  397. if (typeof TextEncoder == "undefined") {
  398. value = unescape(encodeURIComponent(value));
  399. const result = new Uint8Array$1(value.length);
  400. for (let i = 0; i < result.length; i++) {
  401. result[i] = value.charCodeAt(i);
  402. }
  403. return result;
  404. } else {
  405. return new TextEncoder().encode(value);
  406. }
  407. }
  408. // Derived from https://github.com/xqdoo00o/jszip/blob/master/lib/sjcl.js and https://github.com/bitwiseshiftleft/sjcl
  409. // deno-lint-ignore-file no-this-alias
  410. /*
  411. * SJCL is open. You can use, modify and redistribute it under a BSD
  412. * license or under the GNU GPL, version 2.0.
  413. */
  414. /** @fileOverview Javascript cryptography implementation.
  415. *
  416. * Crush to remove comments, shorten variable names and
  417. * generally reduce transmission size.
  418. *
  419. * @author Emily Stark
  420. * @author Mike Hamburg
  421. * @author Dan Boneh
  422. */
  423. /*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */
  424. /** @fileOverview Arrays of bits, encoded as arrays of Numbers.
  425. *
  426. * @author Emily Stark
  427. * @author Mike Hamburg
  428. * @author Dan Boneh
  429. */
  430. /**
  431. * Arrays of bits, encoded as arrays of Numbers.
  432. * @namespace
  433. * @description
  434. * <p>
  435. * These objects are the currency accepted by SJCL's crypto functions.
  436. * </p>
  437. *
  438. * <p>
  439. * Most of our crypto primitives operate on arrays of 4-byte words internally,
  440. * but many of them can take arguments that are not a multiple of 4 bytes.
  441. * This library encodes arrays of bits (whose size need not be a multiple of 8
  442. * bits) as arrays of 32-bit words. The bits are packed, big-endian, into an
  443. * array of words, 32 bits at a time. Since the words are double-precision
  444. * floating point numbers, they fit some extra data. We use this (in a private,
  445. * possibly-changing manner) to encode the number of bits actually present
  446. * in the last word of the array.
  447. * </p>
  448. *
  449. * <p>
  450. * Because bitwise ops clear this out-of-band data, these arrays can be passed
  451. * to ciphers like AES which want arrays of words.
  452. * </p>
  453. */
  454. const bitArray = {
  455. /**
  456. * Concatenate two bit arrays.
  457. * @param {bitArray} a1 The first array.
  458. * @param {bitArray} a2 The second array.
  459. * @return {bitArray} The concatenation of a1 and a2.
  460. */
  461. concat(a1, a2) {
  462. if (a1.length === 0 || a2.length === 0) {
  463. return a1.concat(a2);
  464. }
  465. const last = a1[a1.length - 1], shift = bitArray.getPartial(last);
  466. if (shift === 32) {
  467. return a1.concat(a2);
  468. } else {
  469. return bitArray._shiftRight(a2, shift, last | 0, a1.slice(0, a1.length - 1));
  470. }
  471. },
  472. /**
  473. * Find the length of an array of bits.
  474. * @param {bitArray} a The array.
  475. * @return {Number} The length of a, in bits.
  476. */
  477. bitLength(a) {
  478. const l = a.length;
  479. if (l === 0) {
  480. return 0;
  481. }
  482. const x = a[l - 1];
  483. return (l - 1) * 32 + bitArray.getPartial(x);
  484. },
  485. /**
  486. * Truncate an array.
  487. * @param {bitArray} a The array.
  488. * @param {Number} len The length to truncate to, in bits.
  489. * @return {bitArray} A new array, truncated to len bits.
  490. */
  491. clamp(a, len) {
  492. if (a.length * 32 < len) {
  493. return a;
  494. }
  495. a = a.slice(0, Math$1.ceil(len / 32));
  496. const l = a.length;
  497. len = len & 31;
  498. if (l > 0 && len) {
  499. a[l - 1] = bitArray.partial(len, a[l - 1] & 0x80000000 >> (len - 1), 1);
  500. }
  501. return a;
  502. },
  503. /**
  504. * Make a partial word for a bit array.
  505. * @param {Number} len The number of bits in the word.
  506. * @param {Number} x The bits.
  507. * @param {Number} [_end=0] Pass 1 if x has already been shifted to the high side.
  508. * @return {Number} The partial word.
  509. */
  510. partial(len, x, _end) {
  511. if (len === 32) {
  512. return x;
  513. }
  514. return (_end ? x | 0 : x << (32 - len)) + len * 0x10000000000;
  515. },
  516. /**
  517. * Get the number of bits used by a partial word.
  518. * @param {Number} x The partial word.
  519. * @return {Number} The number of bits used by the partial word.
  520. */
  521. getPartial(x) {
  522. return Math$1.round(x / 0x10000000000) || 32;
  523. },
  524. /** Shift an array right.
  525. * @param {bitArray} a The array to shift.
  526. * @param {Number} shift The number of bits to shift.
  527. * @param {Number} [carry=0] A byte to carry in
  528. * @param {bitArray} [out=[]] An array to prepend to the output.
  529. * @private
  530. */
  531. _shiftRight(a, shift, carry, out) {
  532. if (out === undefined) {
  533. out = [];
  534. }
  535. for (; shift >= 32; shift -= 32) {
  536. out.push(carry);
  537. carry = 0;
  538. }
  539. if (shift === 0) {
  540. return out.concat(a);
  541. }
  542. for (let i = 0; i < a.length; i++) {
  543. out.push(carry | a[i] >>> shift);
  544. carry = a[i] << (32 - shift);
  545. }
  546. const last2 = a.length ? a[a.length - 1] : 0;
  547. const shift2 = bitArray.getPartial(last2);
  548. out.push(bitArray.partial(shift + shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(), 1));
  549. return out;
  550. }
  551. };
  552. /** @fileOverview Bit array codec implementations.
  553. *
  554. * @author Emily Stark
  555. * @author Mike Hamburg
  556. * @author Dan Boneh
  557. */
  558. /**
  559. * Arrays of bytes
  560. * @namespace
  561. */
  562. const codec = {
  563. bytes: {
  564. /** Convert from a bitArray to an array of bytes. */
  565. fromBits(arr) {
  566. const bl = bitArray.bitLength(arr);
  567. const byteLength = bl / 8;
  568. const out = new Uint8Array$1(byteLength);
  569. let tmp;
  570. for (let i = 0; i < byteLength; i++) {
  571. if ((i & 3) === 0) {
  572. tmp = arr[i / 4];
  573. }
  574. out[i] = tmp >>> 24;
  575. tmp <<= 8;
  576. }
  577. return out;
  578. },
  579. /** Convert from an array of bytes to a bitArray. */
  580. toBits(bytes) {
  581. const out = [];
  582. let i;
  583. let tmp = 0;
  584. for (i = 0; i < bytes.length; i++) {
  585. tmp = tmp << 8 | bytes[i];
  586. if ((i & 3) === 3) {
  587. out.push(tmp);
  588. tmp = 0;
  589. }
  590. }
  591. if (i & 3) {
  592. out.push(bitArray.partial(8 * (i & 3), tmp));
  593. }
  594. return out;
  595. }
  596. }
  597. };
  598. const hash = {};
  599. /**
  600. * Context for a SHA-1 operation in progress.
  601. * @constructor
  602. */
  603. hash.sha1 = class {
  604. constructor(hash) {
  605. const sha1 = this;
  606. /**
  607. * The hash's block size, in bits.
  608. * @constant
  609. */
  610. sha1.blockSize = 512;
  611. /**
  612. * The SHA-1 initialization vector.
  613. * @private
  614. */
  615. sha1._init = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
  616. /**
  617. * The SHA-1 hash key.
  618. * @private
  619. */
  620. sha1._key = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6];
  621. if (hash) {
  622. sha1._h = hash._h.slice(0);
  623. sha1._buffer = hash._buffer.slice(0);
  624. sha1._length = hash._length;
  625. } else {
  626. sha1.reset();
  627. }
  628. }
  629. /**
  630. * Reset the hash state.
  631. * @return this
  632. */
  633. reset() {
  634. const sha1 = this;
  635. sha1._h = sha1._init.slice(0);
  636. sha1._buffer = [];
  637. sha1._length = 0;
  638. return sha1;
  639. }
  640. /**
  641. * Input several words to the hash.
  642. * @param {bitArray|String} data the data to hash.
  643. * @return this
  644. */
  645. update(data) {
  646. const sha1 = this;
  647. if (typeof data === "string") {
  648. data = codec.utf8String.toBits(data);
  649. }
  650. const b = sha1._buffer = bitArray.concat(sha1._buffer, data);
  651. const ol = sha1._length;
  652. const nl = sha1._length = ol + bitArray.bitLength(data);
  653. if (nl > 9007199254740991) {
  654. throw new Error("Cannot hash more than 2^53 - 1 bits");
  655. }
  656. const c = new Uint32Array(b);
  657. let j = 0;
  658. for (let i = sha1.blockSize + ol - ((sha1.blockSize + ol) & (sha1.blockSize - 1)); i <= nl;
  659. i += sha1.blockSize) {
  660. sha1._block(c.subarray(16 * j, 16 * (j + 1)));
  661. j += 1;
  662. }
  663. b.splice(0, 16 * j);
  664. return sha1;
  665. }
  666. /**
  667. * Complete hashing and output the hash value.
  668. * @return {bitArray} The hash value, an array of 5 big-endian words. TODO
  669. */
  670. finalize() {
  671. const sha1 = this;
  672. let b = sha1._buffer;
  673. const h = sha1._h;
  674. // Round out and push the buffer
  675. b = bitArray.concat(b, [bitArray.partial(1, 1)]);
  676. // Round out the buffer to a multiple of 16 words, less the 2 length words.
  677. for (let i = b.length + 2; i & 15; i++) {
  678. b.push(0);
  679. }
  680. // append the length
  681. b.push(Math$1.floor(sha1._length / 0x100000000));
  682. b.push(sha1._length | 0);
  683. while (b.length) {
  684. sha1._block(b.splice(0, 16));
  685. }
  686. sha1.reset();
  687. return h;
  688. }
  689. /**
  690. * The SHA-1 logical functions f(0), f(1), ..., f(79).
  691. * @private
  692. */
  693. _f(t, b, c, d) {
  694. if (t <= 19) {
  695. return (b & c) | (~b & d);
  696. } else if (t <= 39) {
  697. return b ^ c ^ d;
  698. } else if (t <= 59) {
  699. return (b & c) | (b & d) | (c & d);
  700. } else if (t <= 79) {
  701. return b ^ c ^ d;
  702. }
  703. }
  704. /**
  705. * Circular left-shift operator.
  706. * @private
  707. */
  708. _S(n, x) {
  709. return (x << n) | (x >>> 32 - n);
  710. }
  711. /**
  712. * Perform one cycle of SHA-1.
  713. * @param {Uint32Array|bitArray} words one block of words.
  714. * @private
  715. */
  716. _block(words) {
  717. const sha1 = this;
  718. const h = sha1._h;
  719. // When words is passed to _block, it has 16 elements. SHA1 _block
  720. // function extends words with new elements (at the end there are 80 elements).
  721. // The problem is that if we use Uint32Array instead of Array,
  722. // the length of Uint32Array cannot be changed. Thus, we replace words with a
  723. // normal Array here.
  724. const w = Array$1(80); // do not use Uint32Array here as the instantiation is slower
  725. for (let j = 0; j < 16; j++) {
  726. w[j] = words[j];
  727. }
  728. let a = h[0];
  729. let b = h[1];
  730. let c = h[2];
  731. let d = h[3];
  732. let e = h[4];
  733. for (let t = 0; t <= 79; t++) {
  734. if (t >= 16) {
  735. w[t] = sha1._S(1, w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]);
  736. }
  737. const tmp = (sha1._S(5, a) + sha1._f(t, b, c, d) + e + w[t] +
  738. sha1._key[Math$1.floor(t / 20)]) | 0;
  739. e = d;
  740. d = c;
  741. c = sha1._S(30, b);
  742. b = a;
  743. a = tmp;
  744. }
  745. h[0] = (h[0] + a) | 0;
  746. h[1] = (h[1] + b) | 0;
  747. h[2] = (h[2] + c) | 0;
  748. h[3] = (h[3] + d) | 0;
  749. h[4] = (h[4] + e) | 0;
  750. }
  751. };
  752. /** @fileOverview Low-level AES implementation.
  753. *
  754. * This file contains a low-level implementation of AES, optimized for
  755. * size and for efficiency on several browsers. It is based on
  756. * OpenSSL's aes_core.c, a public-domain implementation by Vincent
  757. * Rijmen, Antoon Bosselaers and Paulo Barreto.
  758. *
  759. * An older version of this implementation is available in the public
  760. * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,
  761. * Stanford University 2008-2010 and BSD-licensed for liability
  762. * reasons.
  763. *
  764. * @author Emily Stark
  765. * @author Mike Hamburg
  766. * @author Dan Boneh
  767. */
  768. const cipher = {};
  769. /**
  770. * Schedule out an AES key for both encryption and decryption. This
  771. * is a low-level class. Use a cipher mode to do bulk encryption.
  772. *
  773. * @constructor
  774. * @param {Array} key The key as an array of 4, 6 or 8 words.
  775. */
  776. cipher.aes = class {
  777. constructor(key) {
  778. /**
  779. * The expanded S-box and inverse S-box tables. These will be computed
  780. * on the client so that we don't have to send them down the wire.
  781. *
  782. * There are two tables, _tables[0] is for encryption and
  783. * _tables[1] is for decryption.
  784. *
  785. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  786. * last (_tables[01][4]) is the S-box itself.
  787. *
  788. * @private
  789. */
  790. const aes = this;
  791. aes._tables = [[[], [], [], [], []], [[], [], [], [], []]];
  792. if (!aes._tables[0][0][0]) {
  793. aes._precompute();
  794. }
  795. const sbox = aes._tables[0][4];
  796. const decTable = aes._tables[1];
  797. const keyLen = key.length;
  798. let i, encKey, decKey, rcon = 1;
  799. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  800. throw new Error("invalid aes key size");
  801. }
  802. aes._key = [encKey = key.slice(0), decKey = []];
  803. // schedule encryption keys
  804. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  805. let tmp = encKey[i - 1];
  806. // apply sbox
  807. if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {
  808. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
  809. // shift rows and add rcon
  810. if (i % keyLen === 0) {
  811. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  812. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  813. }
  814. }
  815. encKey[i] = encKey[i - keyLen] ^ tmp;
  816. }
  817. // schedule decryption keys
  818. for (let j = 0; i; j++, i--) {
  819. const tmp = encKey[j & 3 ? i : i - 4];
  820. if (i <= 4 || j < 4) {
  821. decKey[j] = tmp;
  822. } else {
  823. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^
  824. decTable[1][sbox[tmp >> 16 & 255]] ^
  825. decTable[2][sbox[tmp >> 8 & 255]] ^
  826. decTable[3][sbox[tmp & 255]];
  827. }
  828. }
  829. }
  830. // public
  831. /* Something like this might appear here eventually
  832. name: "AES",
  833. blockSize: 4,
  834. keySizes: [4,6,8],
  835. */
  836. /**
  837. * Encrypt an array of 4 big-endian words.
  838. * @param {Array} data The plaintext.
  839. * @return {Array} The ciphertext.
  840. */
  841. encrypt(data) {
  842. return this._crypt(data, 0);
  843. }
  844. /**
  845. * Decrypt an array of 4 big-endian words.
  846. * @param {Array} data The ciphertext.
  847. * @return {Array} The plaintext.
  848. */
  849. decrypt(data) {
  850. return this._crypt(data, 1);
  851. }
  852. /**
  853. * Expand the S-box tables.
  854. *
  855. * @private
  856. */
  857. _precompute() {
  858. const encTable = this._tables[0];
  859. const decTable = this._tables[1];
  860. const sbox = encTable[4];
  861. const sboxInv = decTable[4];
  862. const d = [];
  863. const th = [];
  864. let xInv, x2, x4, x8;
  865. // Compute double and third tables
  866. for (let i = 0; i < 256; i++) {
  867. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  868. }
  869. for (let x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  870. // Compute sbox
  871. let s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  872. s = s >> 8 ^ s & 255 ^ 99;
  873. sbox[x] = s;
  874. sboxInv[s] = x;
  875. // Compute MixColumns
  876. x8 = d[x4 = d[x2 = d[x]]];
  877. let tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  878. let tEnc = d[s] * 0x101 ^ s * 0x1010100;
  879. for (let i = 0; i < 4; i++) {
  880. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  881. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  882. }
  883. }
  884. // Compactify. Considerable speedup on Firefox.
  885. for (let i = 0; i < 5; i++) {
  886. encTable[i] = encTable[i].slice(0);
  887. decTable[i] = decTable[i].slice(0);
  888. }
  889. }
  890. /**
  891. * Encryption and decryption core.
  892. * @param {Array} input Four words to be encrypted or decrypted.
  893. * @param dir The direction, 0 for encrypt and 1 for decrypt.
  894. * @return {Array} The four encrypted or decrypted words.
  895. * @private
  896. */
  897. _crypt(input, dir) {
  898. if (input.length !== 4) {
  899. throw new Error("invalid aes block size");
  900. }
  901. const key = this._key[dir];
  902. const nInnerRounds = key.length / 4 - 2;
  903. const out = [0, 0, 0, 0];
  904. const table = this._tables[dir];
  905. // load up the tables
  906. const t0 = table[0];
  907. const t1 = table[1];
  908. const t2 = table[2];
  909. const t3 = table[3];
  910. const sbox = table[4];
  911. // state variables a,b,c,d are loaded with pre-whitened data
  912. let a = input[0] ^ key[0];
  913. let b = input[dir ? 3 : 1] ^ key[1];
  914. let c = input[2] ^ key[2];
  915. let d = input[dir ? 1 : 3] ^ key[3];
  916. let kIndex = 4;
  917. let a2, b2, c2;
  918. // Inner rounds. Cribbed from OpenSSL.
  919. for (let i = 0; i < nInnerRounds; i++) {
  920. a2 = t0[a >>> 24] ^ t1[b >> 16 & 255] ^ t2[c >> 8 & 255] ^ t3[d & 255] ^ key[kIndex];
  921. b2 = t0[b >>> 24] ^ t1[c >> 16 & 255] ^ t2[d >> 8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];
  922. c2 = t0[c >>> 24] ^ t1[d >> 16 & 255] ^ t2[a >> 8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
  923. d = t0[d >>> 24] ^ t1[a >> 16 & 255] ^ t2[b >> 8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
  924. kIndex += 4;
  925. a = a2; b = b2; c = c2;
  926. }
  927. // Last round.
  928. for (let i = 0; i < 4; i++) {
  929. out[dir ? 3 & -i : i] =
  930. sbox[a >>> 24] << 24 ^
  931. sbox[b >> 16 & 255] << 16 ^
  932. sbox[c >> 8 & 255] << 8 ^
  933. sbox[d & 255] ^
  934. key[kIndex++];
  935. a2 = a; a = b; b = c; c = d; d = a2;
  936. }
  937. return out;
  938. }
  939. };
  940. /**
  941. * Random values
  942. * @namespace
  943. */
  944. const random = {
  945. /**
  946. * Generate random words with pure js, cryptographically not as strong & safe as native implementation.
  947. * @param {TypedArray} typedArray The array to fill.
  948. * @return {TypedArray} The random values.
  949. */
  950. getRandomValues(typedArray) {
  951. const words = new Uint32Array(typedArray.buffer);
  952. const r = (m_w) => {
  953. let m_z = 0x3ade68b1;
  954. const mask = 0xffffffff;
  955. return function () {
  956. m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
  957. m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
  958. const result = ((((m_z << 0x10) + m_w) & mask) / 0x100000000) + .5;
  959. return result * (Math$1.random() > .5 ? 1 : -1);
  960. };
  961. };
  962. for (let i = 0, rcache; i < typedArray.length; i += 4) {
  963. const _r = r((rcache || Math$1.random()) * 0x100000000);
  964. rcache = _r() * 0x3ade67b7;
  965. words[i / 4] = (_r() * 0x100000000) | 0;
  966. }
  967. return typedArray;
  968. }
  969. };
  970. /** @fileOverview CTR mode implementation.
  971. *
  972. * Special thanks to Roy Nicholson for pointing out a bug in our
  973. * implementation.
  974. *
  975. * @author Emily Stark
  976. * @author Mike Hamburg
  977. * @author Dan Boneh
  978. */
  979. /** Brian Gladman's CTR Mode.
  980. * @constructor
  981. * @param {Object} _prf The aes instance to generate key.
  982. * @param {bitArray} _iv The iv for ctr mode, it must be 128 bits.
  983. */
  984. const mode = {};
  985. /**
  986. * Brian Gladman's CTR Mode.
  987. * @namespace
  988. */
  989. mode.ctrGladman = class {
  990. constructor(prf, iv) {
  991. this._prf = prf;
  992. this._initIv = iv;
  993. this._iv = iv;
  994. }
  995. reset() {
  996. this._iv = this._initIv;
  997. }
  998. /** Input some data to calculate.
  999. * @param {bitArray} data the data to process, it must be intergral multiple of 128 bits unless it's the last.
  1000. */
  1001. update(data) {
  1002. return this.calculate(this._prf, data, this._iv);
  1003. }
  1004. incWord(word) {
  1005. if (((word >> 24) & 0xff) === 0xff) { //overflow
  1006. let b1 = (word >> 16) & 0xff;
  1007. let b2 = (word >> 8) & 0xff;
  1008. let b3 = word & 0xff;
  1009. if (b1 === 0xff) { // overflow b1
  1010. b1 = 0;
  1011. if (b2 === 0xff) {
  1012. b2 = 0;
  1013. if (b3 === 0xff) {
  1014. b3 = 0;
  1015. } else {
  1016. ++b3;
  1017. }
  1018. } else {
  1019. ++b2;
  1020. }
  1021. } else {
  1022. ++b1;
  1023. }
  1024. word = 0;
  1025. word += (b1 << 16);
  1026. word += (b2 << 8);
  1027. word += b3;
  1028. } else {
  1029. word += (0x01 << 24);
  1030. }
  1031. return word;
  1032. }
  1033. incCounter(counter) {
  1034. if ((counter[0] = this.incWord(counter[0])) === 0) {
  1035. // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
  1036. counter[1] = this.incWord(counter[1]);
  1037. }
  1038. }
  1039. calculate(prf, data, iv) {
  1040. let l;
  1041. if (!(l = data.length)) {
  1042. return [];
  1043. }
  1044. const bl = bitArray.bitLength(data);
  1045. for (let i = 0; i < l; i += 4) {
  1046. this.incCounter(iv);
  1047. const e = prf.encrypt(iv);
  1048. data[i] ^= e[0];
  1049. data[i + 1] ^= e[1];
  1050. data[i + 2] ^= e[2];
  1051. data[i + 3] ^= e[3];
  1052. }
  1053. return bitArray.clamp(data, bl);
  1054. }
  1055. };
  1056. const misc = {
  1057. importKey(password) {
  1058. return new misc.hmacSha1(codec.bytes.toBits(password));
  1059. },
  1060. pbkdf2(prf, salt, count, length) {
  1061. count = count || 10000;
  1062. if (length < 0 || count < 0) {
  1063. throw new Error("invalid params to pbkdf2");
  1064. }
  1065. const byteLength = ((length >> 5) + 1) << 2;
  1066. let u, ui, i, j, k;
  1067. const arrayBuffer = new ArrayBuffer(byteLength);
  1068. const out = new DataView(arrayBuffer);
  1069. let outLength = 0;
  1070. const b = bitArray;
  1071. salt = codec.bytes.toBits(salt);
  1072. for (k = 1; outLength < (byteLength || 1); k++) {
  1073. u = ui = prf.encrypt(b.concat(salt, [k]));
  1074. for (i = 1; i < count; i++) {
  1075. ui = prf.encrypt(ui);
  1076. for (j = 0; j < ui.length; j++) {
  1077. u[j] ^= ui[j];
  1078. }
  1079. }
  1080. for (i = 0; outLength < (byteLength || 1) && i < u.length; i++) {
  1081. out.setInt32(outLength, u[i]);
  1082. outLength += 4;
  1083. }
  1084. }
  1085. return arrayBuffer.slice(0, length / 8);
  1086. }
  1087. };
  1088. /** @fileOverview HMAC implementation.
  1089. *
  1090. * @author Emily Stark
  1091. * @author Mike Hamburg
  1092. * @author Dan Boneh
  1093. */
  1094. /** HMAC with the specified hash function.
  1095. * @constructor
  1096. * @param {bitArray} key the key for HMAC.
  1097. * @param {Object} [Hash=hash.sha1] The hash function to use.
  1098. */
  1099. misc.hmacSha1 = class {
  1100. constructor(key) {
  1101. const hmac = this;
  1102. const Hash = hmac._hash = hash.sha1;
  1103. const exKey = [[], []];
  1104. hmac._baseHash = [new Hash(), new Hash()];
  1105. const bs = hmac._baseHash[0].blockSize / 32;
  1106. if (key.length > bs) {
  1107. key = new Hash().update(key).finalize();
  1108. }
  1109. for (let i = 0; i < bs; i++) {
  1110. exKey[0][i] = key[i] ^ 0x36363636;
  1111. exKey[1][i] = key[i] ^ 0x5C5C5C5C;
  1112. }
  1113. hmac._baseHash[0].update(exKey[0]);
  1114. hmac._baseHash[1].update(exKey[1]);
  1115. hmac._resultHash = new Hash(hmac._baseHash[0]);
  1116. }
  1117. reset() {
  1118. const hmac = this;
  1119. hmac._resultHash = new hmac._hash(hmac._baseHash[0]);
  1120. hmac._updated = false;
  1121. }
  1122. update(data) {
  1123. const hmac = this;
  1124. hmac._updated = true;
  1125. hmac._resultHash.update(data);
  1126. }
  1127. digest() {
  1128. const hmac = this;
  1129. const w = hmac._resultHash.finalize();
  1130. const result = new (hmac._hash)(hmac._baseHash[1]).update(w).finalize();
  1131. hmac.reset();
  1132. return result;
  1133. }
  1134. encrypt(data) {
  1135. if (!this._updated) {
  1136. this.update(data);
  1137. return this.digest(data);
  1138. } else {
  1139. throw new Error("encrypt on already updated hmac called!");
  1140. }
  1141. }
  1142. };
  1143. /*
  1144. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1145. Redistribution and use in source and binary forms, with or without
  1146. modification, are permitted provided that the following conditions are met:
  1147. 1. Redistributions of source code must retain the above copyright notice,
  1148. this list of conditions and the following disclaimer.
  1149. 2. Redistributions in binary form must reproduce the above copyright
  1150. notice, this list of conditions and the following disclaimer in
  1151. the documentation and/or other materials provided with the distribution.
  1152. 3. The names of the authors may not be used to endorse or promote products
  1153. derived from this software without specific prior written permission.
  1154. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1155. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1156. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1157. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1158. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1159. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1160. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1161. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1162. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1163. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1164. */
  1165. const GET_RANDOM_VALUES_SUPPORTED = typeof crypto != "undefined" && typeof crypto.getRandomValues == "function";
  1166. const ERR_INVALID_PASSWORD = "Invalid password";
  1167. const ERR_INVALID_SIGNATURE = "Invalid signature";
  1168. const ERR_ABORT_CHECK_PASSWORD = "zipjs-abort-check-password";
  1169. function getRandomValues(array) {
  1170. if (GET_RANDOM_VALUES_SUPPORTED) {
  1171. return crypto.getRandomValues(array);
  1172. } else {
  1173. return random.getRandomValues(array);
  1174. }
  1175. }
  1176. /*
  1177. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1178. Redistribution and use in source and binary forms, with or without
  1179. modification, are permitted provided that the following conditions are met:
  1180. 1. Redistributions of source code must retain the above copyright notice,
  1181. this list of conditions and the following disclaimer.
  1182. 2. Redistributions in binary form must reproduce the above copyright
  1183. notice, this list of conditions and the following disclaimer in
  1184. the documentation and/or other materials provided with the distribution.
  1185. 3. The names of the authors may not be used to endorse or promote products
  1186. derived from this software without specific prior written permission.
  1187. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1188. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1189. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1190. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1191. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1192. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1193. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1194. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1195. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1196. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1197. */
  1198. const BLOCK_LENGTH = 16;
  1199. const RAW_FORMAT = "raw";
  1200. const PBKDF2_ALGORITHM = { name: "PBKDF2" };
  1201. const HASH_ALGORITHM = { name: "HMAC" };
  1202. const HASH_FUNCTION = "SHA-1";
  1203. const BASE_KEY_ALGORITHM = Object$1.assign({ hash: HASH_ALGORITHM }, PBKDF2_ALGORITHM);
  1204. const DERIVED_BITS_ALGORITHM = Object$1.assign({ iterations: 1000, hash: { name: HASH_FUNCTION } }, PBKDF2_ALGORITHM);
  1205. const DERIVED_BITS_USAGE = ["deriveBits"];
  1206. const SALT_LENGTH = [8, 12, 16];
  1207. const KEY_LENGTH = [16, 24, 32];
  1208. const SIGNATURE_LENGTH = 10;
  1209. const COUNTER_DEFAULT_VALUE = [0, 0, 0, 0];
  1210. const UNDEFINED_TYPE = "undefined";
  1211. const FUNCTION_TYPE = "function";
  1212. // deno-lint-ignore valid-typeof
  1213. const CRYPTO_API_SUPPORTED = typeof crypto != UNDEFINED_TYPE;
  1214. const subtle = CRYPTO_API_SUPPORTED && crypto.subtle;
  1215. const SUBTLE_API_SUPPORTED = CRYPTO_API_SUPPORTED && typeof subtle != UNDEFINED_TYPE;
  1216. const codecBytes = codec.bytes;
  1217. const Aes = cipher.aes;
  1218. const CtrGladman = mode.ctrGladman;
  1219. const HmacSha1 = misc.hmacSha1;
  1220. let IMPORT_KEY_SUPPORTED = CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof subtle.importKey == FUNCTION_TYPE;
  1221. let DERIVE_BITS_SUPPORTED = CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof subtle.deriveBits == FUNCTION_TYPE;
  1222. class AESDecryptionStream extends TransformStream {
  1223. constructor({ password, signed, encryptionStrength, checkPasswordOnly }) {
  1224. super({
  1225. start() {
  1226. Object$1.assign(this, {
  1227. ready: new Promise$1(resolve => this.resolveReady = resolve),
  1228. password,
  1229. signed,
  1230. strength: encryptionStrength - 1,
  1231. pending: new Uint8Array$1()
  1232. });
  1233. },
  1234. async transform(chunk, controller) {
  1235. const aesCrypto = this;
  1236. const {
  1237. password,
  1238. strength,
  1239. resolveReady,
  1240. ready
  1241. } = aesCrypto;
  1242. if (password) {
  1243. await createDecryptionKeys(aesCrypto, strength, password, subarray(chunk, 0, SALT_LENGTH[strength] + 2));
  1244. chunk = subarray(chunk, SALT_LENGTH[strength] + 2);
  1245. if (checkPasswordOnly) {
  1246. controller.error(new Error(ERR_ABORT_CHECK_PASSWORD));
  1247. } else {
  1248. resolveReady();
  1249. }
  1250. } else {
  1251. await ready;
  1252. }
  1253. const output = new Uint8Array$1(chunk.length - SIGNATURE_LENGTH - ((chunk.length - SIGNATURE_LENGTH) % BLOCK_LENGTH));
  1254. controller.enqueue(append(aesCrypto, chunk, output, 0, SIGNATURE_LENGTH, true));
  1255. },
  1256. async flush(controller) {
  1257. const {
  1258. signed,
  1259. ctr,
  1260. hmac,
  1261. pending,
  1262. ready
  1263. } = this;
  1264. await ready;
  1265. const chunkToDecrypt = subarray(pending, 0, pending.length - SIGNATURE_LENGTH);
  1266. const originalSignature = subarray(pending, pending.length - SIGNATURE_LENGTH);
  1267. let decryptedChunkArray = new Uint8Array$1();
  1268. if (chunkToDecrypt.length) {
  1269. const encryptedChunk = toBits(codecBytes, chunkToDecrypt);
  1270. hmac.update(encryptedChunk);
  1271. const decryptedChunk = ctr.update(encryptedChunk);
  1272. decryptedChunkArray = fromBits(codecBytes, decryptedChunk);
  1273. }
  1274. if (signed) {
  1275. const signature = subarray(fromBits(codecBytes, hmac.digest()), 0, SIGNATURE_LENGTH);
  1276. for (let indexSignature = 0; indexSignature < SIGNATURE_LENGTH; indexSignature++) {
  1277. if (signature[indexSignature] != originalSignature[indexSignature]) {
  1278. throw new Error(ERR_INVALID_SIGNATURE);
  1279. }
  1280. }
  1281. }
  1282. controller.enqueue(decryptedChunkArray);
  1283. }
  1284. });
  1285. }
  1286. }
  1287. class AESEncryptionStream extends TransformStream {
  1288. constructor({ password, encryptionStrength }) {
  1289. // deno-lint-ignore prefer-const
  1290. let stream;
  1291. super({
  1292. start() {
  1293. Object$1.assign(this, {
  1294. ready: new Promise$1(resolve => this.resolveReady = resolve),
  1295. password,
  1296. strength: encryptionStrength - 1,
  1297. pending: new Uint8Array$1()
  1298. });
  1299. },
  1300. async transform(chunk, controller) {
  1301. const aesCrypto = this;
  1302. const {
  1303. password,
  1304. strength,
  1305. resolveReady,
  1306. ready
  1307. } = aesCrypto;
  1308. let preamble = new Uint8Array$1();
  1309. if (password) {
  1310. preamble = await createEncryptionKeys(aesCrypto, strength, password);
  1311. resolveReady();
  1312. } else {
  1313. await ready;
  1314. }
  1315. const output = new Uint8Array$1(preamble.length + chunk.length - (chunk.length % BLOCK_LENGTH));
  1316. output.set(preamble, 0);
  1317. controller.enqueue(append(aesCrypto, chunk, output, preamble.length, 0));
  1318. },
  1319. async flush(controller) {
  1320. const {
  1321. ctr,
  1322. hmac,
  1323. pending,
  1324. ready
  1325. } = this;
  1326. await ready;
  1327. let encryptedChunkArray = new Uint8Array$1();
  1328. if (pending.length) {
  1329. const encryptedChunk = ctr.update(toBits(codecBytes, pending));
  1330. hmac.update(encryptedChunk);
  1331. encryptedChunkArray = fromBits(codecBytes, encryptedChunk);
  1332. }
  1333. stream.signature = fromBits(codecBytes, hmac.digest()).slice(0, SIGNATURE_LENGTH);
  1334. controller.enqueue(concat(encryptedChunkArray, stream.signature));
  1335. }
  1336. });
  1337. stream = this;
  1338. }
  1339. }
  1340. function append(aesCrypto, input, output, paddingStart, paddingEnd, verifySignature) {
  1341. const {
  1342. ctr,
  1343. hmac,
  1344. pending
  1345. } = aesCrypto;
  1346. const inputLength = input.length - paddingEnd;
  1347. if (pending.length) {
  1348. input = concat(pending, input);
  1349. output = expand(output, inputLength - (inputLength % BLOCK_LENGTH));
  1350. }
  1351. let offset;
  1352. for (offset = 0; offset <= inputLength - BLOCK_LENGTH; offset += BLOCK_LENGTH) {
  1353. const inputChunk = toBits(codecBytes, subarray(input, offset, offset + BLOCK_LENGTH));
  1354. if (verifySignature) {
  1355. hmac.update(inputChunk);
  1356. }
  1357. const outputChunk = ctr.update(inputChunk);
  1358. if (!verifySignature) {
  1359. hmac.update(outputChunk);
  1360. }
  1361. output.set(fromBits(codecBytes, outputChunk), offset + paddingStart);
  1362. }
  1363. aesCrypto.pending = subarray(input, offset);
  1364. return output;
  1365. }
  1366. async function createDecryptionKeys(decrypt, strength, password, preamble) {
  1367. const passwordVerificationKey = await createKeys$1(decrypt, strength, password, subarray(preamble, 0, SALT_LENGTH[strength]));
  1368. const passwordVerification = subarray(preamble, SALT_LENGTH[strength]);
  1369. if (passwordVerificationKey[0] != passwordVerification[0] || passwordVerificationKey[1] != passwordVerification[1]) {
  1370. throw new Error(ERR_INVALID_PASSWORD);
  1371. }
  1372. }
  1373. async function createEncryptionKeys(encrypt, strength, password) {
  1374. const salt = getRandomValues(new Uint8Array$1(SALT_LENGTH[strength]));
  1375. const passwordVerification = await createKeys$1(encrypt, strength, password, salt);
  1376. return concat(salt, passwordVerification);
  1377. }
  1378. async function createKeys$1(aesCrypto, strength, password, salt) {
  1379. aesCrypto.password = null;
  1380. const encodedPassword = encodeText(password);
  1381. const baseKey = await importKey(RAW_FORMAT, encodedPassword, BASE_KEY_ALGORITHM, false, DERIVED_BITS_USAGE);
  1382. const derivedBits = await deriveBits(Object$1.assign({ salt }, DERIVED_BITS_ALGORITHM), baseKey, 8 * ((KEY_LENGTH[strength] * 2) + 2));
  1383. const compositeKey = new Uint8Array$1(derivedBits);
  1384. const key = toBits(codecBytes, subarray(compositeKey, 0, KEY_LENGTH[strength]));
  1385. const authentication = toBits(codecBytes, subarray(compositeKey, KEY_LENGTH[strength], KEY_LENGTH[strength] * 2));
  1386. const passwordVerification = subarray(compositeKey, KEY_LENGTH[strength] * 2);
  1387. Object$1.assign(aesCrypto, {
  1388. keys: {
  1389. key,
  1390. authentication,
  1391. passwordVerification
  1392. },
  1393. ctr: new CtrGladman(new Aes(key), Array$1.from(COUNTER_DEFAULT_VALUE)),
  1394. hmac: new HmacSha1(authentication)
  1395. });
  1396. return passwordVerification;
  1397. }
  1398. async function importKey(format, password, algorithm, extractable, keyUsages) {
  1399. if (IMPORT_KEY_SUPPORTED) {
  1400. try {
  1401. return await subtle.importKey(format, password, algorithm, extractable, keyUsages);
  1402. } catch (_error) {
  1403. IMPORT_KEY_SUPPORTED = false;
  1404. return misc.importKey(password);
  1405. }
  1406. } else {
  1407. return misc.importKey(password);
  1408. }
  1409. }
  1410. async function deriveBits(algorithm, baseKey, length) {
  1411. if (DERIVE_BITS_SUPPORTED) {
  1412. try {
  1413. return await subtle.deriveBits(algorithm, baseKey, length);
  1414. } catch (_error) {
  1415. DERIVE_BITS_SUPPORTED = false;
  1416. return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length);
  1417. }
  1418. } else {
  1419. return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length);
  1420. }
  1421. }
  1422. function concat(leftArray, rightArray) {
  1423. let array = leftArray;
  1424. if (leftArray.length + rightArray.length) {
  1425. array = new Uint8Array$1(leftArray.length + rightArray.length);
  1426. array.set(leftArray, 0);
  1427. array.set(rightArray, leftArray.length);
  1428. }
  1429. return array;
  1430. }
  1431. function expand(inputArray, length) {
  1432. if (length && length > inputArray.length) {
  1433. const array = inputArray;
  1434. inputArray = new Uint8Array$1(length);
  1435. inputArray.set(array, 0);
  1436. }
  1437. return inputArray;
  1438. }
  1439. function subarray(array, begin, end) {
  1440. return array.subarray(begin, end);
  1441. }
  1442. function fromBits(codecBytes, chunk) {
  1443. return codecBytes.fromBits(chunk);
  1444. }
  1445. function toBits(codecBytes, chunk) {
  1446. return codecBytes.toBits(chunk);
  1447. }
  1448. /*
  1449. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1450. Redistribution and use in source and binary forms, with or without
  1451. modification, are permitted provided that the following conditions are met:
  1452. 1. Redistributions of source code must retain the above copyright notice,
  1453. this list of conditions and the following disclaimer.
  1454. 2. Redistributions in binary form must reproduce the above copyright
  1455. notice, this list of conditions and the following disclaimer in
  1456. the documentation and/or other materials provided with the distribution.
  1457. 3. The names of the authors may not be used to endorse or promote products
  1458. derived from this software without specific prior written permission.
  1459. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1460. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1461. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1462. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1463. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1464. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1465. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1466. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1467. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1468. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1469. */
  1470. const HEADER_LENGTH = 12;
  1471. class ZipCryptoDecryptionStream extends TransformStream {
  1472. constructor({ password, passwordVerification, checkPasswordOnly }) {
  1473. super({
  1474. start() {
  1475. Object$1.assign(this, {
  1476. password,
  1477. passwordVerification
  1478. });
  1479. createKeys(this, password);
  1480. },
  1481. transform(chunk, controller) {
  1482. const zipCrypto = this;
  1483. if (zipCrypto.password) {
  1484. const decryptedHeader = decrypt(zipCrypto, chunk.subarray(0, HEADER_LENGTH));
  1485. zipCrypto.password = null;
  1486. if (decryptedHeader[HEADER_LENGTH - 1] != zipCrypto.passwordVerification) {
  1487. throw new Error(ERR_INVALID_PASSWORD);
  1488. }
  1489. chunk = chunk.subarray(HEADER_LENGTH);
  1490. }
  1491. if (checkPasswordOnly) {
  1492. controller.error(new Error(ERR_ABORT_CHECK_PASSWORD));
  1493. } else {
  1494. controller.enqueue(decrypt(zipCrypto, chunk));
  1495. }
  1496. }
  1497. });
  1498. }
  1499. }
  1500. class ZipCryptoEncryptionStream extends TransformStream {
  1501. constructor({ password, passwordVerification }) {
  1502. super({
  1503. start() {
  1504. Object$1.assign(this, {
  1505. password,
  1506. passwordVerification
  1507. });
  1508. createKeys(this, password);
  1509. },
  1510. transform(chunk, controller) {
  1511. const zipCrypto = this;
  1512. let output;
  1513. let offset;
  1514. if (zipCrypto.password) {
  1515. zipCrypto.password = null;
  1516. const header = getRandomValues(new Uint8Array$1(HEADER_LENGTH));
  1517. header[HEADER_LENGTH - 1] = zipCrypto.passwordVerification;
  1518. output = new Uint8Array$1(chunk.length + header.length);
  1519. output.set(encrypt(zipCrypto, header), 0);
  1520. offset = HEADER_LENGTH;
  1521. } else {
  1522. output = new Uint8Array$1(chunk.length);
  1523. offset = 0;
  1524. }
  1525. output.set(encrypt(zipCrypto, chunk), offset);
  1526. controller.enqueue(output);
  1527. }
  1528. });
  1529. }
  1530. }
  1531. function decrypt(target, input) {
  1532. const output = new Uint8Array$1(input.length);
  1533. for (let index = 0; index < input.length; index++) {
  1534. output[index] = getByte(target) ^ input[index];
  1535. updateKeys(target, output[index]);
  1536. }
  1537. return output;
  1538. }
  1539. function encrypt(target, input) {
  1540. const output = new Uint8Array$1(input.length);
  1541. for (let index = 0; index < input.length; index++) {
  1542. output[index] = getByte(target) ^ input[index];
  1543. updateKeys(target, input[index]);
  1544. }
  1545. return output;
  1546. }
  1547. function createKeys(target, password) {
  1548. const keys = [0x12345678, 0x23456789, 0x34567890];
  1549. Object$1.assign(target, {
  1550. keys,
  1551. crcKey0: new Crc32(keys[0]),
  1552. crcKey2: new Crc32(keys[2]),
  1553. });
  1554. for (let index = 0; index < password.length; index++) {
  1555. updateKeys(target, password.charCodeAt(index));
  1556. }
  1557. }
  1558. function updateKeys(target, byte) {
  1559. let [key0, key1, key2] = target.keys;
  1560. target.crcKey0.append([byte]);
  1561. key0 = ~target.crcKey0.get();
  1562. key1 = getInt32(Math$1.imul(getInt32(key1 + getInt8(key0)), 134775813) + 1);
  1563. target.crcKey2.append([key1 >>> 24]);
  1564. key2 = ~target.crcKey2.get();
  1565. target.keys = [key0, key1, key2];
  1566. }
  1567. function getByte(target) {
  1568. const temp = target.keys[2] | 2;
  1569. return getInt8(Math$1.imul(temp, (temp ^ 1)) >>> 8);
  1570. }
  1571. function getInt8(number) {
  1572. return number & 0xFF;
  1573. }
  1574. function getInt32(number) {
  1575. return number & 0xFFFFFFFF;
  1576. }
  1577. /*
  1578. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1579. Redistribution and use in source and binary forms, with or without
  1580. modification, are permitted provided that the following conditions are met:
  1581. 1. Redistributions of source code must retain the above copyright notice,
  1582. this list of conditions and the following disclaimer.
  1583. 2. Redistributions in binary form must reproduce the above copyright
  1584. notice, this list of conditions and the following disclaimer in
  1585. the documentation and/or other materials provided with the distribution.
  1586. 3. The names of the authors may not be used to endorse or promote products
  1587. derived from this software without specific prior written permission.
  1588. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1589. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1590. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1591. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1592. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1593. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1594. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1595. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1596. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1597. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1598. */
  1599. const COMPRESSION_FORMAT = "deflate-raw";
  1600. class DeflateStream extends TransformStream {
  1601. constructor(options, { chunkSize, CompressionStream, CompressionStreamNative }) {
  1602. super({});
  1603. const { compressed, encrypted, useCompressionStream, zipCrypto, signed, level } = options;
  1604. const stream = this;
  1605. let crc32Stream, encryptionStream;
  1606. let readable = filterEmptyChunks(super.readable);
  1607. if ((!encrypted || zipCrypto) && signed) {
  1608. crc32Stream = new Crc32Stream();
  1609. readable = pipeThrough(readable, crc32Stream);
  1610. }
  1611. if (compressed) {
  1612. readable = pipeThroughCommpressionStream(readable, useCompressionStream, { level, chunkSize }, CompressionStreamNative, CompressionStream);
  1613. }
  1614. if (encrypted) {
  1615. if (zipCrypto) {
  1616. readable = pipeThrough(readable, new ZipCryptoEncryptionStream(options));
  1617. } else {
  1618. encryptionStream = new AESEncryptionStream(options);
  1619. readable = pipeThrough(readable, encryptionStream);
  1620. }
  1621. }
  1622. setReadable(stream, readable, () => {
  1623. let signature;
  1624. if (encrypted && !zipCrypto) {
  1625. signature = encryptionStream.signature;
  1626. }
  1627. if ((!encrypted || zipCrypto) && signed) {
  1628. signature = new DataView(crc32Stream.value.buffer).getUint32(0);
  1629. }
  1630. stream.signature = signature;
  1631. });
  1632. }
  1633. }
  1634. class InflateStream extends TransformStream {
  1635. constructor(options, { chunkSize, DecompressionStream, DecompressionStreamNative }) {
  1636. super({});
  1637. const { zipCrypto, encrypted, signed, signature, compressed, useCompressionStream } = options;
  1638. let crc32Stream, decryptionStream;
  1639. let readable = filterEmptyChunks(super.readable);
  1640. if (encrypted) {
  1641. if (zipCrypto) {
  1642. readable = pipeThrough(readable, new ZipCryptoDecryptionStream(options));
  1643. } else {
  1644. decryptionStream = new AESDecryptionStream(options);
  1645. readable = pipeThrough(readable, decryptionStream);
  1646. }
  1647. }
  1648. if (compressed) {
  1649. readable = pipeThroughCommpressionStream(readable, useCompressionStream, { chunkSize }, DecompressionStreamNative, DecompressionStream);
  1650. }
  1651. if ((!encrypted || zipCrypto) && signed) {
  1652. crc32Stream = new Crc32Stream();
  1653. readable = pipeThrough(readable, crc32Stream);
  1654. }
  1655. setReadable(this, readable, () => {
  1656. if ((!encrypted || zipCrypto) && signed) {
  1657. const dataViewSignature = new DataView(crc32Stream.value.buffer);
  1658. if (signature != dataViewSignature.getUint32(0, false)) {
  1659. throw new Error(ERR_INVALID_SIGNATURE);
  1660. }
  1661. }
  1662. });
  1663. }
  1664. }
  1665. function filterEmptyChunks(readable) {
  1666. return pipeThrough(readable, new TransformStream({
  1667. transform(chunk, controller) {
  1668. if (chunk && chunk.length) {
  1669. controller.enqueue(chunk);
  1670. }
  1671. }
  1672. }));
  1673. }
  1674. function setReadable(stream, readable, flush) {
  1675. readable = pipeThrough(readable, new TransformStream({ flush }));
  1676. Object$1.defineProperty(stream, "readable", {
  1677. get() {
  1678. return readable;
  1679. }
  1680. });
  1681. }
  1682. function pipeThroughCommpressionStream(readable, useCompressionStream, options, CodecStreamNative, CodecStream) {
  1683. try {
  1684. const CompressionStream = useCompressionStream && CodecStreamNative ? CodecStreamNative : CodecStream;
  1685. readable = pipeThrough(readable, new CompressionStream(COMPRESSION_FORMAT, options));
  1686. } catch (error) {
  1687. if (useCompressionStream) {
  1688. readable = pipeThrough(readable, new CodecStream(COMPRESSION_FORMAT, options));
  1689. } else {
  1690. throw error;
  1691. }
  1692. }
  1693. return readable;
  1694. }
  1695. function pipeThrough(readable, transformStream) {
  1696. return readable.pipeThrough(transformStream);
  1697. }
  1698. /*
  1699. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1700. Redistribution and use in source and binary forms, with or without
  1701. modification, are permitted provided that the following conditions are met:
  1702. 1. Redistributions of source code must retain the above copyright notice,
  1703. this list of conditions and the following disclaimer.
  1704. 2. Redistributions in binary form must reproduce the above copyright
  1705. notice, this list of conditions and the following disclaimer in
  1706. the documentation and/or other materials provided with the distribution.
  1707. 3. The names of the authors may not be used to endorse or promote products
  1708. derived from this software without specific prior written permission.
  1709. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1710. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1711. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1712. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1713. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1714. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1715. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1716. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1717. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1718. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1719. */
  1720. const MESSAGE_EVENT_TYPE = "message";
  1721. const MESSAGE_START = "start";
  1722. const MESSAGE_PULL = "pull";
  1723. const MESSAGE_DATA = "data";
  1724. const MESSAGE_ACK_DATA = "ack";
  1725. const MESSAGE_CLOSE = "close";
  1726. const CODEC_DEFLATE = "deflate";
  1727. const CODEC_INFLATE = "inflate";
  1728. class CodecStream extends TransformStream {
  1729. constructor(options, config) {
  1730. super({});
  1731. const codec = this;
  1732. const { codecType } = options;
  1733. let Stream;
  1734. if (codecType.startsWith(CODEC_DEFLATE)) {
  1735. Stream = DeflateStream;
  1736. } else if (codecType.startsWith(CODEC_INFLATE)) {
  1737. Stream = InflateStream;
  1738. }
  1739. let size = 0;
  1740. const stream = new Stream(options, config);
  1741. const readable = super.readable;
  1742. const transformStream = new TransformStream({
  1743. transform(chunk, controller) {
  1744. if (chunk && chunk.length) {
  1745. size += chunk.length;
  1746. controller.enqueue(chunk);
  1747. }
  1748. },
  1749. flush() {
  1750. const { signature } = stream;
  1751. Object$1.assign(codec, {
  1752. signature,
  1753. size
  1754. });
  1755. }
  1756. });
  1757. Object$1.defineProperty(codec, "readable", {
  1758. get() {
  1759. return readable.pipeThrough(stream).pipeThrough(transformStream);
  1760. }
  1761. });
  1762. }
  1763. }
  1764. /*
  1765. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1766. Redistribution and use in source and binary forms, with or without
  1767. modification, are permitted provided that the following conditions are met:
  1768. 1. Redistributions of source code must retain the above copyright notice,
  1769. this list of conditions and the following disclaimer.
  1770. 2. Redistributions in binary form must reproduce the above copyright
  1771. notice, this list of conditions and the following disclaimer in
  1772. the documentation and/or other materials provided with the distribution.
  1773. 3. The names of the authors may not be used to endorse or promote products
  1774. derived from this software without specific prior written permission.
  1775. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1776. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1777. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1778. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1779. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1780. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1781. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1782. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1783. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1784. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1785. */
  1786. // deno-lint-ignore valid-typeof
  1787. const WEB_WORKERS_SUPPORTED = typeof Worker$1 != UNDEFINED_TYPE$1;
  1788. class CodecWorker {
  1789. constructor(workerData, { readable, writable }, { options, config, streamOptions, useWebWorkers, transferStreams, scripts }, onTaskFinished) {
  1790. const { signal } = streamOptions;
  1791. Object$1.assign(workerData, {
  1792. busy: true,
  1793. readable: readable.pipeThrough(new ProgressWatcherStream(readable, streamOptions, config), { signal }),
  1794. writable,
  1795. options: Object$1.assign({}, options),
  1796. scripts,
  1797. transferStreams,
  1798. terminate() {
  1799. const { worker, busy } = workerData;
  1800. if (worker && !busy) {
  1801. worker.terminate();
  1802. workerData.interface = null;
  1803. }
  1804. },
  1805. onTaskFinished() {
  1806. workerData.busy = false;
  1807. onTaskFinished(workerData);
  1808. }
  1809. });
  1810. return (useWebWorkers && WEB_WORKERS_SUPPORTED ? createWebWorkerInterface : createWorkerInterface)(workerData, config);
  1811. }
  1812. }
  1813. class ProgressWatcherStream extends TransformStream {
  1814. constructor(readableSource, { onstart, onprogress, size, onend }, { chunkSize }) {
  1815. let chunkOffset = 0;
  1816. super({
  1817. start() {
  1818. if (onstart) {
  1819. callHandler(onstart, size);
  1820. }
  1821. },
  1822. async transform(chunk, controller) {
  1823. chunkOffset += chunk.length;
  1824. if (onprogress) {
  1825. await callHandler(onprogress, chunkOffset, size);
  1826. }
  1827. controller.enqueue(chunk);
  1828. },
  1829. flush() {
  1830. readableSource.size = chunkOffset;
  1831. if (onend) {
  1832. callHandler(onend, chunkOffset);
  1833. }
  1834. }
  1835. }, { highWaterMark: 1, size: () => chunkSize });
  1836. }
  1837. }
  1838. async function callHandler(handler, ...parameters) {
  1839. try {
  1840. await handler(...parameters);
  1841. } catch (_error) {
  1842. // ignored
  1843. }
  1844. }
  1845. function createWorkerInterface(workerData, config) {
  1846. return {
  1847. run: () => runWorker$1(workerData, config)
  1848. };
  1849. }
  1850. function createWebWorkerInterface(workerData, { baseURL, chunkSize }) {
  1851. if (!workerData.interface) {
  1852. Object$1.assign(workerData, {
  1853. worker: getWebWorker(workerData.scripts[0], baseURL, workerData),
  1854. interface: {
  1855. run: () => runWebWorker(workerData, { chunkSize })
  1856. }
  1857. });
  1858. }
  1859. return workerData.interface;
  1860. }
  1861. async function runWorker$1({ options, readable, writable, onTaskFinished }, config) {
  1862. const codecStream = new CodecStream(options, config);
  1863. try {
  1864. await readable.pipeThrough(codecStream).pipeTo(writable, { preventClose: true, preventAbort: true });
  1865. const {
  1866. signature,
  1867. size
  1868. } = codecStream;
  1869. return {
  1870. signature,
  1871. size
  1872. };
  1873. } finally {
  1874. onTaskFinished();
  1875. }
  1876. }
  1877. async function runWebWorker(workerData, config) {
  1878. let resolveResult, rejectResult;
  1879. const result = new Promise$1((resolve, reject) => {
  1880. resolveResult = resolve;
  1881. rejectResult = reject;
  1882. });
  1883. Object$1.assign(workerData, {
  1884. reader: null,
  1885. writer: null,
  1886. resolveResult,
  1887. rejectResult,
  1888. result
  1889. });
  1890. const { readable, options, scripts } = workerData;
  1891. const { writable, closed } = watchClosedStream(workerData.writable);
  1892. const streamsTransferred = sendMessage({
  1893. type: MESSAGE_START,
  1894. scripts: scripts.slice(1),
  1895. options,
  1896. config,
  1897. readable,
  1898. writable
  1899. }, workerData);
  1900. if (!streamsTransferred) {
  1901. Object$1.assign(workerData, {
  1902. reader: readable.getReader(),
  1903. writer: writable.getWriter()
  1904. });
  1905. }
  1906. const resultValue = await result;
  1907. try {
  1908. await writable.getWriter().close();
  1909. } catch (_error) {
  1910. // ignored
  1911. }
  1912. await closed;
  1913. return resultValue;
  1914. }
  1915. function watchClosedStream(writableSource) {
  1916. const writer = writableSource.getWriter();
  1917. let resolveStreamClosed;
  1918. const closed = new Promise$1(resolve => resolveStreamClosed = resolve);
  1919. const writable = new WritableStream({
  1920. async write(chunk) {
  1921. await writer.ready;
  1922. await writer.write(chunk);
  1923. },
  1924. close() {
  1925. writer.releaseLock();
  1926. resolveStreamClosed();
  1927. },
  1928. abort(reason) {
  1929. return writer.abort(reason);
  1930. }
  1931. });
  1932. return { writable, closed };
  1933. }
  1934. let classicWorkersSupported = true;
  1935. let transferStreamsSupported = true;
  1936. function getWebWorker(url, baseURL, workerData) {
  1937. const workerOptions = { type: "module" };
  1938. let scriptUrl, worker;
  1939. // deno-lint-ignore valid-typeof
  1940. if (typeof url == FUNCTION_TYPE$1) {
  1941. url = url();
  1942. }
  1943. try {
  1944. scriptUrl = new URL$1(url, baseURL);
  1945. } catch (_error) {
  1946. scriptUrl = url;
  1947. }
  1948. if (classicWorkersSupported) {
  1949. try {
  1950. worker = new Worker$1(scriptUrl);
  1951. } catch (_error) {
  1952. classicWorkersSupported = false;
  1953. worker = new Worker$1(scriptUrl, workerOptions);
  1954. }
  1955. } else {
  1956. worker = new Worker$1(scriptUrl, workerOptions);
  1957. }
  1958. worker.addEventListener(MESSAGE_EVENT_TYPE, event => onMessage(event, workerData));
  1959. return worker;
  1960. }
  1961. function sendMessage(message, { worker, writer, onTaskFinished, transferStreams }) {
  1962. try {
  1963. let { value, readable, writable } = message;
  1964. const transferables = [];
  1965. if (value) {
  1966. message.value = value.buffer;
  1967. transferables.push(message.value);
  1968. }
  1969. if (transferStreams && transferStreamsSupported) {
  1970. if (readable) {
  1971. transferables.push(readable);
  1972. }
  1973. if (writable) {
  1974. transferables.push(writable);
  1975. }
  1976. } else {
  1977. message.readable = message.writable = null;
  1978. }
  1979. if (transferables.length) {
  1980. try {
  1981. worker.postMessage(message, transferables);
  1982. return true;
  1983. } catch (_error) {
  1984. transferStreamsSupported = false;
  1985. message.readable = message.writable = null;
  1986. worker.postMessage(message);
  1987. }
  1988. } else {
  1989. worker.postMessage(message);
  1990. }
  1991. } catch (error) {
  1992. if (writer) {
  1993. writer.releaseLock();
  1994. }
  1995. onTaskFinished();
  1996. throw error;
  1997. }
  1998. }
  1999. async function onMessage({ data }, workerData) {
  2000. const { type, value, messageId, result, error } = data;
  2001. const { reader, writer, resolveResult, rejectResult, onTaskFinished } = workerData;
  2002. try {
  2003. if (error) {
  2004. const { message, stack, code, name } = error;
  2005. const responseError = new Error(message);
  2006. Object$1.assign(responseError, { stack, code, name });
  2007. close(responseError);
  2008. } else {
  2009. if (type == MESSAGE_PULL) {
  2010. const { value, done } = await reader.read();
  2011. sendMessage({ type: MESSAGE_DATA, value, done, messageId }, workerData);
  2012. }
  2013. if (type == MESSAGE_DATA) {
  2014. await writer.ready;
  2015. await writer.write(new Uint8Array$1(value));
  2016. sendMessage({ type: MESSAGE_ACK_DATA, messageId }, workerData);
  2017. }
  2018. if (type == MESSAGE_CLOSE) {
  2019. close(null, result);
  2020. }
  2021. }
  2022. } catch (error) {
  2023. close(error);
  2024. }
  2025. function close(error, result) {
  2026. if (error) {
  2027. rejectResult(error);
  2028. } else {
  2029. resolveResult(result);
  2030. }
  2031. if (writer) {
  2032. writer.releaseLock();
  2033. }
  2034. onTaskFinished();
  2035. }
  2036. }
  2037. /*
  2038. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2039. Redistribution and use in source and binary forms, with or without
  2040. modification, are permitted provided that the following conditions are met:
  2041. 1. Redistributions of source code must retain the above copyright notice,
  2042. this list of conditions and the following disclaimer.
  2043. 2. Redistributions in binary form must reproduce the above copyright
  2044. notice, this list of conditions and the following disclaimer in
  2045. the documentation and/or other materials provided with the distribution.
  2046. 3. The names of the authors may not be used to endorse or promote products
  2047. derived from this software without specific prior written permission.
  2048. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2049. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2050. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2051. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2052. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2053. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2054. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2055. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2056. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2057. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2058. */
  2059. let pool = [];
  2060. const pendingRequests = [];
  2061. let indexWorker = 0;
  2062. async function runWorker(stream, workerOptions) {
  2063. const { options, config } = workerOptions;
  2064. const { transferStreams, useWebWorkers, useCompressionStream, codecType, compressed, signed, encrypted } = options;
  2065. const { workerScripts, maxWorkers, terminateWorkerTimeout } = config;
  2066. workerOptions.transferStreams = transferStreams || transferStreams === UNDEFINED_VALUE;
  2067. const streamCopy = !compressed && !signed && !encrypted && !workerOptions.transferStreams;
  2068. workerOptions.useWebWorkers = !streamCopy && (useWebWorkers || (useWebWorkers === UNDEFINED_VALUE && config.useWebWorkers));
  2069. workerOptions.scripts = workerOptions.useWebWorkers && workerScripts ? workerScripts[codecType] : [];
  2070. options.useCompressionStream = useCompressionStream || (useCompressionStream === UNDEFINED_VALUE && config.useCompressionStream);
  2071. let worker;
  2072. const workerData = pool.find(workerData => !workerData.busy);
  2073. if (workerData) {
  2074. clearTerminateTimeout(workerData);
  2075. worker = new CodecWorker(workerData, stream, workerOptions, onTaskFinished);
  2076. } else if (pool.length < maxWorkers) {
  2077. const workerData = { indexWorker };
  2078. indexWorker++;
  2079. pool.push(workerData);
  2080. worker = new CodecWorker(workerData, stream, workerOptions, onTaskFinished);
  2081. } else {
  2082. worker = await new Promise$1(resolve => pendingRequests.push({ resolve, stream, workerOptions }));
  2083. }
  2084. return worker.run();
  2085. function onTaskFinished(workerData) {
  2086. if (pendingRequests.length) {
  2087. const [{ resolve, stream, workerOptions }] = pendingRequests.splice(0, 1);
  2088. resolve(new CodecWorker(workerData, stream, workerOptions, onTaskFinished));
  2089. } else if (workerData.worker) {
  2090. clearTerminateTimeout(workerData);
  2091. if (Number$1.isFinite(terminateWorkerTimeout) && terminateWorkerTimeout >= 0) {
  2092. workerData.terminateTimeout = setTimeout(() => {
  2093. pool = pool.filter(data => data != workerData);
  2094. workerData.terminate();
  2095. }, terminateWorkerTimeout);
  2096. }
  2097. } else {
  2098. pool = pool.filter(data => data != workerData);
  2099. }
  2100. }
  2101. }
  2102. function clearTerminateTimeout(workerData) {
  2103. const { terminateTimeout } = workerData;
  2104. if (terminateTimeout) {
  2105. clearTimeout(terminateTimeout);
  2106. workerData.terminateTimeout = null;
  2107. }
  2108. }
  2109. function terminateWorkers() {
  2110. pool.forEach(workerData => {
  2111. clearTerminateTimeout(workerData);
  2112. workerData.terminate();
  2113. });
  2114. }
  2115. /*
  2116. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2117. Redistribution and use in source and binary forms, with or without
  2118. modification, are permitted provided that the following conditions are met:
  2119. 1. Redistributions of source code must retain the above copyright notice,
  2120. this list of conditions and the following disclaimer.
  2121. 2. Redistributions in binary form must reproduce the above copyright
  2122. notice, this list of conditions and the following disclaimer in
  2123. the documentation and/or other materials provided with the distribution.
  2124. 3. The names of the authors may not be used to endorse or promote products
  2125. derived from this software without specific prior written permission.
  2126. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2127. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2128. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2129. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2130. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2131. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2132. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2133. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2134. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2135. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2136. */
  2137. const ERR_HTTP_STATUS = "HTTP error ";
  2138. const ERR_HTTP_RANGE = "HTTP Range not supported";
  2139. const ERR_ITERATOR_COMPLETED_TOO_SOON = "Writer iterator completed too soon";
  2140. const CONTENT_TYPE_TEXT_PLAIN = "text/plain";
  2141. const HTTP_HEADER_CONTENT_LENGTH = "Content-Length";
  2142. const HTTP_HEADER_CONTENT_RANGE = "Content-Range";
  2143. const HTTP_HEADER_ACCEPT_RANGES = "Accept-Ranges";
  2144. const HTTP_HEADER_RANGE = "Range";
  2145. const HTTP_HEADER_CONTENT_TYPE = "Content-Type";
  2146. const HTTP_METHOD_HEAD = "HEAD";
  2147. const HTTP_METHOD_GET = "GET";
  2148. const HTTP_RANGE_UNIT = "bytes";
  2149. const DEFAULT_CHUNK_SIZE = 64 * 1024;
  2150. const PROPERTY_NAME_WRITABLE = "writable";
  2151. class Stream {
  2152. constructor() {
  2153. this.size = 0;
  2154. }
  2155. init() {
  2156. this.initialized = true;
  2157. }
  2158. }
  2159. class Reader extends Stream {
  2160. get readable() {
  2161. const reader = this;
  2162. const { chunkSize = DEFAULT_CHUNK_SIZE } = reader;
  2163. const readable = new ReadableStream({
  2164. start() {
  2165. this.chunkOffset = 0;
  2166. },
  2167. async pull(controller) {
  2168. const { offset = 0, size, diskNumberStart } = readable;
  2169. const { chunkOffset } = this;
  2170. controller.enqueue(await readUint8Array(reader, offset + chunkOffset, Math$1.min(chunkSize, size - chunkOffset), diskNumberStart));
  2171. if (chunkOffset + chunkSize > size) {
  2172. controller.close();
  2173. } else {
  2174. this.chunkOffset += chunkSize;
  2175. }
  2176. }
  2177. });
  2178. return readable;
  2179. }
  2180. }
  2181. class Writer extends Stream {
  2182. constructor() {
  2183. super();
  2184. const writer = this;
  2185. const writable = new WritableStream({
  2186. write(chunk) {
  2187. return writer.writeUint8Array(chunk);
  2188. }
  2189. });
  2190. Object$1.defineProperty(writer, PROPERTY_NAME_WRITABLE, {
  2191. get() {
  2192. return writable;
  2193. }
  2194. });
  2195. }
  2196. writeUint8Array() {
  2197. // abstract
  2198. }
  2199. }
  2200. class Data64URIReader extends Reader {
  2201. constructor(dataURI) {
  2202. super();
  2203. let dataEnd = dataURI.length;
  2204. while (dataURI.charAt(dataEnd - 1) == "=") {
  2205. dataEnd--;
  2206. }
  2207. const dataStart = dataURI.indexOf(",") + 1;
  2208. Object$1.assign(this, {
  2209. dataURI,
  2210. dataStart,
  2211. size: Math$1.floor((dataEnd - dataStart) * 0.75)
  2212. });
  2213. }
  2214. readUint8Array(offset, length) {
  2215. const {
  2216. dataStart,
  2217. dataURI
  2218. } = this;
  2219. const dataArray = new Uint8Array$1(length);
  2220. const start = Math$1.floor(offset / 3) * 4;
  2221. const bytes = atob(dataURI.substring(start + dataStart, Math$1.ceil((offset + length) / 3) * 4 + dataStart));
  2222. const delta = offset - Math$1.floor(start / 4) * 3;
  2223. for (let indexByte = delta; indexByte < delta + length; indexByte++) {
  2224. dataArray[indexByte - delta] = bytes.charCodeAt(indexByte);
  2225. }
  2226. return dataArray;
  2227. }
  2228. }
  2229. class Data64URIWriter extends Writer {
  2230. constructor(contentType) {
  2231. super();
  2232. Object$1.assign(this, {
  2233. data: "data:" + (contentType || "") + ";base64,",
  2234. pending: []
  2235. });
  2236. }
  2237. writeUint8Array(array) {
  2238. const writer = this;
  2239. let indexArray = 0;
  2240. let dataString = writer.pending;
  2241. const delta = writer.pending.length;
  2242. writer.pending = "";
  2243. for (indexArray = 0; indexArray < (Math$1.floor((delta + array.length) / 3) * 3) - delta; indexArray++) {
  2244. dataString += String.fromCharCode(array[indexArray]);
  2245. }
  2246. for (; indexArray < array.length; indexArray++) {
  2247. writer.pending += String.fromCharCode(array[indexArray]);
  2248. }
  2249. if (dataString.length > 2) {
  2250. writer.data += btoa(dataString);
  2251. } else {
  2252. writer.pending = dataString;
  2253. }
  2254. }
  2255. getData() {
  2256. return this.data + btoa(this.pending);
  2257. }
  2258. }
  2259. class BlobReader extends Reader {
  2260. constructor(blob) {
  2261. super();
  2262. Object$1.assign(this, {
  2263. blob,
  2264. size: blob.size
  2265. });
  2266. }
  2267. async readUint8Array(offset, length) {
  2268. const reader = this;
  2269. const offsetEnd = offset + length;
  2270. const blob = offset || offsetEnd < reader.size ? reader.blob.slice(offset, offsetEnd) : reader.blob;
  2271. let arrayBuffer = await blob.arrayBuffer();
  2272. if (arrayBuffer.byteLength > length) {
  2273. arrayBuffer = arrayBuffer.slice(offset, offsetEnd);
  2274. }
  2275. return new Uint8Array$1(arrayBuffer);
  2276. }
  2277. }
  2278. class BlobWriter extends Stream {
  2279. constructor(contentType) {
  2280. super();
  2281. const writer = this;
  2282. const transformStream = new TransformStream();
  2283. const headers = [];
  2284. if (contentType) {
  2285. headers.push([HTTP_HEADER_CONTENT_TYPE, contentType]);
  2286. }
  2287. Object$1.defineProperty(writer, PROPERTY_NAME_WRITABLE, {
  2288. get() {
  2289. return transformStream.writable;
  2290. }
  2291. });
  2292. writer.blob = new Response(transformStream.readable, { headers }).blob();
  2293. }
  2294. getData() {
  2295. return this.blob;
  2296. }
  2297. }
  2298. class TextReader extends BlobReader {
  2299. constructor(text) {
  2300. super(new Blob$1([text], { type: CONTENT_TYPE_TEXT_PLAIN }));
  2301. }
  2302. }
  2303. class TextWriter extends BlobWriter {
  2304. constructor(encoding) {
  2305. super(encoding);
  2306. Object$1.assign(this, {
  2307. encoding,
  2308. utf8: !encoding || encoding.toLowerCase() == "utf-8"
  2309. });
  2310. }
  2311. async getData() {
  2312. const {
  2313. encoding,
  2314. utf8
  2315. } = this;
  2316. const blob = await super.getData();
  2317. if (blob.text && utf8) {
  2318. return blob.text();
  2319. } else {
  2320. const reader = new FileReader();
  2321. return new Promise$1((resolve, reject) => {
  2322. Object$1.assign(reader, {
  2323. onload: ({ target }) => resolve(target.result),
  2324. onerror: () => reject(reader.error)
  2325. });
  2326. reader.readAsText(blob, encoding);
  2327. });
  2328. }
  2329. }
  2330. }
  2331. class FetchReader extends Reader {
  2332. constructor(url, options) {
  2333. super();
  2334. createHtpReader(this, url, options);
  2335. }
  2336. async init() {
  2337. await initHttpReader(this, sendFetchRequest, getFetchRequestData);
  2338. super.init();
  2339. }
  2340. readUint8Array(index, length) {
  2341. return readUint8ArrayHttpReader(this, index, length, sendFetchRequest, getFetchRequestData);
  2342. }
  2343. }
  2344. class XHRReader extends Reader {
  2345. constructor(url, options) {
  2346. super();
  2347. createHtpReader(this, url, options);
  2348. }
  2349. async init() {
  2350. await initHttpReader(this, sendXMLHttpRequest, getXMLHttpRequestData);
  2351. super.init();
  2352. }
  2353. readUint8Array(index, length) {
  2354. return readUint8ArrayHttpReader(this, index, length, sendXMLHttpRequest, getXMLHttpRequestData);
  2355. }
  2356. }
  2357. function createHtpReader(httpReader, url, options) {
  2358. const {
  2359. preventHeadRequest,
  2360. useRangeHeader,
  2361. forceRangeRequests
  2362. } = options;
  2363. options = Object$1.assign({}, options);
  2364. delete options.preventHeadRequest;
  2365. delete options.useRangeHeader;
  2366. delete options.forceRangeRequests;
  2367. delete options.useXHR;
  2368. Object$1.assign(httpReader, {
  2369. url,
  2370. options,
  2371. preventHeadRequest,
  2372. useRangeHeader,
  2373. forceRangeRequests
  2374. });
  2375. }
  2376. async function initHttpReader(httpReader, sendRequest, getRequestData) {
  2377. const {
  2378. url,
  2379. useRangeHeader,
  2380. forceRangeRequests
  2381. } = httpReader;
  2382. if (isHttpFamily(url) && (useRangeHeader || forceRangeRequests)) {
  2383. const { headers } = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader));
  2384. if (!forceRangeRequests && headers.get(HTTP_HEADER_ACCEPT_RANGES) != HTTP_RANGE_UNIT) {
  2385. throw new Error(ERR_HTTP_RANGE);
  2386. } else {
  2387. let contentSize;
  2388. const contentRangeHeader = headers.get(HTTP_HEADER_CONTENT_RANGE);
  2389. if (contentRangeHeader) {
  2390. const splitHeader = contentRangeHeader.trim().split(/\s*\/\s*/);
  2391. if (splitHeader.length) {
  2392. const headerValue = splitHeader[1];
  2393. if (headerValue && headerValue != "*") {
  2394. contentSize = Number$1(headerValue);
  2395. }
  2396. }
  2397. }
  2398. if (contentSize === UNDEFINED_VALUE) {
  2399. await getContentLength(httpReader, sendRequest, getRequestData);
  2400. } else {
  2401. httpReader.size = contentSize;
  2402. }
  2403. }
  2404. } else {
  2405. await getContentLength(httpReader, sendRequest, getRequestData);
  2406. }
  2407. }
  2408. async function readUint8ArrayHttpReader(httpReader, index, length, sendRequest, getRequestData) {
  2409. const {
  2410. useRangeHeader,
  2411. forceRangeRequests,
  2412. options
  2413. } = httpReader;
  2414. if (useRangeHeader || forceRangeRequests) {
  2415. const response = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader, index, length));
  2416. if (response.status != 206) {
  2417. throw new Error(ERR_HTTP_RANGE);
  2418. }
  2419. return new Uint8Array$1(await response.arrayBuffer());
  2420. } else {
  2421. const { data } = httpReader;
  2422. if (!data) {
  2423. await getRequestData(httpReader, options);
  2424. }
  2425. return new Uint8Array$1(httpReader.data.subarray(index, index + length));
  2426. }
  2427. }
  2428. function getRangeHeaders(httpReader, index = 0, length = 1) {
  2429. return Object$1.assign({}, getHeaders(httpReader), { [HTTP_HEADER_RANGE]: HTTP_RANGE_UNIT + "=" + index + "-" + (index + length - 1) });
  2430. }
  2431. function getHeaders({ options }) {
  2432. const { headers } = options;
  2433. if (headers) {
  2434. if (Symbol.iterator in headers) {
  2435. return Object$1.fromEntries(headers);
  2436. } else {
  2437. return headers;
  2438. }
  2439. }
  2440. }
  2441. async function getFetchRequestData(httpReader) {
  2442. await getRequestData(httpReader, sendFetchRequest);
  2443. }
  2444. async function getXMLHttpRequestData(httpReader) {
  2445. await getRequestData(httpReader, sendXMLHttpRequest);
  2446. }
  2447. async function getRequestData(httpReader, sendRequest) {
  2448. const response = await sendRequest(HTTP_METHOD_GET, httpReader, getHeaders(httpReader));
  2449. httpReader.data = new Uint8Array$1(await response.arrayBuffer());
  2450. if (!httpReader.size) {
  2451. httpReader.size = httpReader.data.length;
  2452. }
  2453. }
  2454. async function getContentLength(httpReader, sendRequest, getRequestData) {
  2455. if (httpReader.preventHeadRequest) {
  2456. await getRequestData(httpReader, httpReader.options);
  2457. } else {
  2458. const response = await sendRequest(HTTP_METHOD_HEAD, httpReader, getHeaders(httpReader));
  2459. const contentLength = response.headers.get(HTTP_HEADER_CONTENT_LENGTH);
  2460. if (contentLength) {
  2461. httpReader.size = Number$1(contentLength);
  2462. } else {
  2463. await getRequestData(httpReader, httpReader.options);
  2464. }
  2465. }
  2466. }
  2467. async function sendFetchRequest(method, { options, url }, headers) {
  2468. const response = await fetch(url, Object$1.assign({}, options, { method, headers }));
  2469. if (response.status < 400) {
  2470. return response;
  2471. } else {
  2472. throw response.status == 416 ? new Error(ERR_HTTP_RANGE) : new Error(ERR_HTTP_STATUS + (response.statusText || response.status));
  2473. }
  2474. }
  2475. function sendXMLHttpRequest(method, { url }, headers) {
  2476. return new Promise$1((resolve, reject) => {
  2477. const request = new XMLHttpRequest();
  2478. request.addEventListener("load", () => {
  2479. if (request.status < 400) {
  2480. const headers = [];
  2481. request.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(header => {
  2482. const splitHeader = header.trim().split(/\s*:\s*/);
  2483. splitHeader[0] = splitHeader[0].trim().replace(/^[a-z]|-[a-z]/g, value => value.toUpperCase());
  2484. headers.push(splitHeader);
  2485. });
  2486. resolve({
  2487. status: request.status,
  2488. arrayBuffer: () => request.response,
  2489. headers: new Map(headers)
  2490. });
  2491. } else {
  2492. reject(request.status == 416 ? new Error(ERR_HTTP_RANGE) : new Error(ERR_HTTP_STATUS + (request.statusText || request.status)));
  2493. }
  2494. }, false);
  2495. request.addEventListener("error", event => reject(event.detail ? event.detail.error : new Error("Network error")), false);
  2496. request.open(method, url);
  2497. if (headers) {
  2498. for (const entry of Object$1.entries(headers)) {
  2499. request.setRequestHeader(entry[0], entry[1]);
  2500. }
  2501. }
  2502. request.responseType = "arraybuffer";
  2503. request.send();
  2504. });
  2505. }
  2506. class HttpReader extends Reader {
  2507. constructor(url, options = {}) {
  2508. super();
  2509. Object$1.assign(this, {
  2510. url,
  2511. reader: options.useXHR ? new XHRReader(url, options) : new FetchReader(url, options)
  2512. });
  2513. }
  2514. set size(value) {
  2515. // ignored
  2516. }
  2517. get size() {
  2518. return this.reader.size;
  2519. }
  2520. async init() {
  2521. await this.reader.init();
  2522. super.init();
  2523. }
  2524. readUint8Array(index, length) {
  2525. return this.reader.readUint8Array(index, length);
  2526. }
  2527. }
  2528. class HttpRangeReader extends HttpReader {
  2529. constructor(url, options = {}) {
  2530. options.useRangeHeader = true;
  2531. super(url, options);
  2532. }
  2533. }
  2534. class Uint8ArrayReader extends Reader {
  2535. constructor(array) {
  2536. super();
  2537. Object$1.assign(this, {
  2538. array,
  2539. size: array.length
  2540. });
  2541. }
  2542. readUint8Array(index, length) {
  2543. return this.array.slice(index, index + length);
  2544. }
  2545. }
  2546. class Uint8ArrayWriter extends Writer {
  2547. init(initSize = 0) {
  2548. Object$1.assign(this, {
  2549. offset: 0,
  2550. array: new Uint8Array$1(initSize)
  2551. });
  2552. super.init();
  2553. }
  2554. writeUint8Array(array) {
  2555. const writer = this;
  2556. if (writer.offset + array.length > writer.array.length) {
  2557. const previousArray = writer.array;
  2558. writer.array = new Uint8Array$1(previousArray.length + array.length);
  2559. writer.array.set(previousArray);
  2560. }
  2561. writer.array.set(array, writer.offset);
  2562. writer.offset += array.length;
  2563. }
  2564. getData() {
  2565. return this.array;
  2566. }
  2567. }
  2568. class SplitDataReader extends Reader {
  2569. constructor(readers) {
  2570. super();
  2571. this.readers = readers;
  2572. }
  2573. async init() {
  2574. const reader = this;
  2575. const { readers } = reader;
  2576. reader.lastDiskNumber = 0;
  2577. reader.lastDiskOffset = 0;
  2578. await Promise$1.all(readers.map(async (diskReader, indexDiskReader) => {
  2579. await diskReader.init();
  2580. if (indexDiskReader != readers.length - 1) {
  2581. reader.lastDiskOffset += diskReader.size;
  2582. }
  2583. reader.size += diskReader.size;
  2584. }));
  2585. super.init();
  2586. }
  2587. async readUint8Array(offset, length, diskNumber = 0) {
  2588. const reader = this;
  2589. const { readers } = this;
  2590. let result;
  2591. let currentDiskNumber = diskNumber;
  2592. if (currentDiskNumber == -1) {
  2593. currentDiskNumber = readers.length - 1;
  2594. }
  2595. let currentReaderOffset = offset;
  2596. while (currentReaderOffset >= readers[currentDiskNumber].size) {
  2597. currentReaderOffset -= readers[currentDiskNumber].size;
  2598. currentDiskNumber++;
  2599. }
  2600. const currentReader = readers[currentDiskNumber];
  2601. const currentReaderSize = currentReader.size;
  2602. if (currentReaderOffset + length <= currentReaderSize) {
  2603. result = await readUint8Array(currentReader, currentReaderOffset, length);
  2604. } else {
  2605. const chunkLength = currentReaderSize - currentReaderOffset;
  2606. result = new Uint8Array$1(length);
  2607. result.set(await readUint8Array(currentReader, currentReaderOffset, chunkLength));
  2608. result.set(await reader.readUint8Array(offset + chunkLength, length - chunkLength, diskNumber), chunkLength);
  2609. }
  2610. reader.lastDiskNumber = Math$1.max(currentDiskNumber, reader.lastDiskNumber);
  2611. return result;
  2612. }
  2613. }
  2614. class SplitDataWriter extends Stream {
  2615. constructor(writerGenerator, maxSize = 4294967295) {
  2616. super();
  2617. const zipWriter = this;
  2618. Object$1.assign(zipWriter, {
  2619. diskNumber: 0,
  2620. diskOffset: 0,
  2621. size: 0,
  2622. maxSize,
  2623. availableSize: maxSize
  2624. });
  2625. let diskSourceWriter, diskWritable, diskWriter;
  2626. const writable = new WritableStream({
  2627. async write(chunk) {
  2628. const { availableSize } = zipWriter;
  2629. if (!diskWriter) {
  2630. const { value, done } = await writerGenerator.next();
  2631. if (done && !value) {
  2632. throw new Error(ERR_ITERATOR_COMPLETED_TOO_SOON);
  2633. } else {
  2634. diskSourceWriter = value;
  2635. diskSourceWriter.size = 0;
  2636. if (diskSourceWriter.maxSize) {
  2637. zipWriter.maxSize = diskSourceWriter.maxSize;
  2638. }
  2639. zipWriter.availableSize = zipWriter.maxSize;
  2640. await initStream(diskSourceWriter);
  2641. diskWritable = value.writable;
  2642. diskWriter = diskWritable.getWriter();
  2643. }
  2644. await this.write(chunk);
  2645. } else if (chunk.length >= availableSize) {
  2646. await writeChunk(chunk.slice(0, availableSize));
  2647. await closeDisk();
  2648. zipWriter.diskOffset += diskSourceWriter.size;
  2649. zipWriter.diskNumber++;
  2650. diskWriter = null;
  2651. await this.write(chunk.slice(availableSize));
  2652. } else {
  2653. await writeChunk(chunk);
  2654. }
  2655. },
  2656. async close() {
  2657. await diskWriter.ready;
  2658. await closeDisk();
  2659. }
  2660. });
  2661. Object$1.defineProperty(zipWriter, PROPERTY_NAME_WRITABLE, {
  2662. get() {
  2663. return writable;
  2664. }
  2665. });
  2666. async function writeChunk(chunk) {
  2667. const chunkLength = chunk.length;
  2668. if (chunkLength) {
  2669. await diskWriter.ready;
  2670. await diskWriter.write(chunk);
  2671. diskSourceWriter.size += chunkLength;
  2672. zipWriter.size += chunkLength;
  2673. zipWriter.availableSize -= chunkLength;
  2674. }
  2675. }
  2676. async function closeDisk() {
  2677. diskWritable.size = diskSourceWriter.size;
  2678. await diskWriter.close();
  2679. }
  2680. }
  2681. }
  2682. function isHttpFamily(url) {
  2683. const { baseURL } = getConfiguration();
  2684. const { protocol } = new URL$1(url, baseURL);
  2685. return protocol == "http:" || protocol == "https:";
  2686. }
  2687. async function initStream(stream, initSize) {
  2688. if (stream.init && !stream.initialized) {
  2689. await stream.init(initSize);
  2690. }
  2691. }
  2692. function initReader(reader) {
  2693. if (Array$1.isArray(reader)) {
  2694. reader = new SplitDataReader(reader);
  2695. }
  2696. if (reader instanceof ReadableStream) {
  2697. reader = {
  2698. readable: reader
  2699. };
  2700. }
  2701. return reader;
  2702. }
  2703. function initWriter(writer) {
  2704. if (writer.writable === UNDEFINED_VALUE && typeof writer.next == FUNCTION_TYPE$1) {
  2705. writer = new SplitDataWriter(writer);
  2706. }
  2707. if (writer instanceof WritableStream) {
  2708. writer = {
  2709. writable: writer
  2710. };
  2711. }
  2712. const { writable } = writer;
  2713. if (writable.size === UNDEFINED_VALUE) {
  2714. writable.size = 0;
  2715. }
  2716. const splitZipFile = writer instanceof SplitDataWriter;
  2717. if (!splitZipFile) {
  2718. Object$1.assign(writer, {
  2719. diskNumber: 0,
  2720. diskOffset: 0,
  2721. availableSize: Infinity,
  2722. maxSize: Infinity
  2723. });
  2724. }
  2725. return writer;
  2726. }
  2727. function readUint8Array(reader, offset, size, diskNumber) {
  2728. return reader.readUint8Array(offset, size, diskNumber);
  2729. }
  2730. const SplitZipReader = SplitDataReader;
  2731. const SplitZipWriter = SplitDataWriter;
  2732. /*
  2733. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2734. Redistribution and use in source and binary forms, with or without
  2735. modification, are permitted provided that the following conditions are met:
  2736. 1. Redistributions of source code must retain the above copyright notice,
  2737. this list of conditions and the following disclaimer.
  2738. 2. Redistributions in binary form must reproduce the above copyright
  2739. notice, this list of conditions and the following disclaimer in
  2740. the documentation and/or other materials provided with the distribution.
  2741. 3. The names of the authors may not be used to endorse or promote products
  2742. derived from this software without specific prior written permission.
  2743. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2744. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2745. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2746. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2747. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2748. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2749. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2750. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2751. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2752. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2753. */
  2754. /* global TextDecoder */
  2755. const CP437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ".split("");
  2756. const VALID_CP437 = CP437.length == 256;
  2757. function decodeCP437(stringValue) {
  2758. if (VALID_CP437) {
  2759. let result = "";
  2760. for (let indexCharacter = 0; indexCharacter < stringValue.length; indexCharacter++) {
  2761. result += CP437[stringValue[indexCharacter]];
  2762. }
  2763. return result;
  2764. } else {
  2765. return new TextDecoder$1().decode(stringValue);
  2766. }
  2767. }
  2768. /*
  2769. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2770. Redistribution and use in source and binary forms, with or without
  2771. modification, are permitted provided that the following conditions are met:
  2772. 1. Redistributions of source code must retain the above copyright notice,
  2773. this list of conditions and the following disclaimer.
  2774. 2. Redistributions in binary form must reproduce the above copyright
  2775. notice, this list of conditions and the following disclaimer in
  2776. the documentation and/or other materials provided with the distribution.
  2777. 3. The names of the authors may not be used to endorse or promote products
  2778. derived from this software without specific prior written permission.
  2779. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2780. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2781. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2782. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2783. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2784. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2785. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2786. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2787. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2788. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2789. */
  2790. function decodeText(value, encoding) {
  2791. if (encoding && encoding.trim().toLowerCase() == "cp437") {
  2792. return decodeCP437(value);
  2793. } else {
  2794. return new TextDecoder$1(encoding).decode(value);
  2795. }
  2796. }
  2797. /*
  2798. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2799. Redistribution and use in source and binary forms, with or without
  2800. modification, are permitted provided that the following conditions are met:
  2801. 1. Redistributions of source code must retain the above copyright notice,
  2802. this list of conditions and the following disclaimer.
  2803. 2. Redistributions in binary form must reproduce the above copyright
  2804. notice, this list of conditions and the following disclaimer in
  2805. the documentation and/or other materials provided with the distribution.
  2806. 3. The names of the authors may not be used to endorse or promote products
  2807. derived from this software without specific prior written permission.
  2808. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2809. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2810. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2811. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2812. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2813. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2814. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2815. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2816. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2817. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2818. */
  2819. const PROPERTY_NAME_FILENAME = "filename";
  2820. const PROPERTY_NAME_RAW_FILENAME = "rawFilename";
  2821. const PROPERTY_NAME_COMMENT = "comment";
  2822. const PROPERTY_NAME_RAW_COMMENT = "rawComment";
  2823. const PROPERTY_NAME_UNCOMPPRESSED_SIZE = "uncompressedSize";
  2824. const PROPERTY_NAME_COMPPRESSED_SIZE = "compressedSize";
  2825. const PROPERTY_NAME_OFFSET = "offset";
  2826. const PROPERTY_NAME_DISK_NUMBER_START = "diskNumberStart";
  2827. const PROPERTY_NAME_LAST_MODIFICATION_DATE = "lastModDate";
  2828. const PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE = "rawLastModDate";
  2829. const PROPERTY_NAME_LAST_ACCESS_DATE = "lastAccessDate";
  2830. const PROPERTY_NAME_RAW_LAST_ACCESS_DATE = "rawLastAccessDate";
  2831. const PROPERTY_NAME_CREATION_DATE = "creationDate";
  2832. const PROPERTY_NAME_RAW_CREATION_DATE = "rawCreationDate";
  2833. const PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE = "internalFileAttribute";
  2834. const PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE = "externalFileAttribute";
  2835. const PROPERTY_NAME_MS_DOS_COMPATIBLE = "msDosCompatible";
  2836. const PROPERTY_NAME_ZIP64 = "zip64";
  2837. const PROPERTY_NAMES = [
  2838. PROPERTY_NAME_FILENAME, PROPERTY_NAME_RAW_FILENAME, PROPERTY_NAME_COMPPRESSED_SIZE, PROPERTY_NAME_UNCOMPPRESSED_SIZE,
  2839. PROPERTY_NAME_LAST_MODIFICATION_DATE, PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE, PROPERTY_NAME_COMMENT, PROPERTY_NAME_RAW_COMMENT,
  2840. PROPERTY_NAME_LAST_ACCESS_DATE, PROPERTY_NAME_CREATION_DATE, PROPERTY_NAME_OFFSET, PROPERTY_NAME_DISK_NUMBER_START,
  2841. PROPERTY_NAME_DISK_NUMBER_START, PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE, PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE,
  2842. PROPERTY_NAME_MS_DOS_COMPATIBLE, PROPERTY_NAME_ZIP64,
  2843. "directory", "bitFlag", "encrypted", "signature", "filenameUTF8", "commentUTF8", "compressionMethod", "version", "versionMadeBy",
  2844. "extraField", "rawExtraField", "extraFieldZip64", "extraFieldUnicodePath", "extraFieldUnicodeComment", "extraFieldAES", "extraFieldNTFS",
  2845. "extraFieldExtendedTimestamp"];
  2846. class Entry {
  2847. constructor(data) {
  2848. PROPERTY_NAMES.forEach(name => this[name] = data[name]);
  2849. }
  2850. }
  2851. /*
  2852. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2853. Redistribution and use in source and binary forms, with or without
  2854. modification, are permitted provided that the following conditions are met:
  2855. 1. Redistributions of source code must retain the above copyright notice,
  2856. this list of conditions and the following disclaimer.
  2857. 2. Redistributions in binary form must reproduce the above copyright
  2858. notice, this list of conditions and the following disclaimer in
  2859. the documentation and/or other materials provided with the distribution.
  2860. 3. The names of the authors may not be used to endorse or promote products
  2861. derived from this software without specific prior written permission.
  2862. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2863. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2864. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2865. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2866. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2867. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2868. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2869. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2870. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2871. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2872. */
  2873. const ERR_BAD_FORMAT = "File format is not recognized";
  2874. const ERR_EOCDR_NOT_FOUND = "End of central directory not found";
  2875. const ERR_EOCDR_ZIP64_NOT_FOUND = "End of Zip64 central directory not found";
  2876. const ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND = "End of Zip64 central directory locator not found";
  2877. const ERR_CENTRAL_DIRECTORY_NOT_FOUND = "Central directory header not found";
  2878. const ERR_LOCAL_FILE_HEADER_NOT_FOUND = "Local file header not found";
  2879. const ERR_EXTRAFIELD_ZIP64_NOT_FOUND = "Zip64 extra field not found";
  2880. const ERR_ENCRYPTED = "File contains encrypted entry";
  2881. const ERR_UNSUPPORTED_ENCRYPTION = "Encryption method not supported";
  2882. const ERR_UNSUPPORTED_COMPRESSION = "Compression method not supported";
  2883. const ERR_SPLIT_ZIP_FILE = "Split zip file";
  2884. const CHARSET_UTF8 = "utf-8";
  2885. const CHARSET_CP437 = "cp437";
  2886. const ZIP64_PROPERTIES = [
  2887. [PROPERTY_NAME_UNCOMPPRESSED_SIZE, MAX_32_BITS],
  2888. [PROPERTY_NAME_COMPPRESSED_SIZE, MAX_32_BITS],
  2889. [PROPERTY_NAME_OFFSET, MAX_32_BITS],
  2890. [PROPERTY_NAME_DISK_NUMBER_START, MAX_16_BITS]
  2891. ];
  2892. const ZIP64_EXTRACTION = {
  2893. [MAX_16_BITS]: {
  2894. getValue: getUint32,
  2895. bytes: 4
  2896. },
  2897. [MAX_32_BITS]: {
  2898. getValue: getBigUint64,
  2899. bytes: 8
  2900. }
  2901. };
  2902. class ZipReader {
  2903. constructor(reader, options = {}) {
  2904. Object$1.assign(this, {
  2905. reader: initReader(reader),
  2906. options,
  2907. config: getConfiguration()
  2908. });
  2909. }
  2910. async* getEntriesGenerator(options = {}) {
  2911. const zipReader = this;
  2912. let { reader } = zipReader;
  2913. const { config } = zipReader;
  2914. await initStream(reader);
  2915. if (reader.size === UNDEFINED_VALUE || !reader.readUint8Array) {
  2916. reader = new BlobReader(await new Response(reader.readable).blob());
  2917. await initStream(reader);
  2918. }
  2919. if (reader.size < END_OF_CENTRAL_DIR_LENGTH) {
  2920. throw new Error(ERR_BAD_FORMAT);
  2921. }
  2922. reader.chunkSize = getChunkSize(config);
  2923. const endOfDirectoryInfo = await seekSignature(reader, END_OF_CENTRAL_DIR_SIGNATURE, reader.size, END_OF_CENTRAL_DIR_LENGTH, MAX_16_BITS * 16);
  2924. if (!endOfDirectoryInfo) {
  2925. const signatureArray = await readUint8Array(reader, 0, 4);
  2926. const signatureView = getDataView$1(signatureArray);
  2927. if (getUint32(signatureView) == SPLIT_ZIP_FILE_SIGNATURE) {
  2928. throw new Error(ERR_SPLIT_ZIP_FILE);
  2929. } else {
  2930. throw new Error(ERR_EOCDR_NOT_FOUND);
  2931. }
  2932. }
  2933. const endOfDirectoryView = getDataView$1(endOfDirectoryInfo);
  2934. let directoryDataLength = getUint32(endOfDirectoryView, 12);
  2935. let directoryDataOffset = getUint32(endOfDirectoryView, 16);
  2936. const commentOffset = endOfDirectoryInfo.offset;
  2937. const commentLength = getUint16(endOfDirectoryView, 20);
  2938. const appendedDataOffset = commentOffset + END_OF_CENTRAL_DIR_LENGTH + commentLength;
  2939. let lastDiskNumber = getUint16(endOfDirectoryView, 4);
  2940. const expectedLastDiskNumber = reader.lastDiskNumber || 0;
  2941. let diskNumber = getUint16(endOfDirectoryView, 6);
  2942. let filesLength = getUint16(endOfDirectoryView, 8);
  2943. let prependedDataLength = 0;
  2944. let startOffset = 0;
  2945. if (directoryDataOffset == MAX_32_BITS || directoryDataLength == MAX_32_BITS || filesLength == MAX_16_BITS || diskNumber == MAX_16_BITS) {
  2946. const endOfDirectoryLocatorArray = await readUint8Array(reader, endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH);
  2947. const endOfDirectoryLocatorView = getDataView$1(endOfDirectoryLocatorArray);
  2948. if (getUint32(endOfDirectoryLocatorView, 0) != ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE) {
  2949. throw new Error(ERR_EOCDR_ZIP64_NOT_FOUND);
  2950. }
  2951. directoryDataOffset = getBigUint64(endOfDirectoryLocatorView, 8);
  2952. let endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH, -1);
  2953. let endOfDirectoryView = getDataView$1(endOfDirectoryArray);
  2954. const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH - ZIP64_END_OF_CENTRAL_DIR_LENGTH;
  2955. if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
  2956. const originalDirectoryDataOffset = directoryDataOffset;
  2957. directoryDataOffset = expectedDirectoryDataOffset;
  2958. prependedDataLength = directoryDataOffset - originalDirectoryDataOffset;
  2959. endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH, -1);
  2960. endOfDirectoryView = getDataView$1(endOfDirectoryArray);
  2961. }
  2962. if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE) {
  2963. throw new Error(ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND);
  2964. }
  2965. if (lastDiskNumber == MAX_16_BITS) {
  2966. lastDiskNumber = getUint32(endOfDirectoryView, 16);
  2967. }
  2968. if (diskNumber == MAX_16_BITS) {
  2969. diskNumber = getUint32(endOfDirectoryView, 20);
  2970. }
  2971. if (filesLength == MAX_16_BITS) {
  2972. filesLength = getBigUint64(endOfDirectoryView, 32);
  2973. }
  2974. if (directoryDataLength == MAX_32_BITS) {
  2975. directoryDataLength = getBigUint64(endOfDirectoryView, 40);
  2976. }
  2977. directoryDataOffset -= directoryDataLength;
  2978. }
  2979. if (expectedLastDiskNumber != lastDiskNumber) {
  2980. throw new Error(ERR_SPLIT_ZIP_FILE);
  2981. }
  2982. if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) {
  2983. throw new Error(ERR_BAD_FORMAT);
  2984. }
  2985. let offset = 0;
  2986. let directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber);
  2987. let directoryView = getDataView$1(directoryArray);
  2988. if (directoryDataLength) {
  2989. const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - directoryDataLength;
  2990. if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
  2991. const originalDirectoryDataOffset = directoryDataOffset;
  2992. directoryDataOffset = expectedDirectoryDataOffset;
  2993. prependedDataLength = directoryDataOffset - originalDirectoryDataOffset;
  2994. directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber);
  2995. directoryView = getDataView$1(directoryArray);
  2996. }
  2997. }
  2998. const expectedDirectoryDataLength = endOfDirectoryInfo.offset - directoryDataOffset - (reader.lastDiskOffset || 0);
  2999. if (directoryDataLength != expectedDirectoryDataLength && expectedDirectoryDataLength >= 0) {
  3000. directoryDataLength = expectedDirectoryDataLength;
  3001. directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber);
  3002. directoryView = getDataView$1(directoryArray);
  3003. }
  3004. if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) {
  3005. throw new Error(ERR_BAD_FORMAT);
  3006. }
  3007. const filenameEncoding = getOptionValue$1(zipReader, options, "filenameEncoding");
  3008. const commentEncoding = getOptionValue$1(zipReader, options, "commentEncoding");
  3009. for (let indexFile = 0; indexFile < filesLength; indexFile++) {
  3010. const fileEntry = new ZipEntry(reader, config, zipReader.options);
  3011. if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE) {
  3012. throw new Error(ERR_CENTRAL_DIRECTORY_NOT_FOUND);
  3013. }
  3014. readCommonHeader(fileEntry, directoryView, offset + 6);
  3015. const languageEncodingFlag = Boolean(fileEntry.bitFlag.languageEncodingFlag);
  3016. const filenameOffset = offset + 46;
  3017. const extraFieldOffset = filenameOffset + fileEntry.filenameLength;
  3018. const commentOffset = extraFieldOffset + fileEntry.extraFieldLength;
  3019. const versionMadeBy = getUint16(directoryView, offset + 4);
  3020. const msDosCompatible = (versionMadeBy & 0) == 0;
  3021. const rawFilename = directoryArray.subarray(filenameOffset, extraFieldOffset);
  3022. const commentLength = getUint16(directoryView, offset + 32);
  3023. const endOffset = commentOffset + commentLength;
  3024. const rawComment = directoryArray.subarray(commentOffset, endOffset);
  3025. const filenameUTF8 = languageEncodingFlag;
  3026. const commentUTF8 = languageEncodingFlag;
  3027. const directory = msDosCompatible && ((getUint8(directoryView, offset + 38) & FILE_ATTR_MSDOS_DIR_MASK) == FILE_ATTR_MSDOS_DIR_MASK);
  3028. const offsetFileEntry = getUint32(directoryView, offset + 42) + prependedDataLength;
  3029. Object$1.assign(fileEntry, {
  3030. versionMadeBy,
  3031. msDosCompatible,
  3032. compressedSize: 0,
  3033. uncompressedSize: 0,
  3034. commentLength,
  3035. directory,
  3036. offset: offsetFileEntry,
  3037. diskNumberStart: getUint16(directoryView, offset + 34),
  3038. internalFileAttribute: getUint16(directoryView, offset + 36),
  3039. externalFileAttribute: getUint32(directoryView, offset + 38),
  3040. rawFilename,
  3041. filenameUTF8,
  3042. commentUTF8,
  3043. rawExtraField: directoryArray.subarray(extraFieldOffset, commentOffset)
  3044. });
  3045. const [filename, comment] = await Promise$1.all([
  3046. decodeText(rawFilename, filenameUTF8 ? CHARSET_UTF8 : filenameEncoding || CHARSET_CP437),
  3047. decodeText(rawComment, commentUTF8 ? CHARSET_UTF8 : commentEncoding || CHARSET_CP437)
  3048. ]);
  3049. Object$1.assign(fileEntry, {
  3050. rawComment,
  3051. filename,
  3052. comment,
  3053. directory: directory || filename.endsWith(DIRECTORY_SIGNATURE)
  3054. });
  3055. startOffset = Math$1.max(offsetFileEntry, startOffset);
  3056. await readCommonFooter(fileEntry, fileEntry, directoryView, offset + 6);
  3057. const entry = new Entry(fileEntry);
  3058. entry.getData = (writer, options) => fileEntry.getData(writer, entry, options);
  3059. offset = endOffset;
  3060. const { onprogress } = options;
  3061. if (onprogress) {
  3062. try {
  3063. await onprogress(indexFile + 1, filesLength, new Entry(fileEntry));
  3064. } catch (_error) {
  3065. // ignored
  3066. }
  3067. }
  3068. yield entry;
  3069. }
  3070. const extractPrependedData = getOptionValue$1(zipReader, options, "extractPrependedData");
  3071. const extractAppendedData = getOptionValue$1(zipReader, options, "extractAppendedData");
  3072. if (extractPrependedData) {
  3073. zipReader.prependedData = startOffset > 0 ? await readUint8Array(reader, 0, startOffset) : new Uint8Array$1();
  3074. }
  3075. zipReader.comment = commentLength ? await readUint8Array(reader, commentOffset + END_OF_CENTRAL_DIR_LENGTH, commentLength) : new Uint8Array$1();
  3076. if (extractAppendedData) {
  3077. zipReader.appendedData = appendedDataOffset < reader.size ? await readUint8Array(reader, appendedDataOffset, reader.size - appendedDataOffset) : new Uint8Array$1();
  3078. }
  3079. return true;
  3080. }
  3081. async getEntries(options = {}) {
  3082. const entries = [];
  3083. for await (const entry of this.getEntriesGenerator(options)) {
  3084. entries.push(entry);
  3085. }
  3086. return entries;
  3087. }
  3088. async close() {
  3089. }
  3090. }
  3091. class ZipEntry {
  3092. constructor(reader, config, options) {
  3093. Object$1.assign(this, {
  3094. reader,
  3095. config,
  3096. options
  3097. });
  3098. }
  3099. async getData(writer, fileEntry, options = {}) {
  3100. const zipEntry = this;
  3101. const {
  3102. reader,
  3103. offset,
  3104. diskNumberStart,
  3105. extraFieldAES,
  3106. compressionMethod,
  3107. config,
  3108. bitFlag,
  3109. signature,
  3110. rawLastModDate,
  3111. uncompressedSize,
  3112. compressedSize
  3113. } = zipEntry;
  3114. const localDirectory = fileEntry.localDirectory = {};
  3115. const dataArray = await readUint8Array(reader, offset, 30, diskNumberStart);
  3116. const dataView = getDataView$1(dataArray);
  3117. let password = getOptionValue$1(zipEntry, options, "password");
  3118. password = password && password.length && password;
  3119. if (extraFieldAES) {
  3120. if (extraFieldAES.originalCompressionMethod != COMPRESSION_METHOD_AES) {
  3121. throw new Error(ERR_UNSUPPORTED_COMPRESSION);
  3122. }
  3123. }
  3124. if (compressionMethod != COMPRESSION_METHOD_STORE && compressionMethod != COMPRESSION_METHOD_DEFLATE) {
  3125. throw new Error(ERR_UNSUPPORTED_COMPRESSION);
  3126. }
  3127. if (getUint32(dataView, 0) != LOCAL_FILE_HEADER_SIGNATURE) {
  3128. throw new Error(ERR_LOCAL_FILE_HEADER_NOT_FOUND);
  3129. }
  3130. readCommonHeader(localDirectory, dataView, 4);
  3131. localDirectory.rawExtraField = localDirectory.extraFieldLength ?
  3132. await readUint8Array(reader, offset + 30 + localDirectory.filenameLength, localDirectory.extraFieldLength, diskNumberStart) :
  3133. new Uint8Array$1();
  3134. await readCommonFooter(zipEntry, localDirectory, dataView, 4, true);
  3135. Object$1.assign(fileEntry, {
  3136. lastAccessDate: localDirectory.lastAccessDate,
  3137. creationDate: localDirectory.creationDate
  3138. });
  3139. const encrypted = zipEntry.encrypted && localDirectory.encrypted;
  3140. const zipCrypto = encrypted && !extraFieldAES;
  3141. if (encrypted) {
  3142. if (!zipCrypto && extraFieldAES.strength === UNDEFINED_VALUE) {
  3143. throw new Error(ERR_UNSUPPORTED_ENCRYPTION);
  3144. } else if (!password) {
  3145. throw new Error(ERR_ENCRYPTED);
  3146. }
  3147. }
  3148. const dataOffset = offset + 30 + localDirectory.filenameLength + localDirectory.extraFieldLength;
  3149. const size = compressedSize;
  3150. const readable = reader.readable;
  3151. Object$1.assign(readable, {
  3152. diskNumberStart,
  3153. offset: dataOffset,
  3154. size
  3155. });
  3156. const signal = getOptionValue$1(zipEntry, options, "signal");
  3157. const checkPasswordOnly = getOptionValue$1(zipEntry, options, "checkPasswordOnly");
  3158. if (checkPasswordOnly) {
  3159. writer = new WritableStream();
  3160. }
  3161. writer = initWriter(writer);
  3162. await initStream(writer, uncompressedSize);
  3163. const { writable } = writer;
  3164. const { onstart, onprogress, onend } = options;
  3165. const workerOptions = {
  3166. options: {
  3167. codecType: CODEC_INFLATE,
  3168. password,
  3169. zipCrypto,
  3170. encryptionStrength: extraFieldAES && extraFieldAES.strength,
  3171. signed: getOptionValue$1(zipEntry, options, "checkSignature"),
  3172. passwordVerification: zipCrypto && (bitFlag.dataDescriptor ? ((rawLastModDate >>> 8) & 0xFF) : ((signature >>> 24) & 0xFF)),
  3173. signature,
  3174. compressed: compressionMethod != 0,
  3175. encrypted,
  3176. useWebWorkers: getOptionValue$1(zipEntry, options, "useWebWorkers"),
  3177. useCompressionStream: getOptionValue$1(zipEntry, options, "useCompressionStream"),
  3178. transferStreams: getOptionValue$1(zipEntry, options, "transferStreams"),
  3179. checkPasswordOnly
  3180. },
  3181. config,
  3182. streamOptions: { signal, size, onstart, onprogress, onend }
  3183. };
  3184. let outputSize = 0;
  3185. try {
  3186. ({ outputSize } = (await runWorker({ readable, writable }, workerOptions)));
  3187. } catch (error) {
  3188. if (!checkPasswordOnly || error.message != ERR_ABORT_CHECK_PASSWORD) {
  3189. throw error;
  3190. }
  3191. } finally {
  3192. const preventClose = getOptionValue$1(zipEntry, options, "preventClose");
  3193. writable.size += outputSize;
  3194. if (!preventClose && !writable.locked) {
  3195. await writable.getWriter().close();
  3196. }
  3197. }
  3198. return checkPasswordOnly ? undefined : writer.getData ? writer.getData() : writable;
  3199. }
  3200. }
  3201. function readCommonHeader(directory, dataView, offset) {
  3202. const rawBitFlag = directory.rawBitFlag = getUint16(dataView, offset + 2);
  3203. const encrypted = (rawBitFlag & BITFLAG_ENCRYPTED) == BITFLAG_ENCRYPTED;
  3204. const rawLastModDate = getUint32(dataView, offset + 6);
  3205. Object$1.assign(directory, {
  3206. encrypted,
  3207. version: getUint16(dataView, offset),
  3208. bitFlag: {
  3209. level: (rawBitFlag & BITFLAG_LEVEL) >> 1,
  3210. dataDescriptor: (rawBitFlag & BITFLAG_DATA_DESCRIPTOR) == BITFLAG_DATA_DESCRIPTOR,
  3211. languageEncodingFlag: (rawBitFlag & BITFLAG_LANG_ENCODING_FLAG) == BITFLAG_LANG_ENCODING_FLAG
  3212. },
  3213. rawLastModDate,
  3214. lastModDate: getDate(rawLastModDate),
  3215. filenameLength: getUint16(dataView, offset + 22),
  3216. extraFieldLength: getUint16(dataView, offset + 24)
  3217. });
  3218. }
  3219. async function readCommonFooter(fileEntry, directory, dataView, offset, localDirectory) {
  3220. const { rawExtraField } = directory;
  3221. const extraField = directory.extraField = new Map();
  3222. const rawExtraFieldView = getDataView$1(new Uint8Array$1(rawExtraField));
  3223. let offsetExtraField = 0;
  3224. try {
  3225. while (offsetExtraField < rawExtraField.length) {
  3226. const type = getUint16(rawExtraFieldView, offsetExtraField);
  3227. const size = getUint16(rawExtraFieldView, offsetExtraField + 2);
  3228. extraField.set(type, {
  3229. type,
  3230. data: rawExtraField.slice(offsetExtraField + 4, offsetExtraField + 4 + size)
  3231. });
  3232. offsetExtraField += 4 + size;
  3233. }
  3234. } catch (_error) {
  3235. // ignored
  3236. }
  3237. const compressionMethod = getUint16(dataView, offset + 4);
  3238. Object$1.assign(directory, {
  3239. signature: getUint32(dataView, offset + 10),
  3240. uncompressedSize: getUint32(dataView, offset + 18),
  3241. compressedSize: getUint32(dataView, offset + 14)
  3242. });
  3243. const extraFieldZip64 = extraField.get(EXTRAFIELD_TYPE_ZIP64);
  3244. if (extraFieldZip64) {
  3245. readExtraFieldZip64(extraFieldZip64, directory);
  3246. directory.extraFieldZip64 = extraFieldZip64;
  3247. }
  3248. const extraFieldUnicodePath = extraField.get(EXTRAFIELD_TYPE_UNICODE_PATH);
  3249. if (extraFieldUnicodePath) {
  3250. await readExtraFieldUnicode(extraFieldUnicodePath, PROPERTY_NAME_FILENAME, PROPERTY_NAME_RAW_FILENAME, directory, fileEntry);
  3251. directory.extraFieldUnicodePath = extraFieldUnicodePath;
  3252. }
  3253. const extraFieldUnicodeComment = extraField.get(EXTRAFIELD_TYPE_UNICODE_COMMENT);
  3254. if (extraFieldUnicodeComment) {
  3255. await readExtraFieldUnicode(extraFieldUnicodeComment, PROPERTY_NAME_COMMENT, PROPERTY_NAME_RAW_COMMENT, directory, fileEntry);
  3256. directory.extraFieldUnicodeComment = extraFieldUnicodeComment;
  3257. }
  3258. const extraFieldAES = extraField.get(EXTRAFIELD_TYPE_AES);
  3259. if (extraFieldAES) {
  3260. readExtraFieldAES(extraFieldAES, directory, compressionMethod);
  3261. directory.extraFieldAES = extraFieldAES;
  3262. } else {
  3263. directory.compressionMethod = compressionMethod;
  3264. }
  3265. const extraFieldNTFS = extraField.get(EXTRAFIELD_TYPE_NTFS);
  3266. if (extraFieldNTFS) {
  3267. readExtraFieldNTFS(extraFieldNTFS, directory);
  3268. directory.extraFieldNTFS = extraFieldNTFS;
  3269. }
  3270. const extraFieldExtendedTimestamp = extraField.get(EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  3271. if (extraFieldExtendedTimestamp) {
  3272. readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory, localDirectory);
  3273. directory.extraFieldExtendedTimestamp = extraFieldExtendedTimestamp;
  3274. }
  3275. const extraFieldUSDZ = extraField.get(EXTRAFIELD_TYPE_USDZ);
  3276. if (extraFieldUSDZ) {
  3277. directory.extraFieldUSDZ = extraFieldUSDZ;
  3278. }
  3279. }
  3280. function readExtraFieldZip64(extraFieldZip64, directory) {
  3281. directory.zip64 = true;
  3282. const extraFieldView = getDataView$1(extraFieldZip64.data);
  3283. const missingProperties = ZIP64_PROPERTIES.filter(([propertyName, max]) => directory[propertyName] == max);
  3284. for (let indexMissingProperty = 0, offset = 0; indexMissingProperty < missingProperties.length; indexMissingProperty++) {
  3285. const [propertyName, max] = missingProperties[indexMissingProperty];
  3286. if (directory[propertyName] == max) {
  3287. const extraction = ZIP64_EXTRACTION[max];
  3288. directory[propertyName] = extraFieldZip64[propertyName] = extraction.getValue(extraFieldView, offset);
  3289. offset += extraction.bytes;
  3290. } else if (extraFieldZip64[propertyName]) {
  3291. throw new Error(ERR_EXTRAFIELD_ZIP64_NOT_FOUND);
  3292. }
  3293. }
  3294. }
  3295. async function readExtraFieldUnicode(extraFieldUnicode, propertyName, rawPropertyName, directory, fileEntry) {
  3296. const extraFieldView = getDataView$1(extraFieldUnicode.data);
  3297. const crc32 = new Crc32();
  3298. crc32.append(fileEntry[rawPropertyName]);
  3299. const dataViewSignature = getDataView$1(new Uint8Array$1(4));
  3300. dataViewSignature.setUint32(0, crc32.get(), true);
  3301. const signature = getUint32(extraFieldView, 1);
  3302. Object$1.assign(extraFieldUnicode, {
  3303. version: getUint8(extraFieldView, 0),
  3304. [propertyName]: decodeText(extraFieldUnicode.data.subarray(5)),
  3305. valid: !fileEntry.bitFlag.languageEncodingFlag && signature == getUint32(dataViewSignature, 0)
  3306. });
  3307. if (extraFieldUnicode.valid) {
  3308. directory[propertyName] = extraFieldUnicode[propertyName];
  3309. directory[propertyName + "UTF8"] = true;
  3310. }
  3311. }
  3312. function readExtraFieldAES(extraFieldAES, directory, compressionMethod) {
  3313. const extraFieldView = getDataView$1(extraFieldAES.data);
  3314. const strength = getUint8(extraFieldView, 4);
  3315. Object$1.assign(extraFieldAES, {
  3316. vendorVersion: getUint8(extraFieldView, 0),
  3317. vendorId: getUint8(extraFieldView, 2),
  3318. strength,
  3319. originalCompressionMethod: compressionMethod,
  3320. compressionMethod: getUint16(extraFieldView, 5)
  3321. });
  3322. directory.compressionMethod = extraFieldAES.compressionMethod;
  3323. }
  3324. function readExtraFieldNTFS(extraFieldNTFS, directory) {
  3325. const extraFieldView = getDataView$1(extraFieldNTFS.data);
  3326. let offsetExtraField = 4;
  3327. let tag1Data;
  3328. try {
  3329. while (offsetExtraField < extraFieldNTFS.data.length && !tag1Data) {
  3330. const tagValue = getUint16(extraFieldView, offsetExtraField);
  3331. const attributeSize = getUint16(extraFieldView, offsetExtraField + 2);
  3332. if (tagValue == EXTRAFIELD_TYPE_NTFS_TAG1) {
  3333. tag1Data = extraFieldNTFS.data.slice(offsetExtraField + 4, offsetExtraField + 4 + attributeSize);
  3334. }
  3335. offsetExtraField += 4 + attributeSize;
  3336. }
  3337. } catch (_error) {
  3338. // ignored
  3339. }
  3340. try {
  3341. if (tag1Data && tag1Data.length == 24) {
  3342. const tag1View = getDataView$1(tag1Data);
  3343. const rawLastModDate = tag1View.getBigUint64(0, true);
  3344. const rawLastAccessDate = tag1View.getBigUint64(8, true);
  3345. const rawCreationDate = tag1View.getBigUint64(16, true);
  3346. Object$1.assign(extraFieldNTFS, {
  3347. rawLastModDate,
  3348. rawLastAccessDate,
  3349. rawCreationDate
  3350. });
  3351. const lastModDate = getDateNTFS(rawLastModDate);
  3352. const lastAccessDate = getDateNTFS(rawLastAccessDate);
  3353. const creationDate = getDateNTFS(rawCreationDate);
  3354. const extraFieldData = { lastModDate, lastAccessDate, creationDate };
  3355. Object$1.assign(extraFieldNTFS, extraFieldData);
  3356. Object$1.assign(directory, extraFieldData);
  3357. }
  3358. } catch (_error) {
  3359. // ignored
  3360. }
  3361. }
  3362. function readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory, localDirectory) {
  3363. const extraFieldView = getDataView$1(extraFieldExtendedTimestamp.data);
  3364. const flags = getUint8(extraFieldView, 0);
  3365. const timeProperties = [];
  3366. const timeRawProperties = [];
  3367. if (localDirectory) {
  3368. if ((flags & 0x1) == 0x1) {
  3369. timeProperties.push(PROPERTY_NAME_LAST_MODIFICATION_DATE);
  3370. timeRawProperties.push(PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE);
  3371. }
  3372. if ((flags & 0x2) == 0x2) {
  3373. timeProperties.push(PROPERTY_NAME_LAST_ACCESS_DATE);
  3374. timeRawProperties.push(PROPERTY_NAME_RAW_LAST_ACCESS_DATE);
  3375. }
  3376. if ((flags & 0x4) == 0x4) {
  3377. timeProperties.push(PROPERTY_NAME_CREATION_DATE);
  3378. timeRawProperties.push(PROPERTY_NAME_RAW_CREATION_DATE);
  3379. }
  3380. } else if (extraFieldExtendedTimestamp.data.length >= 5) {
  3381. timeProperties.push(PROPERTY_NAME_LAST_MODIFICATION_DATE);
  3382. timeRawProperties.push(PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE);
  3383. }
  3384. let offset = 1;
  3385. timeProperties.forEach((propertyName, indexProperty) => {
  3386. if (extraFieldExtendedTimestamp.data.length >= offset + 4) {
  3387. const time = getUint32(extraFieldView, offset);
  3388. directory[propertyName] = extraFieldExtendedTimestamp[propertyName] = new Date(time * 1000);
  3389. const rawPropertyName = timeRawProperties[indexProperty];
  3390. extraFieldExtendedTimestamp[rawPropertyName] = time;
  3391. }
  3392. offset += 4;
  3393. });
  3394. }
  3395. async function seekSignature(reader, signature, startOffset, minimumBytes, maximumLength) {
  3396. const signatureArray = new Uint8Array$1(4);
  3397. const signatureView = getDataView$1(signatureArray);
  3398. setUint32$1(signatureView, 0, signature);
  3399. const maximumBytes = minimumBytes + maximumLength;
  3400. return (await seek(minimumBytes)) || await seek(Math$1.min(maximumBytes, startOffset));
  3401. async function seek(length) {
  3402. const offset = startOffset - length;
  3403. const bytes = await readUint8Array(reader, offset, length);
  3404. for (let indexByte = bytes.length - minimumBytes; indexByte >= 0; indexByte--) {
  3405. if (bytes[indexByte] == signatureArray[0] && bytes[indexByte + 1] == signatureArray[1] &&
  3406. bytes[indexByte + 2] == signatureArray[2] && bytes[indexByte + 3] == signatureArray[3]) {
  3407. return {
  3408. offset: offset + indexByte,
  3409. buffer: bytes.slice(indexByte, indexByte + minimumBytes).buffer
  3410. };
  3411. }
  3412. }
  3413. }
  3414. }
  3415. function getOptionValue$1(zipReader, options, name) {
  3416. return options[name] === UNDEFINED_VALUE ? zipReader.options[name] : options[name];
  3417. }
  3418. function getDate(timeRaw) {
  3419. const date = (timeRaw & 0xffff0000) >> 16, time = timeRaw & 0x0000ffff;
  3420. try {
  3421. return new Date(1980 + ((date & 0xFE00) >> 9), ((date & 0x01E0) >> 5) - 1, date & 0x001F, (time & 0xF800) >> 11, (time & 0x07E0) >> 5, (time & 0x001F) * 2, 0);
  3422. } catch (_error) {
  3423. // ignored
  3424. }
  3425. }
  3426. function getDateNTFS(timeRaw) {
  3427. return new Date((Number$1((timeRaw / BigInt(10000)) - BigInt(11644473600000))));
  3428. }
  3429. function getUint8(view, offset) {
  3430. return view.getUint8(offset);
  3431. }
  3432. function getUint16(view, offset) {
  3433. return view.getUint16(offset, true);
  3434. }
  3435. function getUint32(view, offset) {
  3436. return view.getUint32(offset, true);
  3437. }
  3438. function getBigUint64(view, offset) {
  3439. return Number$1(view.getBigUint64(offset, true));
  3440. }
  3441. function setUint32$1(view, offset, value) {
  3442. view.setUint32(offset, value, true);
  3443. }
  3444. function getDataView$1(array) {
  3445. return new DataView(array.buffer);
  3446. }
  3447. /*
  3448. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  3449. Redistribution and use in source and binary forms, with or without
  3450. modification, are permitted provided that the following conditions are met:
  3451. 1. Redistributions of source code must retain the above copyright notice,
  3452. this list of conditions and the following disclaimer.
  3453. 2. Redistributions in binary form must reproduce the above copyright
  3454. notice, this list of conditions and the following disclaimer in
  3455. the documentation and/or other materials provided with the distribution.
  3456. 3. The names of the authors may not be used to endorse or promote products
  3457. derived from this software without specific prior written permission.
  3458. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  3459. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  3460. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  3461. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  3462. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  3463. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  3464. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  3465. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  3466. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  3467. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3468. */
  3469. const ERR_DUPLICATED_NAME = "File already exists";
  3470. const ERR_INVALID_COMMENT = "Zip file comment exceeds 64KB";
  3471. const ERR_INVALID_ENTRY_COMMENT = "File entry comment exceeds 64KB";
  3472. const ERR_INVALID_ENTRY_NAME = "File entry name exceeds 64KB";
  3473. const ERR_INVALID_VERSION = "Version exceeds 65535";
  3474. const ERR_INVALID_ENCRYPTION_STRENGTH = "The strength must equal 1, 2, or 3";
  3475. const ERR_INVALID_EXTRAFIELD_TYPE = "Extra field type exceeds 65535";
  3476. const ERR_INVALID_EXTRAFIELD_DATA = "Extra field data exceeds 64KB";
  3477. const ERR_UNSUPPORTED_FORMAT = "Zip64 is not supported (make sure 'keepOrder' is set to 'true')";
  3478. const EXTRAFIELD_DATA_AES = new Uint8Array$1([0x07, 0x00, 0x02, 0x00, 0x41, 0x45, 0x03, 0x00, 0x00]);
  3479. let workers = 0;
  3480. const pendingEntries = [];
  3481. class ZipWriter {
  3482. constructor(writer, options = {}) {
  3483. writer = initWriter(writer);
  3484. Object$1.assign(this, {
  3485. writer,
  3486. addSplitZipSignature: writer instanceof SplitDataWriter,
  3487. options,
  3488. config: getConfiguration(),
  3489. files: new Map(),
  3490. filenames: new Set$1(),
  3491. offset: writer.writable.size,
  3492. pendingEntriesSize: 0,
  3493. pendingAddFileCalls: new Set$1(),
  3494. bufferedWrites: 0
  3495. });
  3496. }
  3497. async add(name = "", reader, options = {}) {
  3498. const zipWriter = this;
  3499. const {
  3500. pendingAddFileCalls,
  3501. config
  3502. } = zipWriter;
  3503. if (workers < config.maxWorkers) {
  3504. workers++;
  3505. } else {
  3506. await new Promise$1(resolve => pendingEntries.push(resolve));
  3507. }
  3508. let promiseAddFile;
  3509. try {
  3510. name = name.trim();
  3511. if (zipWriter.filenames.has(name)) {
  3512. throw new Error(ERR_DUPLICATED_NAME);
  3513. }
  3514. zipWriter.filenames.add(name);
  3515. promiseAddFile = addFile(zipWriter, name, reader, options);
  3516. pendingAddFileCalls.add(promiseAddFile);
  3517. return await promiseAddFile;
  3518. } catch (error) {
  3519. zipWriter.filenames.delete(name);
  3520. throw error;
  3521. } finally {
  3522. pendingAddFileCalls.delete(promiseAddFile);
  3523. const pendingEntry = pendingEntries.shift();
  3524. if (pendingEntry) {
  3525. pendingEntry();
  3526. } else {
  3527. workers--;
  3528. }
  3529. }
  3530. }
  3531. async close(comment = new Uint8Array$1(), options = {}) {
  3532. const zipWriter = this;
  3533. const { pendingAddFileCalls, writer } = this;
  3534. const { writable } = writer;
  3535. while (pendingAddFileCalls.size) {
  3536. await Promise$1.all(Array$1.from(pendingAddFileCalls));
  3537. }
  3538. await closeFile(this, comment, options);
  3539. const preventClose = getOptionValue(zipWriter, options, "preventClose");
  3540. if (!preventClose) {
  3541. await writable.getWriter().close();
  3542. }
  3543. return writer.getData ? writer.getData() : writable;
  3544. }
  3545. }
  3546. async function addFile(zipWriter, name, reader, options) {
  3547. name = name.trim();
  3548. if (options.directory && (!name.endsWith(DIRECTORY_SIGNATURE))) {
  3549. name += DIRECTORY_SIGNATURE;
  3550. } else {
  3551. options.directory = name.endsWith(DIRECTORY_SIGNATURE);
  3552. }
  3553. const rawFilename = encodeText(name);
  3554. if (getLength(rawFilename) > MAX_16_BITS) {
  3555. throw new Error(ERR_INVALID_ENTRY_NAME);
  3556. }
  3557. const comment = options.comment || "";
  3558. const rawComment = encodeText(comment);
  3559. if (getLength(rawComment) > MAX_16_BITS) {
  3560. throw new Error(ERR_INVALID_ENTRY_COMMENT);
  3561. }
  3562. const version = getOptionValue(zipWriter, options, "version", VERSION_DEFLATE);
  3563. if (version > MAX_16_BITS) {
  3564. throw new Error(ERR_INVALID_VERSION);
  3565. }
  3566. const versionMadeBy = getOptionValue(zipWriter, options, "versionMadeBy", 20);
  3567. if (versionMadeBy > MAX_16_BITS) {
  3568. throw new Error(ERR_INVALID_VERSION);
  3569. }
  3570. const lastModDate = getOptionValue(zipWriter, options, PROPERTY_NAME_LAST_MODIFICATION_DATE, new Date());
  3571. const lastAccessDate = getOptionValue(zipWriter, options, PROPERTY_NAME_LAST_ACCESS_DATE);
  3572. const creationDate = getOptionValue(zipWriter, options, PROPERTY_NAME_CREATION_DATE);
  3573. const msDosCompatible = getOptionValue(zipWriter, options, PROPERTY_NAME_MS_DOS_COMPATIBLE, true);
  3574. const internalFileAttribute = getOptionValue(zipWriter, options, PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE, 0);
  3575. const externalFileAttribute = getOptionValue(zipWriter, options, PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE, 0);
  3576. const password = getOptionValue(zipWriter, options, "password");
  3577. const encryptionStrength = getOptionValue(zipWriter, options, "encryptionStrength", 3);
  3578. const zipCrypto = getOptionValue(zipWriter, options, "zipCrypto");
  3579. const extendedTimestamp = getOptionValue(zipWriter, options, "extendedTimestamp", true);
  3580. const keepOrder = getOptionValue(zipWriter, options, "keepOrder", true);
  3581. const level = getOptionValue(zipWriter, options, "level");
  3582. const useWebWorkers = getOptionValue(zipWriter, options, "useWebWorkers");
  3583. const bufferedWrite = getOptionValue(zipWriter, options, "bufferedWrite");
  3584. const dataDescriptorSignature = getOptionValue(zipWriter, options, "dataDescriptorSignature", false);
  3585. const signal = getOptionValue(zipWriter, options, "signal");
  3586. const useCompressionStream = getOptionValue(zipWriter, options, "useCompressionStream");
  3587. let dataDescriptor = getOptionValue(zipWriter, options, "dataDescriptor", true);
  3588. let zip64 = getOptionValue(zipWriter, options, PROPERTY_NAME_ZIP64);
  3589. if (password !== UNDEFINED_VALUE && encryptionStrength !== UNDEFINED_VALUE && (encryptionStrength < 1 || encryptionStrength > 3)) {
  3590. throw new Error(ERR_INVALID_ENCRYPTION_STRENGTH);
  3591. }
  3592. let rawExtraField = new Uint8Array$1();
  3593. const { extraField } = options;
  3594. if (extraField) {
  3595. let extraFieldSize = 0;
  3596. let offset = 0;
  3597. extraField.forEach(data => extraFieldSize += 4 + getLength(data));
  3598. rawExtraField = new Uint8Array$1(extraFieldSize);
  3599. extraField.forEach((data, type) => {
  3600. if (type > MAX_16_BITS) {
  3601. throw new Error(ERR_INVALID_EXTRAFIELD_TYPE);
  3602. }
  3603. if (getLength(data) > MAX_16_BITS) {
  3604. throw new Error(ERR_INVALID_EXTRAFIELD_DATA);
  3605. }
  3606. arraySet(rawExtraField, new Uint16Array([type]), offset);
  3607. arraySet(rawExtraField, new Uint16Array([getLength(data)]), offset + 2);
  3608. arraySet(rawExtraField, data, offset + 4);
  3609. offset += 4 + getLength(data);
  3610. });
  3611. }
  3612. let maximumCompressedSize = 0;
  3613. let maximumEntrySize = 0;
  3614. let uncompressedSize = 0;
  3615. const zip64Enabled = zip64 === true;
  3616. if (reader) {
  3617. reader = initReader(reader);
  3618. await initStream(reader);
  3619. if (reader.size === UNDEFINED_VALUE) {
  3620. dataDescriptor = true;
  3621. if (zip64 || zip64 === UNDEFINED_VALUE) {
  3622. zip64 = true;
  3623. uncompressedSize = maximumCompressedSize = MAX_32_BITS;
  3624. }
  3625. } else {
  3626. uncompressedSize = reader.size;
  3627. maximumCompressedSize = getMaximumCompressedSize(uncompressedSize);
  3628. }
  3629. }
  3630. const { diskOffset, diskNumber, maxSize } = zipWriter.writer;
  3631. const zip64UncompressedSize = zip64Enabled || uncompressedSize >= MAX_32_BITS;
  3632. const zip64CompressedSize = zip64Enabled || maximumCompressedSize >= MAX_32_BITS;
  3633. const zip64Offset = zip64Enabled || zipWriter.offset + zipWriter.pendingEntriesSize - diskOffset >= MAX_32_BITS;
  3634. const supportZip64SplitFile = getOptionValue(zipWriter, options, "supportZip64SplitFile", true);
  3635. const zip64DiskNumberStart = (supportZip64SplitFile && zip64Enabled) || diskNumber + Math$1.ceil(zipWriter.pendingEntriesSize / maxSize) >= MAX_16_BITS;
  3636. if (zip64Offset || zip64UncompressedSize || zip64CompressedSize || zip64DiskNumberStart) {
  3637. if (zip64 === false || !keepOrder) {
  3638. throw new Error(ERR_UNSUPPORTED_FORMAT);
  3639. } else {
  3640. zip64 = true;
  3641. }
  3642. }
  3643. zip64 = zip64 || false;
  3644. options = Object$1.assign({}, options, {
  3645. rawFilename,
  3646. rawComment,
  3647. version,
  3648. versionMadeBy,
  3649. lastModDate,
  3650. lastAccessDate,
  3651. creationDate,
  3652. rawExtraField,
  3653. zip64,
  3654. zip64UncompressedSize,
  3655. zip64CompressedSize,
  3656. zip64Offset,
  3657. zip64DiskNumberStart,
  3658. password,
  3659. level,
  3660. useWebWorkers,
  3661. encryptionStrength,
  3662. extendedTimestamp,
  3663. zipCrypto,
  3664. bufferedWrite,
  3665. keepOrder,
  3666. dataDescriptor,
  3667. dataDescriptorSignature,
  3668. signal,
  3669. msDosCompatible,
  3670. internalFileAttribute,
  3671. externalFileAttribute,
  3672. useCompressionStream
  3673. });
  3674. const headerInfo = getHeaderInfo(options);
  3675. const dataDescriptorInfo = getDataDescriptorInfo(options);
  3676. const metadataSize = getLength(headerInfo.localHeaderArray, dataDescriptorInfo.dataDescriptorArray);
  3677. maximumEntrySize = metadataSize + maximumCompressedSize;
  3678. if (zipWriter.options.usdz) {
  3679. maximumEntrySize += maximumEntrySize + 64;
  3680. }
  3681. zipWriter.pendingEntriesSize += maximumEntrySize;
  3682. let fileEntry;
  3683. try {
  3684. fileEntry = await getFileEntry(zipWriter, name, reader, { headerInfo, dataDescriptorInfo, metadataSize }, options);
  3685. } finally {
  3686. zipWriter.pendingEntriesSize -= maximumEntrySize;
  3687. }
  3688. Object$1.assign(fileEntry, { name, comment, extraField });
  3689. return new Entry(fileEntry);
  3690. }
  3691. async function getFileEntry(zipWriter, name, reader, entryInfo, options) {
  3692. const {
  3693. files,
  3694. writer
  3695. } = zipWriter;
  3696. const {
  3697. keepOrder,
  3698. dataDescriptor,
  3699. signal
  3700. } = options;
  3701. const {
  3702. headerInfo
  3703. } = entryInfo;
  3704. const { usdz } = zipWriter.options;
  3705. const previousFileEntry = Array$1.from(files.values()).pop();
  3706. let fileEntry = {};
  3707. let bufferedWrite;
  3708. let releaseLockWriter;
  3709. let releaseLockCurrentFileEntry;
  3710. let writingBufferedEntryData;
  3711. let writingEntryData;
  3712. let fileWriter;
  3713. files.set(name, fileEntry);
  3714. try {
  3715. let lockPreviousFileEntry;
  3716. if (keepOrder) {
  3717. lockPreviousFileEntry = previousFileEntry && previousFileEntry.lock;
  3718. requestLockCurrentFileEntry();
  3719. }
  3720. if ((options.bufferedWrite || zipWriter.writerLocked || (zipWriter.bufferedWrites && keepOrder) || !dataDescriptor) && !usdz) {
  3721. fileWriter = new BlobWriter();
  3722. fileWriter.writable.size = 0;
  3723. bufferedWrite = true;
  3724. zipWriter.bufferedWrites++;
  3725. await initStream(writer);
  3726. } else {
  3727. fileWriter = writer;
  3728. await requestLockWriter();
  3729. }
  3730. await initStream(fileWriter);
  3731. const { writable } = writer;
  3732. let { diskOffset } = writer;
  3733. if (zipWriter.addSplitZipSignature) {
  3734. delete zipWriter.addSplitZipSignature;
  3735. const signatureArray = new Uint8Array$1(4);
  3736. const signatureArrayView = getDataView(signatureArray);
  3737. setUint32(signatureArrayView, 0, SPLIT_ZIP_FILE_SIGNATURE);
  3738. await writeData(writable, signatureArray);
  3739. zipWriter.offset += 4;
  3740. }
  3741. if (!bufferedWrite) {
  3742. await lockPreviousFileEntry;
  3743. await skipDiskIfNeeded(writable);
  3744. }
  3745. const { diskNumber } = writer;
  3746. writingEntryData = true;
  3747. fileEntry.diskNumberStart = diskNumber;
  3748. if (usdz) {
  3749. appendExtraFieldUSDZ(entryInfo, zipWriter.offset - diskOffset);
  3750. }
  3751. fileEntry = await createFileEntry(reader, fileWriter, fileEntry, entryInfo, zipWriter.config, options);
  3752. writingEntryData = false;
  3753. files.set(name, fileEntry);
  3754. fileEntry.filename = name;
  3755. if (bufferedWrite) {
  3756. await fileWriter.writable.getWriter().close();
  3757. let blob = await fileWriter.getData();
  3758. await lockPreviousFileEntry;
  3759. await requestLockWriter();
  3760. writingBufferedEntryData = true;
  3761. if (!dataDescriptor) {
  3762. blob = await writeExtraHeaderInfo(fileEntry, blob, writable, options);
  3763. }
  3764. await skipDiskIfNeeded(writable);
  3765. fileEntry.diskNumberStart = writer.diskNumber;
  3766. diskOffset = writer.diskOffset;
  3767. await blob.stream().pipeTo(writable, { preventClose: true, preventAbort: true, signal });
  3768. writable.size += blob.size;
  3769. writingBufferedEntryData = false;
  3770. }
  3771. fileEntry.offset = zipWriter.offset - diskOffset;
  3772. if (fileEntry.zip64) {
  3773. setZip64ExtraInfo(fileEntry, options);
  3774. } else if (fileEntry.offset >= MAX_32_BITS) {
  3775. throw new Error(ERR_UNSUPPORTED_FORMAT);
  3776. }
  3777. zipWriter.offset += fileEntry.length;
  3778. return fileEntry;
  3779. } catch (error) {
  3780. if ((bufferedWrite && writingBufferedEntryData) || (!bufferedWrite && writingEntryData)) {
  3781. zipWriter.hasCorruptedEntries = true;
  3782. if (error) {
  3783. try {
  3784. error.corruptedEntry = true;
  3785. } catch (_error) {
  3786. // ignored
  3787. }
  3788. }
  3789. if (bufferedWrite) {
  3790. zipWriter.offset += fileWriter.writable.size;
  3791. } else {
  3792. zipWriter.offset = fileWriter.writable.size;
  3793. }
  3794. }
  3795. files.delete(name);
  3796. throw error;
  3797. } finally {
  3798. if (bufferedWrite) {
  3799. zipWriter.bufferedWrites--;
  3800. }
  3801. if (releaseLockCurrentFileEntry) {
  3802. releaseLockCurrentFileEntry();
  3803. }
  3804. if (releaseLockWriter) {
  3805. releaseLockWriter();
  3806. }
  3807. }
  3808. function requestLockCurrentFileEntry() {
  3809. fileEntry.lock = new Promise$1(resolve => releaseLockCurrentFileEntry = resolve);
  3810. }
  3811. async function requestLockWriter() {
  3812. zipWriter.writerLocked = true;
  3813. const { lockWriter } = zipWriter;
  3814. zipWriter.lockWriter = new Promise$1(resolve => releaseLockWriter = () => {
  3815. zipWriter.writerLocked = false;
  3816. resolve();
  3817. });
  3818. await lockWriter;
  3819. }
  3820. async function skipDiskIfNeeded(writable) {
  3821. if (headerInfo.localHeaderArray.length > writer.availableSize) {
  3822. writer.availableSize = 0;
  3823. await writeData(writable, new Uint8Array$1());
  3824. }
  3825. }
  3826. }
  3827. async function createFileEntry(reader, writer, { diskNumberStart, lock }, entryInfo, config, options) {
  3828. const {
  3829. headerInfo,
  3830. dataDescriptorInfo,
  3831. metadataSize
  3832. } = entryInfo;
  3833. const {
  3834. localHeaderArray,
  3835. headerArray,
  3836. lastModDate,
  3837. rawLastModDate,
  3838. encrypted,
  3839. compressed,
  3840. version,
  3841. compressionMethod,
  3842. rawExtraFieldExtendedTimestamp,
  3843. extraFieldExtendedTimestampFlag,
  3844. rawExtraFieldNTFS,
  3845. rawExtraFieldAES
  3846. } = headerInfo;
  3847. const { dataDescriptorArray } = dataDescriptorInfo;
  3848. const {
  3849. rawFilename,
  3850. lastAccessDate,
  3851. creationDate,
  3852. password,
  3853. level,
  3854. zip64,
  3855. zip64UncompressedSize,
  3856. zip64CompressedSize,
  3857. zip64Offset,
  3858. zip64DiskNumberStart,
  3859. zipCrypto,
  3860. dataDescriptor,
  3861. directory,
  3862. versionMadeBy,
  3863. rawComment,
  3864. rawExtraField,
  3865. useWebWorkers,
  3866. onstart,
  3867. onprogress,
  3868. onend,
  3869. signal,
  3870. encryptionStrength,
  3871. extendedTimestamp,
  3872. msDosCompatible,
  3873. internalFileAttribute,
  3874. externalFileAttribute,
  3875. useCompressionStream
  3876. } = options;
  3877. const fileEntry = {
  3878. lock,
  3879. versionMadeBy,
  3880. zip64,
  3881. directory: Boolean(directory),
  3882. filenameUTF8: true,
  3883. rawFilename,
  3884. commentUTF8: true,
  3885. rawComment,
  3886. rawExtraFieldExtendedTimestamp,
  3887. rawExtraFieldNTFS,
  3888. rawExtraFieldAES,
  3889. rawExtraField,
  3890. extendedTimestamp,
  3891. msDosCompatible,
  3892. internalFileAttribute,
  3893. externalFileAttribute,
  3894. diskNumberStart
  3895. };
  3896. let compressedSize = 0;
  3897. let uncompressedSize = 0;
  3898. let signature;
  3899. const { writable } = writer;
  3900. if (reader) {
  3901. reader.chunkSize = getChunkSize(config);
  3902. await writeData(writable, localHeaderArray);
  3903. const readable = reader.readable;
  3904. const size = readable.size = reader.size;
  3905. const workerOptions = {
  3906. options: {
  3907. codecType: CODEC_DEFLATE,
  3908. level,
  3909. password,
  3910. encryptionStrength,
  3911. zipCrypto: encrypted && zipCrypto,
  3912. passwordVerification: encrypted && zipCrypto && (rawLastModDate >> 8) & 0xFF,
  3913. signed: true,
  3914. compressed,
  3915. encrypted,
  3916. useWebWorkers,
  3917. useCompressionStream,
  3918. transferStreams: false
  3919. },
  3920. config,
  3921. streamOptions: { signal, size, onstart, onprogress, onend }
  3922. };
  3923. const result = await runWorker({ readable, writable }, workerOptions);
  3924. writable.size += result.size;
  3925. signature = result.signature;
  3926. uncompressedSize = reader.size = readable.size;
  3927. compressedSize = result.size;
  3928. } else {
  3929. await writeData(writable, localHeaderArray);
  3930. }
  3931. let rawExtraFieldZip64;
  3932. if (zip64) {
  3933. let rawExtraFieldZip64Length = 4;
  3934. if (zip64UncompressedSize) {
  3935. rawExtraFieldZip64Length += 8;
  3936. }
  3937. if (zip64CompressedSize) {
  3938. rawExtraFieldZip64Length += 8;
  3939. }
  3940. if (zip64Offset) {
  3941. rawExtraFieldZip64Length += 8;
  3942. }
  3943. if (zip64DiskNumberStart) {
  3944. rawExtraFieldZip64Length += 4;
  3945. }
  3946. rawExtraFieldZip64 = new Uint8Array$1(rawExtraFieldZip64Length);
  3947. } else {
  3948. rawExtraFieldZip64 = new Uint8Array$1();
  3949. }
  3950. setEntryInfo({
  3951. signature,
  3952. rawExtraFieldZip64,
  3953. compressedSize,
  3954. uncompressedSize,
  3955. headerInfo,
  3956. dataDescriptorInfo
  3957. }, options);
  3958. if (dataDescriptor) {
  3959. await writeData(writable, dataDescriptorArray);
  3960. }
  3961. Object$1.assign(fileEntry, {
  3962. uncompressedSize,
  3963. compressedSize,
  3964. lastModDate,
  3965. rawLastModDate,
  3966. creationDate,
  3967. lastAccessDate,
  3968. encrypted,
  3969. length: metadataSize + compressedSize,
  3970. compressionMethod,
  3971. version,
  3972. headerArray,
  3973. signature,
  3974. rawExtraFieldZip64,
  3975. extraFieldExtendedTimestampFlag,
  3976. zip64UncompressedSize,
  3977. zip64CompressedSize,
  3978. zip64Offset,
  3979. zip64DiskNumberStart
  3980. });
  3981. return fileEntry;
  3982. }
  3983. function getHeaderInfo(options) {
  3984. const {
  3985. rawFilename,
  3986. lastModDate,
  3987. lastAccessDate,
  3988. creationDate,
  3989. password,
  3990. level,
  3991. zip64,
  3992. zipCrypto,
  3993. dataDescriptor,
  3994. directory,
  3995. rawExtraField,
  3996. encryptionStrength,
  3997. extendedTimestamp
  3998. } = options;
  3999. const compressed = level !== 0 && !directory;
  4000. const encrypted = Boolean(password && getLength(password));
  4001. let version = options.version;
  4002. let rawExtraFieldAES;
  4003. if (encrypted && !zipCrypto) {
  4004. rawExtraFieldAES = new Uint8Array$1(getLength(EXTRAFIELD_DATA_AES) + 2);
  4005. const extraFieldAESView = getDataView(rawExtraFieldAES);
  4006. setUint16(extraFieldAESView, 0, EXTRAFIELD_TYPE_AES);
  4007. arraySet(rawExtraFieldAES, EXTRAFIELD_DATA_AES, 2);
  4008. setUint8(extraFieldAESView, 8, encryptionStrength);
  4009. } else {
  4010. rawExtraFieldAES = new Uint8Array$1();
  4011. }
  4012. let rawExtraFieldNTFS;
  4013. let rawExtraFieldExtendedTimestamp;
  4014. let extraFieldExtendedTimestampFlag;
  4015. if (extendedTimestamp) {
  4016. rawExtraFieldExtendedTimestamp = new Uint8Array$1(9 + (lastAccessDate ? 4 : 0) + (creationDate ? 4 : 0));
  4017. const extraFieldExtendedTimestampView = getDataView(rawExtraFieldExtendedTimestamp);
  4018. setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  4019. setUint16(extraFieldExtendedTimestampView, 2, getLength(rawExtraFieldExtendedTimestamp) - 4);
  4020. extraFieldExtendedTimestampFlag = 0x1 + (lastAccessDate ? 0x2 : 0) + (creationDate ? 0x4 : 0);
  4021. setUint8(extraFieldExtendedTimestampView, 4, extraFieldExtendedTimestampFlag);
  4022. let offset = 5;
  4023. setUint32(extraFieldExtendedTimestampView, offset, Math$1.floor(lastModDate.getTime() / 1000));
  4024. offset += 4;
  4025. if (lastAccessDate) {
  4026. setUint32(extraFieldExtendedTimestampView, offset, Math$1.floor(lastAccessDate.getTime() / 1000));
  4027. offset += 4;
  4028. }
  4029. if (creationDate) {
  4030. setUint32(extraFieldExtendedTimestampView, offset, Math$1.floor(creationDate.getTime() / 1000));
  4031. }
  4032. try {
  4033. rawExtraFieldNTFS = new Uint8Array$1(36);
  4034. const extraFieldNTFSView = getDataView(rawExtraFieldNTFS);
  4035. const lastModTimeNTFS = getTimeNTFS(lastModDate);
  4036. setUint16(extraFieldNTFSView, 0, EXTRAFIELD_TYPE_NTFS);
  4037. setUint16(extraFieldNTFSView, 2, 32);
  4038. setUint16(extraFieldNTFSView, 8, EXTRAFIELD_TYPE_NTFS_TAG1);
  4039. setUint16(extraFieldNTFSView, 10, 24);
  4040. setBigUint64(extraFieldNTFSView, 12, lastModTimeNTFS);
  4041. setBigUint64(extraFieldNTFSView, 20, getTimeNTFS(lastAccessDate) || lastModTimeNTFS);
  4042. setBigUint64(extraFieldNTFSView, 28, getTimeNTFS(creationDate) || lastModTimeNTFS);
  4043. } catch (_error) {
  4044. rawExtraFieldNTFS = new Uint8Array$1();
  4045. }
  4046. } else {
  4047. rawExtraFieldNTFS = rawExtraFieldExtendedTimestamp = new Uint8Array$1();
  4048. }
  4049. let bitFlag = BITFLAG_LANG_ENCODING_FLAG;
  4050. if (dataDescriptor) {
  4051. bitFlag = bitFlag | BITFLAG_DATA_DESCRIPTOR;
  4052. }
  4053. let compressionMethod = COMPRESSION_METHOD_STORE;
  4054. if (compressed) {
  4055. compressionMethod = COMPRESSION_METHOD_DEFLATE;
  4056. }
  4057. if (zip64) {
  4058. version = version > VERSION_ZIP64 ? version : VERSION_ZIP64;
  4059. }
  4060. if (encrypted) {
  4061. bitFlag = bitFlag | BITFLAG_ENCRYPTED;
  4062. if (!zipCrypto) {
  4063. version = version > VERSION_AES ? version : VERSION_AES;
  4064. compressionMethod = COMPRESSION_METHOD_AES;
  4065. if (compressed) {
  4066. rawExtraFieldAES[9] = COMPRESSION_METHOD_DEFLATE;
  4067. }
  4068. }
  4069. }
  4070. const headerArray = new Uint8Array$1(26);
  4071. const headerView = getDataView(headerArray);
  4072. setUint16(headerView, 0, version);
  4073. setUint16(headerView, 2, bitFlag);
  4074. setUint16(headerView, 4, compressionMethod);
  4075. const dateArray = new Uint32Array(1);
  4076. const dateView = getDataView(dateArray);
  4077. let lastModDateMsDos;
  4078. if (lastModDate < MIN_DATE) {
  4079. lastModDateMsDos = MIN_DATE;
  4080. } else if (lastModDate > MAX_DATE) {
  4081. lastModDateMsDos = MAX_DATE;
  4082. } else {
  4083. lastModDateMsDos = lastModDate;
  4084. }
  4085. setUint16(dateView, 0, (((lastModDateMsDos.getHours() << 6) | lastModDateMsDos.getMinutes()) << 5) | lastModDateMsDos.getSeconds() / 2);
  4086. setUint16(dateView, 2, ((((lastModDateMsDos.getFullYear() - 1980) << 4) | (lastModDateMsDos.getMonth() + 1)) << 5) | lastModDateMsDos.getDate());
  4087. const rawLastModDate = dateArray[0];
  4088. setUint32(headerView, 6, rawLastModDate);
  4089. setUint16(headerView, 22, getLength(rawFilename));
  4090. const extraFieldLength = getLength(rawExtraFieldAES, rawExtraFieldExtendedTimestamp, rawExtraFieldNTFS, rawExtraField);
  4091. setUint16(headerView, 24, extraFieldLength);
  4092. const localHeaderArray = new Uint8Array$1(30 + getLength(rawFilename) + extraFieldLength);
  4093. const localHeaderView = getDataView(localHeaderArray);
  4094. setUint32(localHeaderView, 0, LOCAL_FILE_HEADER_SIGNATURE);
  4095. arraySet(localHeaderArray, headerArray, 4);
  4096. arraySet(localHeaderArray, rawFilename, 30);
  4097. arraySet(localHeaderArray, rawExtraFieldAES, 30 + getLength(rawFilename));
  4098. arraySet(localHeaderArray, rawExtraFieldExtendedTimestamp, 30 + getLength(rawFilename, rawExtraFieldAES));
  4099. arraySet(localHeaderArray, rawExtraFieldNTFS, 30 + getLength(rawFilename, rawExtraFieldAES, rawExtraFieldExtendedTimestamp));
  4100. arraySet(localHeaderArray, rawExtraField, 30 + getLength(rawFilename, rawExtraFieldAES, rawExtraFieldExtendedTimestamp, rawExtraFieldNTFS));
  4101. return {
  4102. localHeaderArray,
  4103. headerArray,
  4104. headerView,
  4105. lastModDate,
  4106. rawLastModDate,
  4107. encrypted,
  4108. compressed,
  4109. version,
  4110. compressionMethod,
  4111. extraFieldExtendedTimestampFlag,
  4112. rawExtraFieldExtendedTimestamp,
  4113. rawExtraFieldNTFS,
  4114. rawExtraFieldAES,
  4115. extraFieldLength
  4116. };
  4117. }
  4118. function appendExtraFieldUSDZ(entryInfo, zipWriterOffset) {
  4119. const { headerInfo } = entryInfo;
  4120. let { localHeaderArray, extraFieldLength } = headerInfo;
  4121. let localHeaderArrayView = getDataView(localHeaderArray);
  4122. let extraBytesLength = 64 - ((zipWriterOffset + localHeaderArray.length) % 64);
  4123. if (extraBytesLength < 4) {
  4124. extraBytesLength += 64;
  4125. }
  4126. const rawExtraFieldUSDZ = new Uint8Array$1(extraBytesLength);
  4127. const extraFieldUSDZView = getDataView(rawExtraFieldUSDZ);
  4128. setUint16(extraFieldUSDZView, 0, EXTRAFIELD_TYPE_USDZ);
  4129. setUint16(extraFieldUSDZView, 2, extraBytesLength - 2);
  4130. const previousLocalHeaderArray = localHeaderArray;
  4131. headerInfo.localHeaderArray = localHeaderArray = new Uint8Array$1(previousLocalHeaderArray.length + extraBytesLength);
  4132. arraySet(localHeaderArray, previousLocalHeaderArray);
  4133. arraySet(localHeaderArray, rawExtraFieldUSDZ, previousLocalHeaderArray.length);
  4134. localHeaderArrayView = getDataView(localHeaderArray);
  4135. setUint16(localHeaderArrayView, 28, extraFieldLength + extraBytesLength);
  4136. entryInfo.metadataSize += extraBytesLength;
  4137. }
  4138. function getDataDescriptorInfo(options) {
  4139. const {
  4140. zip64,
  4141. dataDescriptor,
  4142. dataDescriptorSignature
  4143. } = options;
  4144. let dataDescriptorArray = new Uint8Array$1();
  4145. let dataDescriptorView, dataDescriptorOffset = 0;
  4146. if (dataDescriptor) {
  4147. dataDescriptorArray = new Uint8Array$1(zip64 ? (dataDescriptorSignature ? 24 : 20) : (dataDescriptorSignature ? 16 : 12));
  4148. dataDescriptorView = getDataView(dataDescriptorArray);
  4149. if (dataDescriptorSignature) {
  4150. dataDescriptorOffset = 4;
  4151. setUint32(dataDescriptorView, 0, DATA_DESCRIPTOR_RECORD_SIGNATURE);
  4152. }
  4153. }
  4154. return {
  4155. dataDescriptorArray,
  4156. dataDescriptorView,
  4157. dataDescriptorOffset
  4158. };
  4159. }
  4160. function setEntryInfo(entryInfo, options) {
  4161. const {
  4162. signature,
  4163. rawExtraFieldZip64,
  4164. compressedSize,
  4165. uncompressedSize,
  4166. headerInfo,
  4167. dataDescriptorInfo
  4168. } = entryInfo;
  4169. const {
  4170. headerView,
  4171. encrypted
  4172. } = headerInfo;
  4173. const {
  4174. dataDescriptorView,
  4175. dataDescriptorOffset
  4176. } = dataDescriptorInfo;
  4177. const {
  4178. zip64,
  4179. zip64UncompressedSize,
  4180. zip64CompressedSize,
  4181. zipCrypto,
  4182. dataDescriptor
  4183. } = options;
  4184. if ((!encrypted || zipCrypto) && signature !== UNDEFINED_VALUE) {
  4185. setUint32(headerView, 10, signature);
  4186. if (dataDescriptor) {
  4187. setUint32(dataDescriptorView, dataDescriptorOffset, signature);
  4188. }
  4189. }
  4190. if (zip64) {
  4191. const rawExtraFieldZip64View = getDataView(rawExtraFieldZip64);
  4192. setUint16(rawExtraFieldZip64View, 0, EXTRAFIELD_TYPE_ZIP64);
  4193. setUint16(rawExtraFieldZip64View, 2, rawExtraFieldZip64.length - 4);
  4194. let rawExtraFieldZip64Offset = 4;
  4195. if (zip64UncompressedSize) {
  4196. setUint32(headerView, 18, MAX_32_BITS);
  4197. setBigUint64(rawExtraFieldZip64View, rawExtraFieldZip64Offset, BigInt(uncompressedSize));
  4198. rawExtraFieldZip64Offset += 8;
  4199. }
  4200. if (zip64CompressedSize) {
  4201. setUint32(headerView, 14, MAX_32_BITS);
  4202. setBigUint64(rawExtraFieldZip64View, rawExtraFieldZip64Offset, BigInt(compressedSize));
  4203. }
  4204. if (dataDescriptor) {
  4205. setBigUint64(dataDescriptorView, dataDescriptorOffset + 4, BigInt(compressedSize));
  4206. setBigUint64(dataDescriptorView, dataDescriptorOffset + 12, BigInt(uncompressedSize));
  4207. }
  4208. } else {
  4209. setUint32(headerView, 14, compressedSize);
  4210. setUint32(headerView, 18, uncompressedSize);
  4211. if (dataDescriptor) {
  4212. setUint32(dataDescriptorView, dataDescriptorOffset + 4, compressedSize);
  4213. setUint32(dataDescriptorView, dataDescriptorOffset + 8, uncompressedSize);
  4214. }
  4215. }
  4216. }
  4217. async function writeExtraHeaderInfo(fileEntry, entryData, writable, { zipCrypto }) {
  4218. let arrayBuffer;
  4219. arrayBuffer = await entryData.slice(0, 26).arrayBuffer();
  4220. if (arrayBuffer.byteLength != 26) {
  4221. arrayBuffer = arrayBuffer.slice(0, 26);
  4222. }
  4223. const arrayBufferView = new DataView(arrayBuffer);
  4224. if (!fileEntry.encrypted || zipCrypto) {
  4225. setUint32(arrayBufferView, 14, fileEntry.signature);
  4226. }
  4227. if (fileEntry.zip64) {
  4228. setUint32(arrayBufferView, 18, MAX_32_BITS);
  4229. setUint32(arrayBufferView, 22, MAX_32_BITS);
  4230. } else {
  4231. setUint32(arrayBufferView, 18, fileEntry.compressedSize);
  4232. setUint32(arrayBufferView, 22, fileEntry.uncompressedSize);
  4233. }
  4234. await writeData(writable, new Uint8Array$1(arrayBuffer));
  4235. return entryData.slice(arrayBuffer.byteLength);
  4236. }
  4237. function setZip64ExtraInfo(fileEntry, options) {
  4238. const { rawExtraFieldZip64, offset, diskNumberStart } = fileEntry;
  4239. const { zip64UncompressedSize, zip64CompressedSize, zip64Offset, zip64DiskNumberStart } = options;
  4240. const rawExtraFieldZip64View = getDataView(rawExtraFieldZip64);
  4241. let rawExtraFieldZip64Offset = 4;
  4242. if (zip64UncompressedSize) {
  4243. rawExtraFieldZip64Offset += 8;
  4244. }
  4245. if (zip64CompressedSize) {
  4246. rawExtraFieldZip64Offset += 8;
  4247. }
  4248. if (zip64Offset) {
  4249. setBigUint64(rawExtraFieldZip64View, rawExtraFieldZip64Offset, BigInt(offset));
  4250. rawExtraFieldZip64Offset += 8;
  4251. }
  4252. if (zip64DiskNumberStart) {
  4253. setUint32(rawExtraFieldZip64View, rawExtraFieldZip64Offset, diskNumberStart);
  4254. }
  4255. }
  4256. async function closeFile(zipWriter, comment, options) {
  4257. const { files, writer } = zipWriter;
  4258. const { diskOffset, writable } = writer;
  4259. let { diskNumber } = writer;
  4260. let offset = 0;
  4261. let directoryDataLength = 0;
  4262. let directoryOffset = zipWriter.offset - diskOffset;
  4263. let filesLength = files.size;
  4264. for (const [, fileEntry] of files) {
  4265. const {
  4266. rawFilename,
  4267. rawExtraFieldZip64,
  4268. rawExtraFieldAES,
  4269. rawComment,
  4270. rawExtraFieldNTFS,
  4271. rawExtraField,
  4272. extendedTimestamp,
  4273. extraFieldExtendedTimestampFlag,
  4274. lastModDate
  4275. } = fileEntry;
  4276. let rawExtraFieldTimestamp;
  4277. if (extendedTimestamp) {
  4278. rawExtraFieldTimestamp = new Uint8Array$1(9);
  4279. const extraFieldExtendedTimestampView = getDataView(rawExtraFieldTimestamp);
  4280. setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  4281. setUint16(extraFieldExtendedTimestampView, 2, 5);
  4282. setUint8(extraFieldExtendedTimestampView, 4, extraFieldExtendedTimestampFlag);
  4283. setUint32(extraFieldExtendedTimestampView, 5, Math$1.floor(lastModDate.getTime() / 1000));
  4284. } else {
  4285. rawExtraFieldTimestamp = new Uint8Array$1();
  4286. }
  4287. fileEntry.rawExtraFieldCDExtendedTimestamp = rawExtraFieldTimestamp;
  4288. directoryDataLength += 46 +
  4289. getLength(
  4290. rawFilename,
  4291. rawComment,
  4292. rawExtraFieldZip64,
  4293. rawExtraFieldAES,
  4294. rawExtraFieldNTFS,
  4295. rawExtraFieldTimestamp,
  4296. rawExtraField);
  4297. }
  4298. const directoryArray = new Uint8Array$1(directoryDataLength);
  4299. const directoryView = getDataView(directoryArray);
  4300. await initStream(writer);
  4301. let directoryDiskOffset = 0;
  4302. for (const [indexFileEntry, fileEntry] of Array$1.from(files.values()).entries()) {
  4303. const {
  4304. offset: fileEntryOffset,
  4305. rawFilename,
  4306. rawExtraFieldZip64,
  4307. rawExtraFieldAES,
  4308. rawExtraFieldCDExtendedTimestamp,
  4309. rawExtraFieldNTFS,
  4310. rawExtraField,
  4311. rawComment,
  4312. versionMadeBy,
  4313. headerArray,
  4314. directory,
  4315. zip64,
  4316. zip64UncompressedSize,
  4317. zip64CompressedSize,
  4318. zip64DiskNumberStart,
  4319. zip64Offset,
  4320. msDosCompatible,
  4321. internalFileAttribute,
  4322. externalFileAttribute,
  4323. diskNumberStart,
  4324. uncompressedSize,
  4325. compressedSize
  4326. } = fileEntry;
  4327. const extraFieldLength = getLength(rawExtraFieldZip64, rawExtraFieldAES, rawExtraFieldCDExtendedTimestamp, rawExtraFieldNTFS, rawExtraField);
  4328. setUint32(directoryView, offset, CENTRAL_FILE_HEADER_SIGNATURE);
  4329. setUint16(directoryView, offset + 4, versionMadeBy);
  4330. const headerView = getDataView(headerArray);
  4331. if (!zip64UncompressedSize) {
  4332. setUint32(headerView, 18, uncompressedSize);
  4333. }
  4334. if (!zip64CompressedSize) {
  4335. setUint32(headerView, 14, compressedSize);
  4336. }
  4337. arraySet(directoryArray, headerArray, offset + 6);
  4338. setUint16(directoryView, offset + 30, extraFieldLength);
  4339. setUint16(directoryView, offset + 32, getLength(rawComment));
  4340. setUint16(directoryView, offset + 34, zip64 && zip64DiskNumberStart ? MAX_16_BITS : diskNumberStart);
  4341. setUint16(directoryView, offset + 36, internalFileAttribute);
  4342. if (externalFileAttribute) {
  4343. setUint32(directoryView, offset + 38, externalFileAttribute);
  4344. } else if (directory && msDosCompatible) {
  4345. setUint8(directoryView, offset + 38, FILE_ATTR_MSDOS_DIR_MASK);
  4346. }
  4347. setUint32(directoryView, offset + 42, zip64 && zip64Offset ? MAX_32_BITS : fileEntryOffset);
  4348. arraySet(directoryArray, rawFilename, offset + 46);
  4349. arraySet(directoryArray, rawExtraFieldZip64, offset + 46 + getLength(rawFilename));
  4350. arraySet(directoryArray, rawExtraFieldAES, offset + 46 + getLength(rawFilename, rawExtraFieldZip64));
  4351. arraySet(directoryArray, rawExtraFieldCDExtendedTimestamp, offset + 46 + getLength(rawFilename, rawExtraFieldZip64, rawExtraFieldAES));
  4352. arraySet(directoryArray, rawExtraFieldNTFS, offset + 46 + getLength(rawFilename, rawExtraFieldZip64, rawExtraFieldAES, rawExtraFieldCDExtendedTimestamp));
  4353. arraySet(directoryArray, rawExtraField, offset + 46 + getLength(rawFilename, rawExtraFieldZip64, rawExtraFieldAES, rawExtraFieldCDExtendedTimestamp, rawExtraFieldNTFS));
  4354. arraySet(directoryArray, rawComment, offset + 46 + getLength(rawFilename) + extraFieldLength);
  4355. const directoryEntryLength = 46 + getLength(rawFilename, rawComment) + extraFieldLength;
  4356. if (offset - directoryDiskOffset > writer.availableSize) {
  4357. writer.availableSize = 0;
  4358. await writeData(writable, directoryArray.slice(directoryDiskOffset, offset));
  4359. directoryDiskOffset = offset;
  4360. }
  4361. offset += directoryEntryLength;
  4362. if (options.onprogress) {
  4363. try {
  4364. await options.onprogress(indexFileEntry + 1, files.size, new Entry(fileEntry));
  4365. } catch (_error) {
  4366. // ignored
  4367. }
  4368. }
  4369. }
  4370. await writeData(writable, directoryDiskOffset ? directoryArray.slice(directoryDiskOffset) : directoryArray);
  4371. let lastDiskNumber = writer.diskNumber;
  4372. const { availableSize } = writer;
  4373. if (availableSize < END_OF_CENTRAL_DIR_LENGTH) {
  4374. lastDiskNumber++;
  4375. }
  4376. let zip64 = getOptionValue(zipWriter, options, "zip64");
  4377. if (directoryOffset >= MAX_32_BITS || directoryDataLength >= MAX_32_BITS || filesLength >= MAX_16_BITS || lastDiskNumber >= MAX_16_BITS) {
  4378. if (zip64 === false) {
  4379. throw new Error(ERR_UNSUPPORTED_FORMAT);
  4380. } else {
  4381. zip64 = true;
  4382. }
  4383. }
  4384. const endOfdirectoryArray = new Uint8Array$1(zip64 ? ZIP64_END_OF_CENTRAL_DIR_TOTAL_LENGTH : END_OF_CENTRAL_DIR_LENGTH);
  4385. const endOfdirectoryView = getDataView(endOfdirectoryArray);
  4386. offset = 0;
  4387. if (zip64) {
  4388. setUint32(endOfdirectoryView, 0, ZIP64_END_OF_CENTRAL_DIR_SIGNATURE);
  4389. setBigUint64(endOfdirectoryView, 4, BigInt(44));
  4390. setUint16(endOfdirectoryView, 12, 45);
  4391. setUint16(endOfdirectoryView, 14, 45);
  4392. setUint32(endOfdirectoryView, 16, lastDiskNumber);
  4393. setUint32(endOfdirectoryView, 20, diskNumber);
  4394. setBigUint64(endOfdirectoryView, 24, BigInt(filesLength));
  4395. setBigUint64(endOfdirectoryView, 32, BigInt(filesLength));
  4396. setBigUint64(endOfdirectoryView, 40, BigInt(directoryDataLength));
  4397. setBigUint64(endOfdirectoryView, 48, BigInt(directoryOffset));
  4398. setUint32(endOfdirectoryView, 56, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE);
  4399. setBigUint64(endOfdirectoryView, 64, BigInt(directoryOffset) + BigInt(directoryDataLength));
  4400. setUint32(endOfdirectoryView, 72, lastDiskNumber + 1);
  4401. const supportZip64SplitFile = getOptionValue(zipWriter, options, "supportZip64SplitFile", true);
  4402. if (supportZip64SplitFile) {
  4403. lastDiskNumber = MAX_16_BITS;
  4404. diskNumber = MAX_16_BITS;
  4405. }
  4406. filesLength = MAX_16_BITS;
  4407. directoryOffset = MAX_32_BITS;
  4408. directoryDataLength = MAX_32_BITS;
  4409. offset += ZIP64_END_OF_CENTRAL_DIR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH;
  4410. }
  4411. setUint32(endOfdirectoryView, offset, END_OF_CENTRAL_DIR_SIGNATURE);
  4412. setUint16(endOfdirectoryView, offset + 4, lastDiskNumber);
  4413. setUint16(endOfdirectoryView, offset + 6, diskNumber);
  4414. setUint16(endOfdirectoryView, offset + 8, filesLength);
  4415. setUint16(endOfdirectoryView, offset + 10, filesLength);
  4416. setUint32(endOfdirectoryView, offset + 12, directoryDataLength);
  4417. setUint32(endOfdirectoryView, offset + 16, directoryOffset);
  4418. const commentLength = getLength(comment);
  4419. if (commentLength) {
  4420. if (commentLength <= MAX_16_BITS) {
  4421. setUint16(endOfdirectoryView, offset + 20, commentLength);
  4422. } else {
  4423. throw new Error(ERR_INVALID_COMMENT);
  4424. }
  4425. }
  4426. await writeData(writable, endOfdirectoryArray);
  4427. if (commentLength) {
  4428. await writeData(writable, comment);
  4429. }
  4430. }
  4431. async function writeData(writable, array) {
  4432. const streamWriter = writable.getWriter();
  4433. await streamWriter.ready;
  4434. writable.size += getLength(array);
  4435. await streamWriter.write(array);
  4436. streamWriter.releaseLock();
  4437. }
  4438. function getTimeNTFS(date) {
  4439. if (date) {
  4440. return ((BigInt(date.getTime()) + BigInt(11644473600000)) * BigInt(10000));
  4441. }
  4442. }
  4443. function getOptionValue(zipWriter, options, name, defaultValue) {
  4444. const result = options[name] === UNDEFINED_VALUE ? zipWriter.options[name] : options[name];
  4445. return result === UNDEFINED_VALUE ? defaultValue : result;
  4446. }
  4447. function getMaximumCompressedSize(uncompressedSize) {
  4448. return uncompressedSize + (5 * (Math$1.floor(uncompressedSize / 16383) + 1));
  4449. }
  4450. function setUint8(view, offset, value) {
  4451. view.setUint8(offset, value);
  4452. }
  4453. function setUint16(view, offset, value) {
  4454. view.setUint16(offset, value, true);
  4455. }
  4456. function setUint32(view, offset, value) {
  4457. view.setUint32(offset, value, true);
  4458. }
  4459. function setBigUint64(view, offset, value) {
  4460. view.setBigUint64(offset, value, true);
  4461. }
  4462. function arraySet(array, typedArray, offset) {
  4463. array.set(typedArray, offset);
  4464. }
  4465. function getDataView(array) {
  4466. return new DataView(array.buffer);
  4467. }
  4468. function getLength(...arrayLikes) {
  4469. let result = 0;
  4470. arrayLikes.forEach(arrayLike => arrayLike && (result += arrayLike.length));
  4471. return result;
  4472. }
  4473. /*
  4474. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  4475. Redistribution and use in source and binary forms, with or without
  4476. modification, are permitted provided that the following conditions are met:
  4477. 1. Redistributions of source code must retain the above copyright notice,
  4478. this list of conditions and the following disclaimer.
  4479. 2. Redistributions in binary form must reproduce the above copyright
  4480. notice, this list of conditions and the following disclaimer in
  4481. the documentation and/or other materials provided with the distribution.
  4482. 3. The names of the authors may not be used to endorse or promote products
  4483. derived from this software without specific prior written permission.
  4484. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  4485. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  4486. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  4487. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  4488. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4489. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  4490. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  4491. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  4492. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  4493. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4494. */
  4495. let baseURL;
  4496. try {
  4497. baseURL = (document.currentScript && document.currentScript.src || new URL('single-file-extension-editor.js', document.baseURI).href);
  4498. } catch (_error) {
  4499. // ignored
  4500. }
  4501. configure({ baseURL });
  4502. e(configure);
  4503. var zip$1 = /*#__PURE__*/Object.freeze({
  4504. __proto__: null,
  4505. BlobReader: BlobReader,
  4506. BlobWriter: BlobWriter,
  4507. Data64URIReader: Data64URIReader,
  4508. Data64URIWriter: Data64URIWriter,
  4509. ERR_BAD_FORMAT: ERR_BAD_FORMAT,
  4510. ERR_CENTRAL_DIRECTORY_NOT_FOUND: ERR_CENTRAL_DIRECTORY_NOT_FOUND,
  4511. ERR_DUPLICATED_NAME: ERR_DUPLICATED_NAME,
  4512. ERR_ENCRYPTED: ERR_ENCRYPTED,
  4513. ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND: ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND,
  4514. ERR_EOCDR_NOT_FOUND: ERR_EOCDR_NOT_FOUND,
  4515. ERR_EOCDR_ZIP64_NOT_FOUND: ERR_EOCDR_ZIP64_NOT_FOUND,
  4516. ERR_EXTRAFIELD_ZIP64_NOT_FOUND: ERR_EXTRAFIELD_ZIP64_NOT_FOUND,
  4517. ERR_HTTP_RANGE: ERR_HTTP_RANGE,
  4518. ERR_INVALID_COMMENT: ERR_INVALID_COMMENT,
  4519. ERR_INVALID_ENCRYPTION_STRENGTH: ERR_INVALID_ENCRYPTION_STRENGTH,
  4520. ERR_INVALID_ENTRY_COMMENT: ERR_INVALID_ENTRY_COMMENT,
  4521. ERR_INVALID_ENTRY_NAME: ERR_INVALID_ENTRY_NAME,
  4522. ERR_INVALID_EXTRAFIELD_DATA: ERR_INVALID_EXTRAFIELD_DATA,
  4523. ERR_INVALID_EXTRAFIELD_TYPE: ERR_INVALID_EXTRAFIELD_TYPE,
  4524. ERR_INVALID_PASSWORD: ERR_INVALID_PASSWORD,
  4525. ERR_INVALID_SIGNATURE: ERR_INVALID_SIGNATURE,
  4526. ERR_INVALID_VERSION: ERR_INVALID_VERSION,
  4527. ERR_ITERATOR_COMPLETED_TOO_SOON: ERR_ITERATOR_COMPLETED_TOO_SOON,
  4528. ERR_LOCAL_FILE_HEADER_NOT_FOUND: ERR_LOCAL_FILE_HEADER_NOT_FOUND,
  4529. ERR_SPLIT_ZIP_FILE: ERR_SPLIT_ZIP_FILE,
  4530. ERR_UNSUPPORTED_COMPRESSION: ERR_UNSUPPORTED_COMPRESSION,
  4531. ERR_UNSUPPORTED_ENCRYPTION: ERR_UNSUPPORTED_ENCRYPTION,
  4532. ERR_UNSUPPORTED_FORMAT: ERR_UNSUPPORTED_FORMAT,
  4533. HttpRangeReader: HttpRangeReader,
  4534. HttpReader: HttpReader,
  4535. Reader: Reader,
  4536. SplitDataReader: SplitDataReader,
  4537. SplitDataWriter: SplitDataWriter,
  4538. SplitZipReader: SplitZipReader,
  4539. SplitZipWriter: SplitZipWriter,
  4540. TextReader: TextReader,
  4541. TextWriter: TextWriter,
  4542. Uint8ArrayReader: Uint8ArrayReader,
  4543. Uint8ArrayWriter: Uint8ArrayWriter,
  4544. Writer: Writer,
  4545. ZipReader: ZipReader,
  4546. ZipWriter: ZipWriter,
  4547. configure: configure,
  4548. getMimeType: getMimeType,
  4549. initReader: initReader,
  4550. initShimAsyncCodec: initShimAsyncCodec,
  4551. initStream: initStream,
  4552. initWriter: initWriter,
  4553. readUint8Array: readUint8Array,
  4554. terminateWorkers: terminateWorkers
  4555. });
  4556. /*
  4557. * Copyright 2010-2022 Gildas Lormeau
  4558. * contact : gildas.lormeau <at> gmail.com
  4559. *
  4560. * This file is part of SingleFile.
  4561. *
  4562. * The code in this file is free software: you can redistribute it and/or
  4563. * modify it under the terms of the GNU Affero General Public License
  4564. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  4565. * of the License, or (at your option) any later version.
  4566. *
  4567. * The code in this file is distributed in the hope that it will be useful,
  4568. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  4569. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  4570. * General Public License for more details.
  4571. *
  4572. * As additional permission under GNU AGPL version 3 section 7, you may
  4573. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  4574. * AGPL normally required by section 4, provided you include this license
  4575. * notice and a URL through which recipients can access the Corresponding
  4576. * Source.
  4577. */
  4578. async function extract(content, { password, prompt = () => { }, shadowRootScriptURL, zipOptions = { useWebWorkers: false }, noBlobURL } = {}) {
  4579. const KNOWN_MIMETYPES = {
  4580. "gif": "image/gif",
  4581. "jpg": "image/jpeg",
  4582. "png": "image/png",
  4583. "tif": "image/tiff",
  4584. "tiff": "image/tiff",
  4585. "bmp": "image/bmp",
  4586. "ico": "image/vnd.microsoft.icon",
  4587. "webp": "image/webp",
  4588. "svg": "image/svg+xml",
  4589. "avi": "video/x-msvideo",
  4590. "ogv": "video/ogg",
  4591. "mp4": "video/mp4",
  4592. "mpeg": "video/mpeg",
  4593. "ts": "video/mp2t",
  4594. "webm": "video/webm",
  4595. "3gp": "video/3gpp",
  4596. "3g2": "video/3gpp",
  4597. "mp3": "audio/mpeg",
  4598. "oga": "audio/ogg",
  4599. "mid": "audio/midi",
  4600. "midi": "audio/midi",
  4601. "opus": "audio/opus",
  4602. "wav": "audio/wav",
  4603. "weba": "audio/webm"
  4604. };
  4605. const REGEXP_MATCH_STYLESHEET = /stylesheet_[0-9]+\.css/;
  4606. const REGEXP_MATCH_SCRIPT = /scripts\/[0-9]+\.js/;
  4607. const REGEXP_MATCH_ROOT_INDEX = /^([0-9_]+\/)?index\.html$/;
  4608. const REGEXP_MATCH_INDEX = /index\.html$/;
  4609. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  4610. const CHARSET_UTF8 = ";charset=utf-8";
  4611. if (Array.isArray(content)) {
  4612. content = new Blob([new Uint8Array(content)]);
  4613. }
  4614. zip.configure(zipOptions);
  4615. const blobReader = new zip.BlobReader(content);
  4616. const zipReader = new zip.ZipReader(blobReader);
  4617. const entries = await zipReader.getEntries();
  4618. const options = { password };
  4619. let docContent, origDocContent, url, resources = [];
  4620. await Promise.all(entries.map(async entry => {
  4621. const { filename } = entry;
  4622. let dataWriter, content, textContent, mimeType;
  4623. if (!options.password && entry.encrypted) {
  4624. options.password = prompt("Please enter the password to view the page");
  4625. }
  4626. if (filename.match(REGEXP_MATCH_INDEX) || filename.match(REGEXP_MATCH_STYLESHEET) || filename.match(REGEXP_MATCH_SCRIPT)) {
  4627. dataWriter = new zip.TextWriter();
  4628. textContent = await entry.getData(dataWriter, options);
  4629. if (filename.match(REGEXP_MATCH_INDEX)) {
  4630. mimeType = "text/html" + CHARSET_UTF8;
  4631. } else {
  4632. if (filename.match(REGEXP_MATCH_STYLESHEET)) {
  4633. mimeType = "text/css" + CHARSET_UTF8;
  4634. } else if (filename.match(REGEXP_MATCH_SCRIPT)) {
  4635. mimeType = "text/javascript" + CHARSET_UTF8;
  4636. }
  4637. if (textContent !== undefined) {
  4638. content = await getDataURI(textContent, mimeType);
  4639. } else {
  4640. content = "data:text/plain,";
  4641. }
  4642. }
  4643. } else {
  4644. const extension = filename.match(/\.([^.]+)/);
  4645. if (extension && extension[1] && KNOWN_MIMETYPES[extension[1]]) {
  4646. mimeType = KNOWN_MIMETYPES[extension[1]];
  4647. } else {
  4648. mimeType = "application/octet-stream";
  4649. }
  4650. if (filename.match(/frames\//) || noBlobURL) {
  4651. content = await entry.getData(new zip.Data64URIWriter(mimeType), options);
  4652. } else {
  4653. const blob = await entry.getData(new zip.BlobWriter(mimeType), options);
  4654. content = URL.createObjectURL(blob);
  4655. }
  4656. }
  4657. const name = entry.filename.match(/^([0-9_]+\/)?(.*)$/)[2];
  4658. resources.push({ filename: entry.filename, name, url: entry.comment, content, mimeType, textContent, parentResources: [] });
  4659. }));
  4660. await zipReader.close();
  4661. resources = resources.sort((resourceLeft, resourceRight) => resourceRight.filename.length - resourceLeft.filename.length);
  4662. for (const resource of resources) {
  4663. let { textContent, mimeType, filename } = resource;
  4664. if (textContent !== undefined) {
  4665. let prefixPath = "";
  4666. const prefixPathMatch = filename.match(/(.*\/)[^/]+$/);
  4667. if (prefixPathMatch && prefixPathMatch[1]) {
  4668. prefixPath = prefixPathMatch[1];
  4669. }
  4670. if (filename.match(REGEXP_MATCH_ROOT_INDEX)) {
  4671. origDocContent = textContent;
  4672. }
  4673. if (!filename.match(REGEXP_MATCH_SCRIPT)) {
  4674. const resourceFilename = filename;
  4675. await Promise.all(resources.map(async innerResource => {
  4676. const { filename, parentResources, content } = innerResource;
  4677. if (filename.startsWith(prefixPath) && filename != resourceFilename) {
  4678. const relativeFilename = filename.substring(prefixPath.length);
  4679. if (!relativeFilename.match(/manifest\.json$/)) {
  4680. const searchRegExp = new RegExp(relativeFilename.replace(REGEXP_ESCAPE, "\\$1"), "g");
  4681. const position = textContent.search(searchRegExp);
  4682. if (position != -1) {
  4683. parentResources.push(resourceFilename);
  4684. textContent = textContent.replace(searchRegExp, content);
  4685. }
  4686. }
  4687. }
  4688. }));
  4689. resource.content = await getDataURI(textContent, mimeType);
  4690. resource.textContent = textContent;
  4691. }
  4692. if (filename.match(REGEXP_MATCH_INDEX)) {
  4693. if (shadowRootScriptURL) {
  4694. resource.textContent = textContent.replace(/<script data-template-shadow-root.*<\/script>/g, "<script data-template-shadow-root src=" + shadowRootScriptURL + "></" + "script>");
  4695. }
  4696. }
  4697. if (filename.match(REGEXP_MATCH_ROOT_INDEX)) {
  4698. docContent = textContent;
  4699. url = resource.url;
  4700. }
  4701. }
  4702. }
  4703. return { docContent, origDocContent, resources, url };
  4704. async function getDataURI(textContent, mimeType) {
  4705. const reader = new FileReader();
  4706. reader.readAsDataURL(new Blob([textContent], { type: mimeType }));
  4707. return new Promise((resolve, reject) => {
  4708. reader.onload = () => resolve(reader.result);
  4709. reader.onerror = reject;
  4710. });
  4711. }
  4712. }
  4713. /*
  4714. * Copyright 2010-2022 Gildas Lormeau
  4715. * contact : gildas.lormeau <at> gmail.com
  4716. *
  4717. * This file is part of SingleFile.
  4718. *
  4719. * The code in this file is free software: you can redistribute it and/or
  4720. * modify it under the terms of the GNU Affero General Public License
  4721. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  4722. * of the License, or (at your option) any later version.
  4723. *
  4724. * The code in this file is distributed in the hope that it will be useful,
  4725. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  4726. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  4727. * General Public License for more details.
  4728. *
  4729. * As additional permission under GNU AGPL version 3 section 7, you may
  4730. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  4731. * AGPL normally required by section 4, provided you include this license
  4732. * notice and a URL through which recipients can access the Corresponding
  4733. * Source.
  4734. */
  4735. async function display(document, docContent, { disableFramePointerEvents } = {}) {
  4736. const DISABLED_NOSCRIPT_ATTRIBUTE_NAME = "data-single-file-disabled-noscript";
  4737. const doc = (new DOMParser()).parseFromString(docContent, "text/html");
  4738. doc.querySelectorAll("noscript:not([" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "])").forEach(element => {
  4739. element.setAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME, element.innerHTML);
  4740. element.textContent = "";
  4741. });
  4742. if (doc.doctype) {
  4743. if (document.doctype) {
  4744. document.replaceChild(doc.doctype, document.doctype);
  4745. } else {
  4746. document.insertBefore(doc.doctype, document.documentElement);
  4747. }
  4748. } else if (document.doctype) {
  4749. document.doctype.remove();
  4750. }
  4751. if (disableFramePointerEvents) {
  4752. doc.querySelectorAll("iframe").forEach(element => {
  4753. const pointerEvents = "pointer-events";
  4754. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  4755. element.style.setProperty(pointerEvents, "none", "important");
  4756. });
  4757. }
  4758. document.replaceChild(document.importNode(doc.documentElement, true), document.documentElement);
  4759. document.querySelectorAll("[" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "]").forEach(element => {
  4760. element.textContent = element.getAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  4761. element.removeAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  4762. });
  4763. document.documentElement.setAttribute("data-sfz", "");
  4764. document.querySelectorAll("link[rel*=icon]").forEach(element => element.parentElement.replaceChild(element, element));
  4765. document.open = document.write = document.close = () => { };
  4766. for (let element of Array.from(document.querySelectorAll("script"))) {
  4767. await new Promise(resolve => {
  4768. const scriptElement = document.createElement("script");
  4769. Array.from(element.attributes).forEach(attribute => scriptElement.setAttribute(attribute.name, attribute.value));
  4770. const async = element.getAttribute("async") == "" || element.getAttribute("async") == "async";
  4771. if (element.textContent) {
  4772. scriptElement.textContent = element.textContent;
  4773. } else if (!async) {
  4774. scriptElement.addEventListener("load", resolve);
  4775. scriptElement.addEventListener("error", () => resolve());
  4776. }
  4777. element.parentElement.replaceChild(scriptElement, element);
  4778. if (element.textContent || async) {
  4779. resolve();
  4780. }
  4781. });
  4782. }
  4783. }
  4784. /*
  4785. * Copyright 2010-2020 Gildas Lormeau
  4786. * contact : gildas.lormeau <at> gmail.com
  4787. *
  4788. * This file is part of SingleFile.
  4789. *
  4790. * The code in this file is free software: you can redistribute it and/or
  4791. * modify it under the terms of the GNU Affero General Public License
  4792. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  4793. * of the License, or (at your option) any later version.
  4794. *
  4795. * The code in this file is distributed in the hope that it will be useful,
  4796. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  4797. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  4798. * General Public License for more details.
  4799. *
  4800. * As additional permission under GNU AGPL version 3 section 7, you may
  4801. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  4802. * AGPL normally required by section 4, provided you include this license
  4803. * notice and a URL through which recipients can access the Corresponding
  4804. * Source.
  4805. */
  4806. (globalThis => {
  4807. const IS_NOT_SAFARI = !/Safari/.test(navigator.userAgent) || /Chrome/.test(navigator.userAgent) || /Vivaldi/.test(navigator.userAgent) || /OPR/.test(navigator.userAgent);
  4808. const singlefile = globalThis.singlefile;
  4809. const FORBIDDEN_TAG_NAMES = ["a", "area", "audio", "base", "br", "col", "command", "embed", "hr", "img", "iframe", "input", "keygen", "link", "meta", "param", "source", "track", "video", "wbr"];
  4810. const BUTTON_ANCHOR_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAgMAAAAOFJJnAAABhGlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV9TtaIVETuIOASsThZERRylikWwUNoKrTqYXPohNGlIUlwcBdeCgx+LVQcXZ10dXAVB8APEydFJ0UVK/F9SaBHjwXE/3t173L0DhFqJqWbbOKBqlpGMRcVMdkUMvKIbfQCG0SExU4+nFtLwHF/38PH1LsKzvM/9OXqUnMkAn0g8y3TDIl4nnt60dM77xCFWlBTic+Ixgy5I/Mh12eU3zgWHBZ4ZMtLJOeIQsVhoYbmFWdFQiaeIw4qqUb6QcVnhvMVZLVVY4578hcGctpziOs0hxLCIOBIQIaOCDZRgIUKrRoqJJO1HPfyDjj9BLplcG2DkmEcZKiTHD/4Hv7s185MTblIwCrS/2PbHCBDYBepV2/4+tu36CeB/Bq60pr9cA2Y+Sa82tfAR0LsNXFw3NXkPuNwBBp50yZAcyU9TyOeB9zP6pizQfwt0rbq9NfZx+gCkqaulG+DgEBgtUPaax7s7W3v790yjvx825XKP2aKCdAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAAAd0SU1FB+QLEQA4M3Y7LzIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAACVBMVEUAAAAAAACKioqjwG1pAAAAAXRSTlMAQObYZgAAAAFiS0dEAmYLfGQAAABkSURBVBjThc47CsNADIThWfD0bnSfbdIroP/+V0mhsN5gTNToK0YPaSvnF9B9wGykG54j/2GF1/hauE4E1AOuNxrBdA5KUXIqdiCnqC1zIZ2mFJQzKJ3wesOhcwDM4+fo7cOuD9C4HTQ9HAAQAAAAAElFTkSuQmCC";
  4811. const BUTTON_CLOSE_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAgMAAAAOFJJnAAABhGlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV9TtaIVETuIOASsThZERRylikWwUNoKrTqYXPohNGlIUlwcBdeCgx+LVQcXZ10dXAVB8APEydFJ0UVK/F9SaBHjwXE/3t173L0DhFqJqWbbOKBqlpGMRcVMdkUMvKIbfQCG0SExU4+nFtLwHF/38PH1LsKzvM/9OXqUnMkAn0g8y3TDIl4nnt60dM77xCFWlBTic+Ixgy5I/Mh12eU3zgWHBZ4ZMtLJOeIQsVhoYbmFWdFQiaeIw4qqUb6QcVnhvMVZLVVY4578hcGctpziOs0hxLCIOBIQIaOCDZRgIUKrRoqJJO1HPfyDjj9BLplcG2DkmEcZKiTHD/4Hv7s185MTblIwCrS/2PbHCBDYBepV2/4+tu36CeB/Bq60pr9cA2Y+Sa82tfAR0LsNXFw3NXkPuNwBBp50yZAcyU9TyOeB9zP6pizQfwt0rbq9NfZx+gCkqaulG+DgEBgtUPaax7s7W3v790yjvx825XKP2aKCdAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAAAd0SU1FB+QLEQA6Na1u6IUAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAACVBMVEUAAAAAAACKioqjwG1pAAAAAXRSTlMAQObYZgAAAAFiS0dEAmYLfGQAAABlSURBVBhXTc/BEUQhCAPQ58ES6McSPED/rfwDI7vOMCoJIeGd6CvFgZXiwk47Ia5VUKdrVXcb39kfqxqmTg+I2xJ2tqhVTaGaQjTl7/GgIc/4CL4Vs3RsjLFndcxPnAn4iww8A3yQjRZjti1t6AAAAABJRU5ErkJggg==";
  4812. const SHADOWROOT_ATTRIBUTE_NAME = "shadowrootmode";
  4813. const SCRIPT_TEMPLATE_SHADOW_ROOT = "data-template-shadow-root";
  4814. const NOTE_TAGNAME = "single-file-note";
  4815. const NOTE_CLASS = "note";
  4816. const NOTE_MASK_CLASS = "note-mask";
  4817. const NOTE_HIDDEN_CLASS = "note-hidden";
  4818. const NOTE_ANCHORED_CLASS = "note-anchored";
  4819. const NOTE_SELECTED_CLASS = "note-selected";
  4820. const NOTE_MOVING_CLASS = "note-moving";
  4821. const NOTE_MASK_MOVING_CLASS = "note-mask-moving";
  4822. const PAGE_MASK_CLASS = "page-mask";
  4823. const MASK_CLASS = "single-file-mask";
  4824. const PAGE_MASK_CONTAINER_CLASS = "single-file-page-mask";
  4825. const HIGHLIGHT_CLASS = "single-file-highlight";
  4826. const REMOVED_CONTENT_CLASS = "single-file-removed";
  4827. const HIGHLIGHT_HIDDEN_CLASS = "single-file-highlight-hidden";
  4828. const PAGE_MASK_ACTIVE_CLASS = "page-mask-active";
  4829. const CUT_HOVER_CLASS = "single-file-cut-hover";
  4830. const CUT_OUTER_HOVER_CLASS = "single-file-cut-outer-hover";
  4831. const CUT_SELECTED_CLASS = "single-file-cut-selected";
  4832. const CUT_OUTER_SELECTED_CLASS = "single-file-cut-outer-selected";
  4833. const CUT_MODE_CLASS = "single-file-cut-mode";
  4834. const NOTE_INITIAL_POSITION_X = 20;
  4835. const NOTE_INITIAL_POSITION_Y = 20;
  4836. const NOTE_INITIAL_WIDTH = 150;
  4837. const NOTE_INITIAL_HEIGHT = 150;
  4838. const NOTE_HEADER_HEIGHT = 25;
  4839. const DISABLED_NOSCRIPT_ATTRIBUTE_NAME = "data-single-file-disabled-noscript";
  4840. const COMMENT_HEADER = "Page saved with SingleFile";
  4841. const COMMENT_HEADER_LEGACY = "Archive processed by SingleFile";
  4842. const STYLE_FORMATTED_PAGE = `
  4843. /* This Source Code Form is subject to the terms of the Mozilla Public
  4844. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  4845. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  4846. /* Avoid adding ID selector rules in this style sheet, since they could
  4847. * inadvertently match elements in the article content. */
  4848. :root {
  4849. --grey-90-a10: rgba(12, 12, 13, 0.1);
  4850. --grey-90-a20: rgba(12, 12, 13, 0.2);
  4851. --grey-90-a30: rgba(12, 12, 13, 0.3);
  4852. --grey-90-a80: rgba(12, 12, 13, 0.8);
  4853. --grey-30: #d7d7db;
  4854. --blue-40: #45a1ff;
  4855. --blue-40-a30: rgba(69, 161, 255, 0.3);
  4856. --blue-60: #0060df;
  4857. --body-padding: 64px;
  4858. --font-size: 12;
  4859. --content-width: 70em;
  4860. --line-height: 1.6em;
  4861. }
  4862. body {
  4863. --main-background: #fff;
  4864. --main-foreground: #333;
  4865. --font-color: #000000;
  4866. --primary-color: #0B83FF;
  4867. --toolbar-border: var(--grey-90-a20);
  4868. --toolbar-transparent-border: transparent;
  4869. --toolbar-box-shadow: var(--grey-90-a10);
  4870. --toolbar-button-background: transparent;
  4871. --toolbar-button-background-hover: var(--grey-90-a10);
  4872. --toolbar-button-foreground-hover: var(--font-color);
  4873. --toolbar-button-background-active: var(--grey-90-a20);
  4874. --toolbar-button-foreground-active: var(--primary-color);
  4875. --toolbar-button-border: transparent;
  4876. --toolbar-button-border-hover: transparent;
  4877. --toolbar-button-border-active: transparent;
  4878. --tooltip-background: var(--grey-90-a80);
  4879. --tooltip-foreground: white;
  4880. --tooltip-border: transparent;
  4881. --popup-background: white;
  4882. --popup-border: rgba(0, 0, 0, 0.12);
  4883. --opaque-popup-border: #e0e0e0;
  4884. --popup-line: var(--grey-30);
  4885. --popup-shadow: rgba(49, 49, 49, 0.3);
  4886. --popup-button-background: #edecf0;
  4887. --popup-button-background-hover: hsla(0,0%,70%,.4);
  4888. --popup-button-foreground-hover: var(--font-color);
  4889. --popup-button-background-active: hsla(240,5%,5%,.15);
  4890. --selected-background: var(--blue-40-a30);
  4891. --selected-border: var(--blue-40);
  4892. --font-value-border: var(--grey-30);
  4893. --icon-fill: #3b3b3c;
  4894. --icon-disabled-fill: #8080807F;
  4895. --link-foreground: var(--blue-60);
  4896. --link-selected-foreground: #333;
  4897. --visited-link-foreground: #b5007f;
  4898. /* light colours */
  4899. }
  4900. body.sepia {
  4901. --main-background: #f4ecd8;
  4902. --main-foreground: #5b4636;
  4903. --toolbar-border: #5b4636;
  4904. }
  4905. body.dark {
  4906. --main-background: rgb(28, 27, 34);
  4907. --main-foreground: #eee;
  4908. --font-color: #fff;
  4909. --toolbar-border: #4a4a4b;
  4910. --toolbar-box-shadow: black;
  4911. --toolbar-button-background-hover: var(--grey-90-a30);
  4912. --toolbar-button-background-active: var(--grey-90-a80);
  4913. --tooltip-background: black;
  4914. --tooltip-foreground: white;
  4915. --popup-background: rgb(66,65,77);
  4916. --opaque-popup-border: #434146;
  4917. --popup-line: rgb(82, 82, 94);
  4918. --popup-button-background: #5c5c61;
  4919. --popup-button-background-active: hsla(0,0%,70%,.6);
  4920. --selected-background: #3E6D9A;
  4921. --font-value-border: #656468;
  4922. --icon-fill: #fff;
  4923. --icon-disabled-fill: #ffffff66;
  4924. --link-foreground: #45a1ff;
  4925. --link-selected-foreground: #fff;
  4926. --visited-link-foreground: #e675fd;
  4927. /* dark colours */
  4928. }
  4929. body.hcm {
  4930. --main-background: Canvas;
  4931. --main-foreground: CanvasText;
  4932. --font-color: CanvasText;
  4933. --primary-color: SelectedItem;
  4934. --toolbar-border: CanvasText;
  4935. /* We need a true transparent but in HCM this would compute to an actual color,
  4936. so select the page's background color instead: */
  4937. --toolbar-transparent-border: Canvas;
  4938. --toolbar-box-shadow: Canvas;
  4939. --toolbar-button-background: ButtonFace;
  4940. --toolbar-button-background-hover: ButtonText;
  4941. --toolbar-button-foreground-hover: ButtonFace;
  4942. --toolbar-button-background-active: SelectedItem;
  4943. --toolbar-button-foreground-active: SelectedItemText;
  4944. --toolbar-button-border: ButtonText;
  4945. --toolbar-button-border-hover: ButtonText;
  4946. --toolbar-button-border-active: ButtonText;
  4947. --tooltip-background: Canvas;
  4948. --tooltip-foreground: CanvasText;
  4949. --tooltip-border: CanvasText;
  4950. --popup-background: Canvas;
  4951. --popup-border: CanvasText;
  4952. --opaque-popup-border: CanvasText;
  4953. --popup-line: CanvasText;
  4954. --popup-button-background: ButtonFace;
  4955. --popup-button-background-hover: ButtonText;
  4956. --popup-button-foreground-hover: ButtonFace;
  4957. --popup-button-background-active: ButtonText;
  4958. --selected-background: Canvas;
  4959. --selected-border: SelectedItem;
  4960. --font-value-border: CanvasText;
  4961. --icon-fill: ButtonText;
  4962. --icon-disabled-fill: GrayText;
  4963. --link-foreground: LinkText;
  4964. --link-selected-foreground: ActiveText;
  4965. --visited-link-foreground: VisitedText;
  4966. }
  4967. body {
  4968. margin: 0;
  4969. padding: var(--body-padding);
  4970. background-color: var(--main-background);
  4971. color: var(--main-foreground);
  4972. }
  4973. body.loaded {
  4974. transition: color 0.4s, background-color 0.4s;
  4975. }
  4976. body.dark *::-moz-selection {
  4977. background-color: var(--selected-background);
  4978. }
  4979. a::-moz-selection {
  4980. color: var(--link-selected-foreground);
  4981. }
  4982. body.sans-serif,
  4983. body.sans-serif .remove-button {
  4984. font-family: Helvetica, Arial, sans-serif;
  4985. }
  4986. body.serif,
  4987. body.serif .remove-button {
  4988. font-family: Georgia, "Times New Roman", serif;
  4989. }
  4990. /* Override some controls and content styles based on color scheme */
  4991. body.light > .container > .header > .domain {
  4992. border-bottom-color: #333333 !important;
  4993. }
  4994. body.sepia > .container > .header > .domain {
  4995. border-bottom-color: #5b4636 !important;
  4996. }
  4997. body.dark > .container > .header > .domain {
  4998. border-bottom-color: #eeeeee !important;
  4999. }
  5000. body.light blockquote {
  5001. border-inline-start: 2px solid #333333 !important;
  5002. }
  5003. body.sepia blockquote {
  5004. border-inline-start: 2px solid #5b4636 !important;
  5005. }
  5006. body.dark blockquote {
  5007. border-inline-start: 2px solid #eeeeee !important;
  5008. }
  5009. .light-button {
  5010. color: #333333;
  5011. background-color: #ffffff;
  5012. }
  5013. .dark-button {
  5014. color: #eeeeee;
  5015. background-color: #1c1b22;
  5016. }
  5017. .sepia-button {
  5018. color: #5b4636;
  5019. background-color: #f4ecd8;
  5020. }
  5021. .auto-button {
  5022. text-align: center;
  5023. }
  5024. @media (prefers-color-scheme: dark) {
  5025. .auto-button {
  5026. background-color: #1c1b22;
  5027. color: #eeeeee;
  5028. }
  5029. }
  5030. @media not (prefers-color-scheme: dark) {
  5031. .auto-button {
  5032. background-color: #ffffff;
  5033. color: #333333;
  5034. }
  5035. }
  5036. /* Loading/error message */
  5037. .reader-message {
  5038. margin-top: 40px;
  5039. display: none;
  5040. text-align: center;
  5041. width: 100%;
  5042. font-size: 0.9em;
  5043. }
  5044. /* Detector element to see if we're at the top of the doc or not. */
  5045. .top-anchor {
  5046. position: absolute;
  5047. top: 0;
  5048. width: 0;
  5049. height: 5px;
  5050. pointer-events: none;
  5051. }
  5052. /* Header */
  5053. .header {
  5054. text-align: start;
  5055. display: none;
  5056. }
  5057. .domain {
  5058. font-size: 0.9em;
  5059. line-height: 1.48em;
  5060. padding-bottom: 4px;
  5061. font-family: Helvetica, Arial, sans-serif;
  5062. text-decoration: none;
  5063. border-bottom: 1px solid;
  5064. color: var(--link-foreground);
  5065. }
  5066. .header > h1 {
  5067. font-size: 1.6em;
  5068. line-height: 1.25em;
  5069. width: 100%;
  5070. margin: 30px 0;
  5071. padding: 0;
  5072. }
  5073. .header > .credits {
  5074. font-size: 0.9em;
  5075. line-height: 1.48em;
  5076. margin: 0 0 10px;
  5077. padding: 0;
  5078. font-style: italic;
  5079. }
  5080. .header > .meta-data {
  5081. font-size: 0.65em;
  5082. margin: 0 0 15px;
  5083. }
  5084. .reader-estimated-time {
  5085. text-align: match-parent;
  5086. }
  5087. /* Controls toolbar */
  5088. .toolbar-container {
  5089. position: sticky;
  5090. z-index: 2;
  5091. top: 32px;
  5092. height: 0; /* take up no space, so body is at the top. */
  5093. /* As a stick container, we're positioned relative to the body. Move us to
  5094. * the edge of the viewport using margins, and take the width of
  5095. * the body padding into account for calculating our width.
  5096. */
  5097. margin-inline-start: calc(-1 * var(--body-padding));
  5098. width: max(var(--body-padding), calc((100% - var(--content-width)) / 2 + var(--body-padding)));
  5099. font-size: var(--font-size); /* Needed to ensure 'em' units match, is reset for .reader-controls */
  5100. }
  5101. .toolbar {
  5102. padding-block: 16px;
  5103. border: 1px solid var(--toolbar-border);
  5104. border-radius: 6px;
  5105. box-shadow: 0 2px 8px var(--toolbar-box-shadow);
  5106. width: 32px; /* basic width, without padding/border */
  5107. /* padding should be 16px, except if there's not enough space for that, in
  5108. * which case use half the available space for padding (=25% on each side).
  5109. * The 34px here is the width + borders. We use a variable because we need
  5110. * to know this size for the margin calculation.
  5111. */
  5112. --inline-padding: min(16px, calc(25% - 0.25 * 34px));
  5113. padding-inline: var(--inline-padding);
  5114. /* Keep a maximum of 96px distance to the body, but center once the margin
  5115. * gets too small. We need to set the start margin, however...
  5116. * To center, we'd want 50% of the container, but we'd subtract half our
  5117. * own width (16px) and half the border (1px) and the inline padding.
  5118. * When the other margin would be 96px, we want 100% - 96px - the complete
  5119. * width of the actual toolbar (34px + 2 * padding)
  5120. */
  5121. margin-inline-start: max(calc(50% - 17px - var(--inline-padding)), calc(100% - 96px - 34px - 2 * var(--inline-padding)));
  5122. font-family: Helvetica, Arial, sans-serif;
  5123. list-style: none;
  5124. user-select: none;
  5125. }
  5126. @media (prefers-reduced-motion: no-preference) {
  5127. .toolbar {
  5128. transition-property: border-color, box-shadow;
  5129. transition-duration: 250ms;
  5130. }
  5131. .toolbar .toolbar-button {
  5132. transition-property: opacity;
  5133. transition-duration: 250ms;
  5134. }
  5135. .toolbar-container.scrolled .toolbar:not(:hover, :focus-within) {
  5136. border-color: var(--toolbar-transparent-border);
  5137. box-shadow: 0 2px 8px transparent;
  5138. }
  5139. .toolbar-container.scrolled .toolbar:not(:hover, :focus-within) .toolbar-button {
  5140. opacity: 0.6;
  5141. }
  5142. .toolbar-container.transition-location {
  5143. transition-duration: 250ms;
  5144. transition-property: width;
  5145. }
  5146. }
  5147. .toolbar-container.overlaps .toolbar-button {
  5148. opacity: 0.1;
  5149. }
  5150. .dropdown-open .toolbar {
  5151. border-color: var(--toolbar-transparent-border);
  5152. box-shadow: 0 2px 8px transparent;
  5153. }
  5154. .reader-controls {
  5155. /* We use 'em's above this node to get it to the right size. However,
  5156. * the UI inside the toolbar should use a fixed, smaller size. */
  5157. font-size: 11px;
  5158. }
  5159. button {
  5160. -moz-context-properties: fill;
  5161. color: var(--font-color);
  5162. fill: var(--icon-fill);
  5163. }
  5164. button:disabled {
  5165. fill: var(--icon-disabled-fill);
  5166. }
  5167. .toolbar button::-moz-focus-inner {
  5168. border: 0;
  5169. }
  5170. .toolbar-button {
  5171. position: relative;
  5172. width: 32px;
  5173. height: 32px;
  5174. padding: 0;
  5175. border: 1px solid var(--toolbar-button-border);
  5176. border-radius: 4px;
  5177. margin: 4px 0;
  5178. background-color: var(--toolbar-button-background);
  5179. background-size: 16px 16px;
  5180. background-position: center;
  5181. background-repeat: no-repeat;
  5182. }
  5183. .toolbar-button:hover,
  5184. .toolbar-button:focus-visible {
  5185. background-color: var(--toolbar-button-background-hover);
  5186. border-color: var(--toolbar-button-border-hover);
  5187. fill: var(--toolbar-button-foreground-hover);
  5188. }
  5189. .open .toolbar-button,
  5190. .toolbar-button:hover:active {
  5191. background-color: var(--toolbar-button-background-active);
  5192. border-color: var(--toolbar-button-border-active);
  5193. color: var(--toolbar-button-foreground-active);
  5194. fill: var(--toolbar-button-foreground-active);
  5195. }
  5196. .hover-label {
  5197. position: absolute;
  5198. top: 4px;
  5199. inset-inline-start: 36px;
  5200. line-height: 16px;
  5201. white-space: pre; /* make sure we don't wrap */
  5202. background-color: var(--tooltip-background);
  5203. color: var(--tooltip-foreground);
  5204. padding: 4px 8px;
  5205. border: 1px solid var(--tooltip-border);
  5206. border-radius: 2px;
  5207. visibility: hidden;
  5208. pointer-events: none;
  5209. /* Put above .dropdown .dropdown-popup, which has z-index: 1000. */
  5210. z-index: 1001;
  5211. }
  5212. /* Show the hover tooltip on non-dropdown buttons. */
  5213. .toolbar-button:not(.dropdown-toggle):hover > .hover-label,
  5214. .toolbar-button:not(.dropdown-toggle):focus-visible > .hover-label,
  5215. /* Show the hover tooltip for dropdown buttons unless its dropdown is open. */
  5216. :not(.open) > li > .dropdown-toggle:hover > .hover-label,
  5217. :not(.open) > li > .dropdown-toggle:focus-visible > .hover-label {
  5218. visibility: visible;
  5219. }
  5220. .dropdown {
  5221. text-align: center;
  5222. list-style: none;
  5223. margin: 0;
  5224. padding: 0;
  5225. position: relative;
  5226. }
  5227. .dropdown li {
  5228. margin: 0;
  5229. padding: 0;
  5230. }
  5231. /* Popup */
  5232. .dropdown .dropdown-popup {
  5233. text-align: start;
  5234. position: absolute;
  5235. inset-inline-start: 40px;
  5236. z-index: 1000;
  5237. background-color: var(--popup-background);
  5238. visibility: hidden;
  5239. border-radius: 4px;
  5240. border: 1px solid var(--popup-border);
  5241. box-shadow: 0 0 10px 0 var(--popup-shadow);
  5242. top: 0;
  5243. }
  5244. .open > .dropdown-popup {
  5245. visibility: visible;
  5246. }
  5247. .dropdown-arrow {
  5248. position: absolute;
  5249. height: 24px;
  5250. width: 16px;
  5251. inset-inline-start: -16px;
  5252. background-image: url("chrome://global/skin/reader/RM-Type-Controls-Arrow.svg");
  5253. display: block;
  5254. -moz-context-properties: fill, stroke;
  5255. fill: var(--popup-background);
  5256. stroke: var(--opaque-popup-border);
  5257. pointer-events: none;
  5258. }
  5259. .dropdown-arrow:dir(rtl) {
  5260. transform: scaleX(-1);
  5261. }
  5262. /* Align the style dropdown arrow (narrate does its own) */
  5263. .style-dropdown .dropdown-arrow {
  5264. top: 7px;
  5265. }
  5266. /* Font style popup */
  5267. .radio-button {
  5268. /* We visually hide these, but we keep them around so they can be focused
  5269. * and changed by interacting with them via the label, or the keyboard, or
  5270. * assistive technology.
  5271. */
  5272. opacity: 0;
  5273. pointer-events: none;
  5274. position: absolute;
  5275. }
  5276. .radiorow,
  5277. .buttonrow {
  5278. display: flex;
  5279. align-content: center;
  5280. justify-content: center;
  5281. }
  5282. .content-width-value,
  5283. .font-size-value,
  5284. .line-height-value {
  5285. box-sizing: border-box;
  5286. width: 36px;
  5287. height: 20px;
  5288. line-height: 20px;
  5289. display: flex;
  5290. justify-content: center;
  5291. align-content: center;
  5292. margin: auto;
  5293. border-radius: 10px;
  5294. border: 1px solid var(--font-value-border);
  5295. background-color: var(--popup-button-background);
  5296. }
  5297. .buttonrow > button {
  5298. border: 0;
  5299. height: 60px;
  5300. width: 90px;
  5301. background-color: transparent;
  5302. background-repeat: no-repeat;
  5303. background-position: center;
  5304. }
  5305. .buttonrow > button:enabled:hover,
  5306. .buttonrow > button:enabled:focus-visible {
  5307. background-color: var(--popup-button-background-hover);
  5308. color: var(--popup-button-foreground-hover);
  5309. fill: var(--popup-button-foreground-hover);
  5310. }
  5311. .buttonrow > button:enabled:hover:active {
  5312. background-color: var(--popup-button-background-active);
  5313. }
  5314. .radiorow:not(:last-child),
  5315. .buttonrow:not(:last-child) {
  5316. border-bottom: 1px solid var(--popup-line);
  5317. }
  5318. body.hcm .buttonrow.line-height-buttons {
  5319. /* On HCM the .color-scheme-buttons row is hidden, so remove the border from the row above it */
  5320. border-bottom: none;
  5321. }
  5322. .radiorow > label {
  5323. position: relative;
  5324. box-sizing: border-box;
  5325. border-radius: 2px;
  5326. border: 2px solid var(--popup-border);
  5327. }
  5328. .radiorow > label[checked] {
  5329. border-color: var(--selected-border);
  5330. }
  5331. /* For the hover style, we draw a line under the item by means of a
  5332. * pseudo-element. Because these items are variable height, and
  5333. * because their contents are variable height, position it absolutely,
  5334. * and give it a width of 100% (the content width) + 4px for the 2 * 2px
  5335. * border width.
  5336. */
  5337. .radiorow > input[type=radio]:focus-visible + label::after,
  5338. .radiorow > label:hover::after {
  5339. content: "";
  5340. display: block;
  5341. border-bottom: 2px solid var(--selected-border);
  5342. width: calc(100% + 4px);
  5343. position: absolute;
  5344. /* to skip the 2 * 2px border + 2px spacing. */
  5345. bottom: -6px;
  5346. /* Match the start of the 2px border of the element: */
  5347. inset-inline-start: -2px;
  5348. }
  5349. .font-type-buttons > label {
  5350. height: 64px;
  5351. width: 105px;
  5352. /* Slightly more space between these items. */
  5353. margin: 10px;
  5354. /* Center the Sans-serif / Serif labels */
  5355. text-align: center;
  5356. background-size: 63px 39px;
  5357. background-repeat: no-repeat;
  5358. background-position: center 18px;
  5359. background-color: var(--popup-button-background);
  5360. fill: currentColor;
  5361. -moz-context-properties: fill;
  5362. /* This mostly matches baselines, but because of differences in font
  5363. * baselines between serif and sans-serif, this isn't always enough. */
  5364. line-height: 1;
  5365. padding-top: 2px;
  5366. }
  5367. .font-type-buttons > label[checked] {
  5368. background-color: var(--selected-background);
  5369. }
  5370. .sans-serif-button {
  5371. font-family: Helvetica, Arial, sans-serif;
  5372. background-image: url("chrome://global/skin/reader/RM-Sans-Serif.svg");
  5373. }
  5374. /* Tweak padding to match the baseline on mac */
  5375. :root[platform=macosx] .sans-serif-button {
  5376. padding-top: 3px;
  5377. }
  5378. .serif-button {
  5379. font-family: Georgia, "Times New Roman", serif;
  5380. background-image: url("chrome://global/skin/reader/RM-Serif.svg");
  5381. }
  5382. body.hcm .color-scheme-buttons {
  5383. /* Disallow selecting themes when HCM is on. */
  5384. display: none;
  5385. }
  5386. .color-scheme-buttons > label {
  5387. padding: 12px;
  5388. height: 34px;
  5389. font-size: 12px;
  5390. /* Center the labels horizontally as well as vertically */
  5391. display: inline-flex;
  5392. align-items: center;
  5393. justify-content: center;
  5394. /* We want 10px between items, but there's no margin collapsing in flexbox. */
  5395. margin: 10px 5px;
  5396. }
  5397. .color-scheme-buttons > input:first-child + label {
  5398. margin-inline-start: 10px;
  5399. }
  5400. .color-scheme-buttons > label:last-child {
  5401. margin-inline-end: 10px;
  5402. }
  5403. /* Toolbar icons */
  5404. .close-button {
  5405. background-image: url("chrome://global/skin/icons/close.svg");
  5406. }
  5407. .style-button {
  5408. background-image: url("chrome://global/skin/reader/RM-Type-Controls-24x24.svg");
  5409. }
  5410. .minus-button {
  5411. background-size: 18px 18px;
  5412. background-image: url("chrome://global/skin/reader/RM-Minus-24x24.svg");
  5413. }
  5414. .plus-button {
  5415. background-size: 18px 18px;
  5416. background-image: url("chrome://global/skin/reader/RM-Plus-24x24.svg");
  5417. }
  5418. .content-width-minus-button {
  5419. background-size: 42px 16px;
  5420. background-image: url("chrome://global/skin/reader/RM-Content-Width-Minus-42x16.svg");
  5421. }
  5422. .content-width-plus-button {
  5423. background-size: 44px 16px;
  5424. background-image: url("chrome://global/skin/reader/RM-Content-Width-Plus-44x16.svg");
  5425. }
  5426. .line-height-minus-button {
  5427. background-size: 34px 14px;
  5428. background-image: url("chrome://global/skin/reader/RM-Line-Height-Minus-38x14.svg");
  5429. }
  5430. .line-height-plus-button {
  5431. background-size: 34px 24px;
  5432. background-image: url("chrome://global/skin/reader/RM-Line-Height-Plus-38x24.svg");
  5433. }
  5434. /* Mirror the line height buttons if the article is RTL. */
  5435. .reader-controls[articledir="rtl"] .line-height-minus-button,
  5436. .reader-controls[articledir="rtl"] .line-height-plus-button {
  5437. transform: scaleX(-1);
  5438. }
  5439. @media print {
  5440. .toolbar {
  5441. display: none !important;
  5442. }
  5443. }
  5444. /* Article content */
  5445. /* Note that any class names from the original article that we want to match on
  5446. * must be added to CLASSES_TO_PRESERVE in ReaderMode.jsm, so that
  5447. * Readability.js doesn't strip them out */
  5448. .container {
  5449. margin: 0 auto;
  5450. font-size: var(--font-size);
  5451. max-width: var(--content-width);
  5452. line-height: var(--line-height);
  5453. }
  5454. pre {
  5455. font-family: inherit;
  5456. }
  5457. .moz-reader-content {
  5458. display: none;
  5459. font-size: 1em;
  5460. }
  5461. @media print {
  5462. .moz-reader-content p,
  5463. .moz-reader-content code,
  5464. .moz-reader-content pre,
  5465. .moz-reader-content blockquote,
  5466. .moz-reader-content ul,
  5467. .moz-reader-content ol,
  5468. .moz-reader-content li,
  5469. .moz-reader-content figure,
  5470. .moz-reader-content .wp-caption {
  5471. margin: 0 0 10px !important;
  5472. padding: 0 !important;
  5473. }
  5474. }
  5475. .moz-reader-content h1,
  5476. .moz-reader-content h2,
  5477. .moz-reader-content h3 {
  5478. font-weight: bold;
  5479. }
  5480. .moz-reader-content h1 {
  5481. font-size: 1.6em;
  5482. line-height: 1.25em;
  5483. }
  5484. .moz-reader-content h2 {
  5485. font-size: 1.2em;
  5486. line-height: 1.51em;
  5487. }
  5488. .moz-reader-content h3 {
  5489. font-size: 1em;
  5490. line-height: 1.66em;
  5491. }
  5492. .moz-reader-content a:link {
  5493. text-decoration: underline;
  5494. font-weight: normal;
  5495. }
  5496. .moz-reader-content a:link,
  5497. .moz-reader-content a:link:hover,
  5498. .moz-reader-content a:link:active {
  5499. color: var(--link-foreground);
  5500. }
  5501. .moz-reader-content a:visited {
  5502. color: var(--visited-link-foreground);
  5503. }
  5504. .moz-reader-content * {
  5505. max-width: 100%;
  5506. height: auto;
  5507. }
  5508. .moz-reader-content p,
  5509. .moz-reader-content p,
  5510. .moz-reader-content code,
  5511. .moz-reader-content pre,
  5512. .moz-reader-content blockquote,
  5513. .moz-reader-content ul,
  5514. .moz-reader-content ol,
  5515. .moz-reader-content li,
  5516. .moz-reader-content figure,
  5517. .moz-reader-content .wp-caption {
  5518. margin: -10px -10px 20px;
  5519. padding: 10px;
  5520. border-radius: 5px;
  5521. }
  5522. .moz-reader-content li {
  5523. margin-bottom: 0;
  5524. }
  5525. .moz-reader-content li > ul,
  5526. .moz-reader-content li > ol {
  5527. margin-bottom: -10px;
  5528. }
  5529. .moz-reader-content p > img:only-child,
  5530. .moz-reader-content p > a:only-child > img:only-child,
  5531. .moz-reader-content .wp-caption img,
  5532. .moz-reader-content figure img {
  5533. display: block;
  5534. }
  5535. .moz-reader-content img[moz-reader-center] {
  5536. margin-inline: auto;
  5537. }
  5538. .moz-reader-content .caption,
  5539. .moz-reader-content .wp-caption-text
  5540. .moz-reader-content figcaption {
  5541. font-size: 0.9em;
  5542. line-height: 1.48em;
  5543. font-style: italic;
  5544. }
  5545. .moz-reader-content pre {
  5546. white-space: pre-wrap;
  5547. }
  5548. .moz-reader-content blockquote {
  5549. padding: 0;
  5550. padding-inline-start: 16px;
  5551. }
  5552. .moz-reader-content ul,
  5553. .moz-reader-content ol {
  5554. padding: 0;
  5555. }
  5556. .moz-reader-content ul {
  5557. padding-inline-start: 30px;
  5558. list-style: disc;
  5559. }
  5560. .moz-reader-content ol {
  5561. padding-inline-start: 30px;
  5562. }
  5563. table,
  5564. th,
  5565. td {
  5566. border: 1px solid currentColor;
  5567. border-collapse: collapse;
  5568. padding: 6px;
  5569. vertical-align: top;
  5570. }
  5571. table {
  5572. margin: 5px;
  5573. }
  5574. /* Visually hide (but don't display: none) screen reader elements */
  5575. .moz-reader-content .visually-hidden,
  5576. .moz-reader-content .visuallyhidden,
  5577. .moz-reader-content .sr-only {
  5578. display: inline-block;
  5579. width: 1px;
  5580. height: 1px;
  5581. margin: -1px;
  5582. overflow: hidden;
  5583. padding: 0;
  5584. border-width: 0;
  5585. }
  5586. /* Hide elements with common "hidden" class names */
  5587. .moz-reader-content .hidden,
  5588. .moz-reader-content .invisible {
  5589. display: none;
  5590. }
  5591. /* Enforce wordpress and similar emoji/smileys aren't sized to be full-width,
  5592. * see bug 1399616 for context. */
  5593. .moz-reader-content img.wp-smiley,
  5594. .moz-reader-content img.emoji {
  5595. display: inline-block;
  5596. border-width: 0;
  5597. /* height: auto is implied from '.moz-reader-content *' rule. */
  5598. width: 1em;
  5599. margin: 0 .07em;
  5600. padding: 0;
  5601. }
  5602. .reader-show-element {
  5603. display: initial;
  5604. }
  5605. /* Provide extra spacing for images that may be aided with accompanying element such as <figcaption> */
  5606. .moz-reader-block-img:not(:last-child) {
  5607. margin-block-end: 12px;
  5608. }
  5609. .moz-reader-wide-table {
  5610. overflow-x: auto;
  5611. display: block;
  5612. }
  5613. pre code {
  5614. background-color: var(--main-background);
  5615. border: 1px solid var(--font-color);
  5616. display: block;
  5617. overflow: auto;
  5618. }`;
  5619. let NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET;
  5620. let selectedNote, anchorElement, maskNoteElement, maskPageElement, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, highlightColor, collapseNoteTimeout, cuttingOuterMode, cuttingMode, cuttingTouchTarget, cuttingPath, cuttingPathIndex, previousContent;
  5621. let removedElements = [], removedElementIndex = 0, initScriptContent, pageResources, pageUrl, pageCompressContent, includeInfobar;
  5622. globalThis.zip = zip$1;
  5623. window.onmessage = async event => {
  5624. const message = JSON.parse(event.data);
  5625. if (message.method == "init") {
  5626. await init(message);
  5627. }
  5628. if (message.method == "addNote") {
  5629. addNote(message);
  5630. }
  5631. if (message.method == "displayNotes") {
  5632. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.remove(NOTE_HIDDEN_CLASS));
  5633. }
  5634. if (message.method == "hideNotes") {
  5635. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.add(NOTE_HIDDEN_CLASS));
  5636. }
  5637. if (message.method == "enableHighlight") {
  5638. if (highlightColor) {
  5639. document.documentElement.classList.remove(highlightColor + "-mode");
  5640. }
  5641. highlightColor = message.color;
  5642. highlightSelectionMode = true;
  5643. document.documentElement.classList.add(message.color + "-mode");
  5644. }
  5645. if (message.method == "disableHighlight") {
  5646. disableHighlight();
  5647. highlightSelectionMode = false;
  5648. }
  5649. if (message.method == "displayHighlights") {
  5650. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  5651. }
  5652. if (message.method == "hideHighlights") {
  5653. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.add(HIGHLIGHT_HIDDEN_CLASS));
  5654. }
  5655. if (message.method == "enableRemoveHighlights") {
  5656. removeHighlightMode = true;
  5657. document.documentElement.classList.add("single-file-remove-highlights-mode");
  5658. }
  5659. if (message.method == "disableRemoveHighlights") {
  5660. removeHighlightMode = false;
  5661. document.documentElement.classList.remove("single-file-remove-highlights-mode");
  5662. }
  5663. if (message.method == "enableEditPage") {
  5664. document.body.contentEditable = true;
  5665. onUpdate(false);
  5666. }
  5667. if (message.method == "formatPage") {
  5668. formatPage(!message.applySystemTheme);
  5669. }
  5670. if (message.method == "cancelFormatPage") {
  5671. cancelFormatPage();
  5672. }
  5673. if (message.method == "disableEditPage") {
  5674. document.body.contentEditable = false;
  5675. }
  5676. if (message.method == "enableCutInnerPage") {
  5677. cuttingMode = true;
  5678. document.documentElement.classList.add(CUT_MODE_CLASS);
  5679. }
  5680. if (message.method == "enableCutOuterPage") {
  5681. cuttingOuterMode = true;
  5682. document.documentElement.classList.add(CUT_MODE_CLASS);
  5683. }
  5684. if (message.method == "disableCutInnerPage" || message.method == "disableCutOuterPage") {
  5685. if (message.method == "disableCutInnerPage") {
  5686. cuttingMode = false;
  5687. } else {
  5688. cuttingOuterMode = false;
  5689. }
  5690. document.documentElement.classList.remove(CUT_MODE_CLASS);
  5691. resetSelectedElements();
  5692. if (cuttingPath) {
  5693. unhighlightCutElement();
  5694. cuttingPath = null;
  5695. }
  5696. }
  5697. if (message.method == "undoCutPage") {
  5698. undoCutPage();
  5699. }
  5700. if (message.method == "undoAllCutPage") {
  5701. while (removedElementIndex) {
  5702. removedElements[removedElementIndex - 1].forEach(element => element.classList.remove(REMOVED_CONTENT_CLASS));
  5703. removedElementIndex--;
  5704. }
  5705. }
  5706. if (message.method == "redoCutPage") {
  5707. redoCutPage();
  5708. }
  5709. if (message.method == "getContent") {
  5710. onUpdate(true);
  5711. includeInfobar = message.includeInfobar;
  5712. let content = getContent(message.compressHTML, message.updatedResources);
  5713. if (initScriptContent) {
  5714. content = content.replace(/<script data-template-shadow-root src.*?<\/script>/g, initScriptContent);
  5715. }
  5716. debugger;
  5717. if (pageCompressContent) {
  5718. if (message.foregroundSave) {
  5719. alert("Foreground save not supported for compressed content");
  5720. } else {
  5721. const viewport = document.head.querySelector("meta[name=viewport]");
  5722. window.parent.postMessage(JSON.stringify({
  5723. method: "setContent",
  5724. content,
  5725. title: document.title,
  5726. doctype: singlefile.helper.getDoctypeString(document),
  5727. url: pageUrl,
  5728. viewport: viewport ? viewport.content : null,
  5729. compressContent: true
  5730. }), "*");
  5731. }
  5732. } else {
  5733. if (message.foregroundSave) {
  5734. if (message.filename && message.filename.length) {
  5735. const link = document.createElement("a");
  5736. link.download = message.filename;
  5737. link.href = URL.createObjectURL(new Blob([content], { type: "text/html" }));
  5738. link.dispatchEvent(new MouseEvent("click"));
  5739. }
  5740. return new Promise(resolve => setTimeout(resolve, 1));
  5741. } else {
  5742. window.parent.postMessage(JSON.stringify({
  5743. method: "setContent",
  5744. content
  5745. }), "*");
  5746. }
  5747. }
  5748. }
  5749. if (message.method == "printPage") {
  5750. printPage();
  5751. }
  5752. if (message.method == "displayInfobar") {
  5753. singlefile.helper.displayIcon(document, true);
  5754. }
  5755. };
  5756. window.onresize = reflowNotes;
  5757. document.ondragover = event => event.preventDefault();
  5758. document.ondrop = async event => {
  5759. if (event.dataTransfer.files && event.dataTransfer.files[0]) {
  5760. const file = event.dataTransfer.files[0];
  5761. event.preventDefault();
  5762. const content = new TextDecoder().decode(await file.arrayBuffer());
  5763. const compressContent = /<html[^>]* data-sfz[^>]*>/i.test(content);
  5764. if (compressContent) {
  5765. await init({ content: file, compressContent }, { filename: file.name });
  5766. } else {
  5767. await init({ content }, { filename: file.name });
  5768. }
  5769. }
  5770. };
  5771. async function init({ content, password, compressContent }, { filename, reset } = {}) {
  5772. await initConstants();
  5773. if (compressContent) {
  5774. const zipOptions = {
  5775. workerScripts: { inflate: ["/lib/single-file-z-worker.js"] }
  5776. };
  5777. try {
  5778. const worker = new Worker(zipOptions.workerScripts.inflate[0]);
  5779. worker.terminate();
  5780. } catch (error) {
  5781. delete zipOptions.workerScripts;
  5782. }
  5783. zipOptions.useWebWorkers = IS_NOT_SAFARI;
  5784. const { docContent, origDocContent, resources, url } = await extract(content, {
  5785. password,
  5786. prompt,
  5787. shadowRootScriptURL: new URL("/lib/single-file-extension-editor-init.js", document.baseURI).href,
  5788. zipOptions
  5789. });
  5790. pageResources = resources;
  5791. pageUrl = url;
  5792. pageCompressContent = true;
  5793. const contentDocument = (new DOMParser()).parseFromString(docContent, "text/html");
  5794. if (detectSavedPage(contentDocument)) {
  5795. await display(document, docContent, { disableFramePointerEvents: true });
  5796. const infobarElement = document.querySelector(singlefile.helper.INFOBAR_TAGNAME);
  5797. if (infobarElement) {
  5798. infobarElement.remove();
  5799. }
  5800. await initPage();
  5801. let icon;
  5802. const origContentDocument = (new DOMParser()).parseFromString(origDocContent, "text/html");
  5803. const iconElement = origContentDocument.querySelector("link[rel*=icon]");
  5804. if (iconElement) {
  5805. const iconResource = resources.find(resource => resource.filename == iconElement.getAttribute("href"));
  5806. if (iconResource && iconResource.blob) {
  5807. const reader = new FileReader();
  5808. reader.readAsDataURL(iconResource.blob);
  5809. icon = await new Promise((resolve, reject) => {
  5810. reader.addEventListener("load", () => resolve(reader.result), false);
  5811. reader.addEventListener("error", reject, false);
  5812. });
  5813. } else {
  5814. icon = iconElement.href;
  5815. }
  5816. }
  5817. window.parent.postMessage(JSON.stringify({
  5818. method: "onInit",
  5819. title: document.title,
  5820. icon,
  5821. filename,
  5822. reset,
  5823. formatPageEnabled: isProbablyReaderable(document)
  5824. }), "*");
  5825. }
  5826. } else {
  5827. const initScriptContentMatch = content.match(/<script data-template-shadow-root.*<\/script>/);
  5828. if (initScriptContentMatch && initScriptContentMatch[0]) {
  5829. initScriptContent = initScriptContentMatch[0];
  5830. }
  5831. content = content.replace(/<script data-template-shadow-root.*<\/script>/g, "<script data-template-shadow-root src=/lib/single-file-extension-editor-init.js></script>");
  5832. const contentDocument = (new DOMParser()).parseFromString(content, "text/html");
  5833. if (detectSavedPage(contentDocument)) {
  5834. if (contentDocument.doctype) {
  5835. if (document.doctype) {
  5836. document.replaceChild(contentDocument.doctype, document.doctype);
  5837. } else {
  5838. document.insertBefore(contentDocument.doctype, document.documentElement);
  5839. }
  5840. } else if (document.doctype) {
  5841. document.doctype.remove();
  5842. }
  5843. const infobarElement = contentDocument.querySelector(singlefile.helper.INFOBAR_TAGNAME);
  5844. if (infobarElement) {
  5845. infobarElement.remove();
  5846. }
  5847. contentDocument.querySelectorAll("noscript").forEach(element => {
  5848. element.setAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME, element.innerHTML);
  5849. element.textContent = "";
  5850. });
  5851. contentDocument.querySelectorAll("iframe").forEach(element => {
  5852. const pointerEvents = "pointer-events";
  5853. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  5854. element.style.setProperty(pointerEvents, "none", "important");
  5855. });
  5856. document.replaceChild(contentDocument.documentElement, document.documentElement);
  5857. document.querySelectorAll("[data-single-file-note-refs]").forEach(noteRefElement => noteRefElement.dataset.singleFileNoteRefs = noteRefElement.dataset.singleFileNoteRefs.replace(/,/g, " "));
  5858. deserializeShadowRoots(document);
  5859. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  5860. document.documentElement.appendChild(getStyleElement(HIGHLIGHTS_WEB_STYLESHEET));
  5861. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  5862. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  5863. document.documentElement.onmousedown = onMouseDown;
  5864. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  5865. document.documentElement.onmouseover = onMouseOver;
  5866. document.documentElement.onmouseout = onMouseOut;
  5867. document.documentElement.onkeydown = onKeyDown;
  5868. document.documentElement.ontouchstart = document.documentElement.ontouchmove = onTouchMove;
  5869. window.onclick = event => event.preventDefault();
  5870. const iconElement = document.querySelector("link[rel*=icon]");
  5871. window.parent.postMessage(JSON.stringify({
  5872. method: "onInit",
  5873. title: document.title,
  5874. icon: iconElement && iconElement.href,
  5875. filename,
  5876. reset,
  5877. formatPageEnabled: isProbablyReaderable(document)
  5878. }), "*");
  5879. }
  5880. }
  5881. }
  5882. async function initPage() {
  5883. document.querySelectorAll("iframe").forEach(element => {
  5884. const pointerEvents = "pointer-events";
  5885. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  5886. element.style.setProperty(pointerEvents, "none", "important");
  5887. });
  5888. document.querySelectorAll("[data-single-file-note-refs]").forEach(noteRefElement => noteRefElement.dataset.singleFileNoteRefs = noteRefElement.dataset.singleFileNoteRefs.replace(/,/g, " "));
  5889. deserializeShadowRoots(document);
  5890. reflowNotes();
  5891. await waitResourcesLoad();
  5892. reflowNotes();
  5893. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  5894. document.documentElement.appendChild(getStyleElement(HIGHLIGHTS_WEB_STYLESHEET));
  5895. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  5896. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  5897. document.documentElement.onmousedown = onMouseDown;
  5898. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  5899. document.documentElement.onmouseover = onMouseOver;
  5900. document.documentElement.onmouseout = onMouseOut;
  5901. document.documentElement.onkeydown = onKeyDown;
  5902. document.documentElement.ontouchstart = document.documentElement.ontouchmove = onTouchMove;
  5903. window.onclick = event => event.preventDefault();
  5904. }
  5905. async function initConstants() {
  5906. [NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET] = await Promise.all([
  5907. minifyText(await ((await fetch("../pages/editor-note-web.css")).text())),
  5908. minifyText(await ((await fetch("../pages/editor-mask-web.css")).text())),
  5909. minifyText(await ((await fetch("../pages/editor-frame-web.css")).text()))
  5910. ]);
  5911. }
  5912. function addNote({ color }) {
  5913. const containerElement = document.createElement(NOTE_TAGNAME);
  5914. const noteElement = document.createElement("div");
  5915. const headerElement = document.createElement("header");
  5916. const blockquoteElement = document.createElement("blockquote");
  5917. const mainElement = document.createElement("textarea");
  5918. const resizeElement = document.createElement("div");
  5919. const removeNoteElement = document.createElement("img");
  5920. const anchorIconElement = document.createElement("img");
  5921. const noteShadow = containerElement.attachShadow({ mode: "open" });
  5922. headerElement.appendChild(anchorIconElement);
  5923. headerElement.appendChild(removeNoteElement);
  5924. blockquoteElement.appendChild(mainElement);
  5925. noteElement.appendChild(headerElement);
  5926. noteElement.appendChild(blockquoteElement);
  5927. noteElement.appendChild(resizeElement);
  5928. noteShadow.appendChild(getStyleElement(NOTES_WEB_STYLESHEET));
  5929. noteShadow.appendChild(noteElement);
  5930. const notesElements = Array.from(document.querySelectorAll(NOTE_TAGNAME));
  5931. const noteId = Math.max.call(Math, 0, ...notesElements.map(noteElement => Number(noteElement.dataset.noteId))) + 1;
  5932. blockquoteElement.cite = "https://www.w3.org/TR/annotation-model/#selector(type=CssSelector,value=[data-single-file-note-refs~=\"" + noteId + "\"])";
  5933. noteElement.classList.add(NOTE_CLASS);
  5934. noteElement.classList.add(NOTE_ANCHORED_CLASS);
  5935. noteElement.classList.add(color);
  5936. noteElement.dataset.color = color;
  5937. mainElement.dir = "auto";
  5938. const boundingRectDocument = document.documentElement.getBoundingClientRect();
  5939. let positionX = NOTE_INITIAL_WIDTH + NOTE_INITIAL_POSITION_X - 1 - boundingRectDocument.x;
  5940. let positionY = NOTE_INITIAL_HEIGHT + NOTE_INITIAL_POSITION_Y - 1 - boundingRectDocument.y;
  5941. while (Array.from(document.elementsFromPoint(positionX - window.scrollX, positionY - window.scrollY)).find(element => element.tagName.toLowerCase() == NOTE_TAGNAME)) {
  5942. positionX += NOTE_INITIAL_POSITION_X;
  5943. positionY += NOTE_INITIAL_POSITION_Y;
  5944. }
  5945. noteElement.style.setProperty("left", (positionX - NOTE_INITIAL_WIDTH - 1) + "px");
  5946. noteElement.style.setProperty("top", (positionY - NOTE_INITIAL_HEIGHT - 1) + "px");
  5947. resizeElement.className = "note-resize";
  5948. resizeElement.ondragstart = event => event.preventDefault();
  5949. removeNoteElement.className = "note-remove";
  5950. removeNoteElement.src = BUTTON_CLOSE_URL;
  5951. removeNoteElement.ondragstart = event => event.preventDefault();
  5952. anchorIconElement.className = "note-anchor";
  5953. anchorIconElement.src = BUTTON_ANCHOR_URL;
  5954. anchorIconElement.ondragstart = event => event.preventDefault();
  5955. containerElement.dataset.noteId = noteId;
  5956. addNoteRef(document.documentElement, noteId);
  5957. attachNoteListeners(containerElement, true);
  5958. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  5959. noteElement.classList.add(NOTE_SELECTED_CLASS);
  5960. selectedNote = noteElement;
  5961. onUpdate(false);
  5962. }
  5963. function attachNoteListeners(containerElement, editable = false) {
  5964. const SELECT_PX_THRESHOLD = 4;
  5965. const COLLAPSING_NOTE_DELAY = 750;
  5966. const noteShadow = containerElement.shadowRoot;
  5967. const noteElement = noteShadow.childNodes[1];
  5968. const headerElement = noteShadow.querySelector("header");
  5969. const mainElement = noteShadow.querySelector("textarea");
  5970. const noteId = containerElement.dataset.noteId;
  5971. const resizeElement = noteShadow.querySelector(".note-resize");
  5972. const anchorIconElement = noteShadow.querySelector(".note-anchor");
  5973. const removeNoteElement = noteShadow.querySelector(".note-remove");
  5974. mainElement.readOnly = !editable;
  5975. if (!editable) {
  5976. anchorIconElement.style.setProperty("display", "none", "important");
  5977. } else {
  5978. anchorIconElement.style.removeProperty("display");
  5979. }
  5980. headerElement.ontouchstart = headerElement.onmousedown = event => {
  5981. if (event.target == headerElement) {
  5982. collapseNoteTimeout = setTimeout(() => {
  5983. noteElement.classList.toggle("note-collapsed");
  5984. hideMaskNote();
  5985. }, COLLAPSING_NOTE_DELAY);
  5986. event.preventDefault();
  5987. const position = getPosition(event);
  5988. const clientX = position.clientX;
  5989. const clientY = position.clientY;
  5990. const boundingRect = noteElement.getBoundingClientRect();
  5991. const deltaX = clientX - boundingRect.left;
  5992. const deltaY = clientY - boundingRect.top;
  5993. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  5994. document.documentElement.style.setProperty("user-select", "none", "important");
  5995. anchorElement = getAnchorElement(containerElement);
  5996. displayMaskNote();
  5997. selectNote(noteElement);
  5998. moveNote(event, deltaX, deltaY);
  5999. movingNoteMode = { event, deltaX, deltaY };
  6000. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  6001. clearTimeout(collapseNoteTimeout);
  6002. if (!movingNoteMode) {
  6003. movingNoteMode = { deltaX, deltaY };
  6004. }
  6005. movingNoteMode.event = event;
  6006. moveNote(event, deltaX, deltaY);
  6007. };
  6008. }
  6009. };
  6010. resizeElement.ontouchstart = resizeElement.onmousedown = event => {
  6011. event.preventDefault();
  6012. resizingNoteMode = true;
  6013. selectNote(noteElement);
  6014. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  6015. document.documentElement.style.setProperty("user-select", "none", "important");
  6016. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  6017. event.preventDefault();
  6018. const { clientX, clientY } = getPosition(event);
  6019. const boundingRectNote = noteElement.getBoundingClientRect();
  6020. noteElement.style.width = clientX - boundingRectNote.left + "px";
  6021. noteElement.style.height = clientY - boundingRectNote.top + "px";
  6022. };
  6023. };
  6024. anchorIconElement.ontouchend = anchorIconElement.onclick = event => {
  6025. event.preventDefault();
  6026. noteElement.classList.toggle(NOTE_ANCHORED_CLASS);
  6027. if (!noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  6028. deleteNoteRef(containerElement, noteId);
  6029. addNoteRef(document.documentElement, noteId);
  6030. }
  6031. onUpdate(false);
  6032. };
  6033. removeNoteElement.ontouchend = removeNoteElement.onclick = event => {
  6034. event.preventDefault();
  6035. deleteNoteRef(containerElement, noteId);
  6036. containerElement.remove();
  6037. };
  6038. noteElement.onmousedown = () => {
  6039. selectNote(noteElement);
  6040. };
  6041. function moveNote(event, deltaX, deltaY) {
  6042. event.preventDefault();
  6043. const { clientX, clientY } = getPosition(event);
  6044. noteElement.classList.add(NOTE_MOVING_CLASS);
  6045. if (editable) {
  6046. if (noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  6047. deleteNoteRef(containerElement, noteId);
  6048. anchorElement = getTarget(clientX, clientY) || document.documentElement;
  6049. addNoteRef(anchorElement, noteId);
  6050. } else {
  6051. anchorElement = document.documentElement;
  6052. }
  6053. }
  6054. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  6055. noteElement.style.setProperty("left", (clientX - deltaX) + "px");
  6056. noteElement.style.setProperty("top", (clientY - deltaY) + "px");
  6057. noteElement.style.setProperty("position", "fixed");
  6058. displayMaskNote();
  6059. }
  6060. function displayMaskNote() {
  6061. if (anchorElement == document.documentElement || anchorElement == document.documentElement) {
  6062. hideMaskNote();
  6063. } else {
  6064. const boundingRectAnchor = anchorElement.getBoundingClientRect();
  6065. maskNoteElement.classList.add(NOTE_MASK_MOVING_CLASS);
  6066. if (selectedNote) {
  6067. maskNoteElement.classList.add(selectedNote.dataset.color);
  6068. }
  6069. maskNoteElement.style.setProperty("top", (boundingRectAnchor.y - 3) + "px");
  6070. maskNoteElement.style.setProperty("left", (boundingRectAnchor.x - 3) + "px");
  6071. maskNoteElement.style.setProperty("width", (boundingRectAnchor.width + 3) + "px");
  6072. maskNoteElement.style.setProperty("height", (boundingRectAnchor.height + 3) + "px");
  6073. }
  6074. }
  6075. function hideMaskNote() {
  6076. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  6077. if (selectedNote) {
  6078. maskNoteElement.classList.remove(selectedNote.dataset.color);
  6079. }
  6080. }
  6081. function selectNote(noteElement) {
  6082. if (selectedNote) {
  6083. selectedNote.classList.remove(NOTE_SELECTED_CLASS);
  6084. maskNoteElement.classList.remove(selectedNote.dataset.color);
  6085. }
  6086. noteElement.classList.add(NOTE_SELECTED_CLASS);
  6087. noteElement.classList.add(noteElement.dataset.color);
  6088. selectedNote = noteElement;
  6089. }
  6090. function getTarget(clientX, clientY) {
  6091. const targets = Array.from(document.elementsFromPoint(clientX, clientY)).filter(element => element.matches("html *:not(" + NOTE_TAGNAME + "):not(." + MASK_CLASS + ")"));
  6092. if (!targets.includes(document.documentElement)) {
  6093. targets.push(document.documentElement);
  6094. }
  6095. let newTarget, target = targets[0], boundingRect = target.getBoundingClientRect();
  6096. newTarget = determineTargetElement("floor", target, clientX - boundingRect.left, getMatchedParents(target, "left"));
  6097. if (newTarget == target) {
  6098. newTarget = determineTargetElement("ceil", target, boundingRect.left + boundingRect.width - clientX, getMatchedParents(target, "right"));
  6099. }
  6100. if (newTarget == target) {
  6101. newTarget = determineTargetElement("floor", target, clientY - boundingRect.top, getMatchedParents(target, "top"));
  6102. }
  6103. if (newTarget == target) {
  6104. newTarget = determineTargetElement("ceil", target, boundingRect.top + boundingRect.height - clientY, getMatchedParents(target, "bottom"));
  6105. }
  6106. target = newTarget;
  6107. while (boundingRect = target && target.getBoundingClientRect(), boundingRect && boundingRect.width <= SELECT_PX_THRESHOLD && boundingRect.height <= SELECT_PX_THRESHOLD) {
  6108. target = target.parentElement;
  6109. }
  6110. return target;
  6111. }
  6112. function getMatchedParents(target, property) {
  6113. let element = target, matchedParent, parents = [];
  6114. do {
  6115. const boundingRect = element.getBoundingClientRect();
  6116. if (element.parentElement && !element.parentElement.tagName.toLowerCase() != NOTE_TAGNAME && !element.classList.contains(MASK_CLASS)) {
  6117. const parentBoundingRect = element.parentElement.getBoundingClientRect();
  6118. matchedParent = Math.abs(parentBoundingRect[property] - boundingRect[property]) <= SELECT_PX_THRESHOLD;
  6119. if (matchedParent) {
  6120. if (element.parentElement.clientWidth > SELECT_PX_THRESHOLD && element.parentElement.clientHeight > SELECT_PX_THRESHOLD &&
  6121. ((element.parentElement.clientWidth - element.clientWidth > SELECT_PX_THRESHOLD) || (element.parentElement.clientHeight - element.clientHeight > SELECT_PX_THRESHOLD))) {
  6122. parents.push(element.parentElement);
  6123. }
  6124. element = element.parentElement;
  6125. }
  6126. } else {
  6127. matchedParent = false;
  6128. }
  6129. } while (matchedParent && element);
  6130. return parents;
  6131. }
  6132. function determineTargetElement(roundingMethod, target, widthDistance, parents) {
  6133. if (Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) <= parents.length) {
  6134. target = parents[parents.length - Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) - 1];
  6135. }
  6136. return target;
  6137. }
  6138. }
  6139. function onMouseDown(event) {
  6140. if ((cuttingMode || cuttingOuterMode) && cuttingPath) {
  6141. event.preventDefault();
  6142. }
  6143. }
  6144. function onMouseUp(event) {
  6145. if (highlightSelectionMode) {
  6146. event.preventDefault();
  6147. highlightSelection();
  6148. onUpdate(false);
  6149. }
  6150. if (removeHighlightMode) {
  6151. event.preventDefault();
  6152. let element = event.target, done;
  6153. while (element && !done) {
  6154. if (element.classList.contains(HIGHLIGHT_CLASS)) {
  6155. document.querySelectorAll("." + HIGHLIGHT_CLASS + "[data-singlefile-highlight-id=" + JSON.stringify(element.dataset.singlefileHighlightId) + "]").forEach(highlightedElement => {
  6156. resetHighlightedElement(highlightedElement);
  6157. onUpdate(false);
  6158. });
  6159. done = true;
  6160. }
  6161. element = element.parentElement;
  6162. }
  6163. }
  6164. if (resizingNoteMode) {
  6165. event.preventDefault();
  6166. resizingNoteMode = false;
  6167. document.documentElement.style.removeProperty("user-select");
  6168. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  6169. document.documentElement.ontouchmove = onTouchMove;
  6170. document.documentElement.onmousemove = null;
  6171. onUpdate(false);
  6172. }
  6173. if (movingNoteMode) {
  6174. event.preventDefault();
  6175. anchorNote(movingNoteMode.event || event, selectedNote, movingNoteMode.deltaX, movingNoteMode.deltaY);
  6176. movingNoteMode = null;
  6177. document.documentElement.ontouchmove = onTouchMove;
  6178. document.documentElement.onmousemove = null;
  6179. onUpdate(false);
  6180. }
  6181. if ((cuttingMode || cuttingOuterMode) && cuttingPath) {
  6182. event.preventDefault();
  6183. if (event.ctrlKey) {
  6184. const element = cuttingPath[cuttingPathIndex];
  6185. element.classList.toggle(cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS);
  6186. } else {
  6187. validateCutElement(event.shiftKey);
  6188. }
  6189. }
  6190. if (collapseNoteTimeout) {
  6191. clearTimeout(collapseNoteTimeout);
  6192. collapseNoteTimeout = null;
  6193. }
  6194. }
  6195. function onMouseOver(event) {
  6196. if (cuttingMode || cuttingOuterMode) {
  6197. const target = event.target;
  6198. if (target.classList) {
  6199. let ancestorFound;
  6200. document.querySelectorAll("." + (cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS)).forEach(element => {
  6201. if (element == target || isAncestor(element, target) || isAncestor(target, element)) {
  6202. ancestorFound = element;
  6203. }
  6204. });
  6205. if (ancestorFound) {
  6206. cuttingPath = [ancestorFound];
  6207. } else {
  6208. cuttingPath = getParents(event.target);
  6209. }
  6210. cuttingPathIndex = 0;
  6211. highlightCutElement();
  6212. }
  6213. }
  6214. }
  6215. function onMouseOut() {
  6216. if (cuttingMode || cuttingOuterMode) {
  6217. if (cuttingPath) {
  6218. unhighlightCutElement();
  6219. cuttingPath = null;
  6220. }
  6221. }
  6222. }
  6223. function onTouchMove(event) {
  6224. if (cuttingMode || cuttingOuterMode) {
  6225. event.preventDefault();
  6226. const { clientX, clientY } = getPosition(event);
  6227. const target = document.elementFromPoint(clientX, clientY);
  6228. if (cuttingTouchTarget != target) {
  6229. onMouseOut();
  6230. if (target) {
  6231. cuttingTouchTarget = target;
  6232. onMouseOver({ target });
  6233. }
  6234. }
  6235. }
  6236. }
  6237. function onKeyDown(event) {
  6238. if (cuttingMode || cuttingOuterMode) {
  6239. if (event.code == "Tab") {
  6240. if (cuttingPath) {
  6241. const delta = event.shiftKey ? -1 : 1;
  6242. let element = cuttingPath[cuttingPathIndex];
  6243. let nextElement = cuttingPath[cuttingPathIndex + delta];
  6244. if (nextElement) {
  6245. let pathIndex = cuttingPathIndex + delta;
  6246. while (
  6247. nextElement &&
  6248. (
  6249. (delta == 1 &&
  6250. element.getBoundingClientRect().width >= nextElement.getBoundingClientRect().width &&
  6251. element.getBoundingClientRect().height >= nextElement.getBoundingClientRect().height) ||
  6252. (delta == -1 &&
  6253. element.getBoundingClientRect().width <= nextElement.getBoundingClientRect().width &&
  6254. element.getBoundingClientRect().height <= nextElement.getBoundingClientRect().height))) {
  6255. pathIndex += delta;
  6256. nextElement = cuttingPath[pathIndex];
  6257. }
  6258. if (nextElement && nextElement.classList && nextElement != document.body && nextElement != document.documentElement) {
  6259. unhighlightCutElement();
  6260. cuttingPathIndex = pathIndex;
  6261. highlightCutElement();
  6262. }
  6263. }
  6264. }
  6265. event.preventDefault();
  6266. }
  6267. if (event.code == "Space") {
  6268. if (cuttingPath) {
  6269. if (event.ctrlKey) {
  6270. const element = cuttingPath[cuttingPathIndex];
  6271. element.classList.add(cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS);
  6272. } else {
  6273. validateCutElement(event.shiftKey);
  6274. }
  6275. event.preventDefault();
  6276. }
  6277. }
  6278. if (event.code == "Escape") {
  6279. resetSelectedElements();
  6280. event.preventDefault();
  6281. }
  6282. if (event.key.toLowerCase() == "z" && event.ctrlKey) {
  6283. if (event.shiftKey) {
  6284. redoCutPage();
  6285. } else {
  6286. undoCutPage();
  6287. }
  6288. event.preventDefault();
  6289. }
  6290. }
  6291. if (event.key.toLowerCase() == "s" && event.ctrlKey) {
  6292. window.parent.postMessage(JSON.stringify({ "method": "savePage" }), "*");
  6293. event.preventDefault();
  6294. }
  6295. if (event.key.toLowerCase() == "p" && event.ctrlKey) {
  6296. printPage();
  6297. event.preventDefault();
  6298. }
  6299. }
  6300. function printPage() {
  6301. unhighlightCutElement();
  6302. resetSelectedElements();
  6303. window.print();
  6304. }
  6305. function highlightCutElement() {
  6306. const element = cuttingPath[cuttingPathIndex];
  6307. element.classList.add(cuttingMode ? CUT_HOVER_CLASS : CUT_OUTER_HOVER_CLASS);
  6308. }
  6309. function unhighlightCutElement() {
  6310. if (cuttingPath) {
  6311. const element = cuttingPath[cuttingPathIndex];
  6312. element.classList.remove(CUT_HOVER_CLASS);
  6313. element.classList.remove(CUT_OUTER_HOVER_CLASS);
  6314. }
  6315. }
  6316. function disableHighlight(doc = document) {
  6317. if (highlightColor) {
  6318. doc.documentElement.classList.remove(highlightColor + "-mode");
  6319. }
  6320. }
  6321. function undoCutPage() {
  6322. if (removedElementIndex) {
  6323. removedElements[removedElementIndex - 1].forEach(element => element.classList.remove(REMOVED_CONTENT_CLASS));
  6324. removedElementIndex--;
  6325. }
  6326. }
  6327. function redoCutPage() {
  6328. if (removedElementIndex < removedElements.length) {
  6329. removedElements[removedElementIndex].forEach(element => element.classList.add(REMOVED_CONTENT_CLASS));
  6330. removedElementIndex++;
  6331. }
  6332. }
  6333. function validateCutElement(invert) {
  6334. const selectedElement = cuttingPath[cuttingPathIndex];
  6335. if ((cuttingMode && !invert) || (cuttingOuterMode && invert)) {
  6336. if (document.documentElement != selectedElement && selectedElement.tagName.toLowerCase() != NOTE_TAGNAME) {
  6337. const elementsRemoved = [selectedElement].concat(...document.querySelectorAll("." + CUT_SELECTED_CLASS + ",." + CUT_SELECTED_CLASS + " *,." + CUT_HOVER_CLASS + " *"));
  6338. resetSelectedElements();
  6339. if (elementsRemoved.length) {
  6340. elementsRemoved.forEach(element => {
  6341. unhighlightCutElement();
  6342. if (element.tagName.toLowerCase() == NOTE_TAGNAME) {
  6343. resetAnchorNote(element);
  6344. } else {
  6345. element.classList.add(REMOVED_CONTENT_CLASS);
  6346. }
  6347. });
  6348. removedElements[removedElementIndex] = elementsRemoved;
  6349. removedElementIndex++;
  6350. removedElements.length = removedElementIndex;
  6351. onUpdate(false);
  6352. }
  6353. }
  6354. } else {
  6355. if (document.documentElement != selectedElement && selectedElement.tagName.toLowerCase() != NOTE_TAGNAME) {
  6356. const elements = [];
  6357. const searchSelector = "*:not(style):not(meta):not(." + REMOVED_CONTENT_CLASS + ")";
  6358. const elementsKept = [selectedElement].concat(...document.querySelectorAll("." + CUT_OUTER_SELECTED_CLASS));
  6359. document.body.querySelectorAll(searchSelector).forEach(element => {
  6360. let removed = true;
  6361. elementsKept.forEach(elementKept => removed = removed && (elementKept != element && !isAncestor(elementKept, element) && !isAncestor(element, elementKept)));
  6362. if (removed) {
  6363. if (element.tagName.toLowerCase() == NOTE_TAGNAME) {
  6364. resetAnchorNote(element);
  6365. } else {
  6366. elements.push(element);
  6367. }
  6368. }
  6369. });
  6370. elementsKept.forEach(elementKept => {
  6371. unhighlightCutElement();
  6372. const elementKeptRect = elementKept.getBoundingClientRect();
  6373. elementKept.querySelectorAll(searchSelector).forEach(descendant => {
  6374. const descendantRect = descendant.getBoundingClientRect();
  6375. if (descendantRect.width && descendantRect.height && (
  6376. descendantRect.left + descendantRect.width < elementKeptRect.left ||
  6377. descendantRect.right > elementKeptRect.right + elementKeptRect.width ||
  6378. descendantRect.top + descendantRect.height < elementKeptRect.top ||
  6379. descendantRect.bottom > elementKeptRect.bottom + elementKeptRect.height
  6380. )) {
  6381. elements.push(descendant);
  6382. }
  6383. });
  6384. });
  6385. resetSelectedElements();
  6386. if (elements.length) {
  6387. elements.forEach(element => element.classList.add(REMOVED_CONTENT_CLASS));
  6388. removedElements[removedElementIndex] = elements;
  6389. removedElementIndex++;
  6390. removedElements.length = removedElementIndex;
  6391. onUpdate(false);
  6392. }
  6393. }
  6394. }
  6395. }
  6396. function resetSelectedElements(doc = document) {
  6397. doc.querySelectorAll("." + CUT_OUTER_SELECTED_CLASS + ",." + CUT_SELECTED_CLASS).forEach(element => {
  6398. element.classList.remove(CUT_OUTER_SELECTED_CLASS);
  6399. element.classList.remove(CUT_SELECTED_CLASS);
  6400. });
  6401. }
  6402. function anchorNote(event, noteElement, deltaX, deltaY) {
  6403. event.preventDefault();
  6404. const { clientX, clientY } = getPosition(event);
  6405. document.documentElement.style.removeProperty("user-select");
  6406. noteElement.classList.remove(NOTE_MOVING_CLASS);
  6407. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  6408. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  6409. maskNoteElement.classList.remove(noteElement.dataset.color);
  6410. const headerElement = noteElement.querySelector("header");
  6411. headerElement.ontouchmove = document.documentElement.onmousemove = null;
  6412. let currentElement = anchorElement;
  6413. let positionedElement;
  6414. while (currentElement.parentElement && !positionedElement) {
  6415. if (!FORBIDDEN_TAG_NAMES.includes(currentElement.tagName.toLowerCase())) {
  6416. const currentElementStyle = getComputedStyle(currentElement);
  6417. if (currentElementStyle.position != "static") {
  6418. positionedElement = currentElement;
  6419. }
  6420. }
  6421. currentElement = currentElement.parentElement;
  6422. }
  6423. if (!positionedElement) {
  6424. positionedElement = document.documentElement;
  6425. }
  6426. const containerElement = noteElement.getRootNode().host;
  6427. if (positionedElement == document.documentElement) {
  6428. const firstMaskElement = document.querySelector("." + MASK_CLASS);
  6429. firstMaskElement.parentElement.insertBefore(containerElement, firstMaskElement);
  6430. } else {
  6431. positionedElement.appendChild(containerElement);
  6432. }
  6433. const boundingRectPositionedElement = positionedElement.getBoundingClientRect();
  6434. const stylePositionedElement = window.getComputedStyle(positionedElement);
  6435. const borderX = parseInt(stylePositionedElement.getPropertyValue("border-left-width"));
  6436. const borderY = parseInt(stylePositionedElement.getPropertyValue("border-top-width"));
  6437. noteElement.style.setProperty("position", "absolute");
  6438. noteElement.style.setProperty("left", (clientX - boundingRectPositionedElement.x - deltaX - borderX) + "px");
  6439. noteElement.style.setProperty("top", (clientY - boundingRectPositionedElement.y - deltaY - borderY) + "px");
  6440. }
  6441. function resetAnchorNote(containerElement) {
  6442. const noteId = containerElement.dataset.noteId;
  6443. const noteElement = containerElement.shadowRoot.childNodes[1];
  6444. noteElement.classList.remove(NOTE_ANCHORED_CLASS);
  6445. deleteNoteRef(containerElement, noteId);
  6446. addNoteRef(document.documentElement, noteId);
  6447. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  6448. }
  6449. function getPosition(event) {
  6450. if (event.touches && event.touches.length) {
  6451. const touch = event.touches[0];
  6452. return touch;
  6453. } else {
  6454. return event;
  6455. }
  6456. }
  6457. function highlightSelection() {
  6458. let highlightId = 0;
  6459. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(highlightedElement => highlightId = Math.max(highlightId, highlightedElement.dataset.singlefileHighlightId));
  6460. highlightId++;
  6461. const selection = window.getSelection();
  6462. const highlightedNodes = new Set();
  6463. for (let indexRange = 0; indexRange < selection.rangeCount; indexRange++) {
  6464. const range = selection.getRangeAt(indexRange);
  6465. if (!range.collapsed) {
  6466. if (range.commonAncestorContainer.nodeType == range.commonAncestorContainer.TEXT_NODE) {
  6467. let contentText = range.startContainer.splitText(range.startOffset);
  6468. contentText = contentText.splitText(range.endOffset);
  6469. addHighLightedNode(contentText.previousSibling);
  6470. } else {
  6471. const treeWalker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
  6472. let highlightNodes;
  6473. while (treeWalker.nextNode()) {
  6474. if (highlightNodes && !treeWalker.currentNode.contains(range.endContainer)) {
  6475. addHighLightedNode(treeWalker.currentNode);
  6476. }
  6477. if (treeWalker.currentNode == range.startContainer) {
  6478. if (range.startContainer.nodeType == range.startContainer.TEXT_NODE) {
  6479. const contentText = range.startContainer.splitText(range.startOffset);
  6480. treeWalker.nextNode();
  6481. addHighLightedNode(contentText);
  6482. } else {
  6483. addHighLightedNode(range.startContainer.childNodes[range.startOffset]);
  6484. }
  6485. highlightNodes = true;
  6486. }
  6487. if (treeWalker.currentNode == range.endContainer) {
  6488. if (range.endContainer.nodeType == range.endContainer.TEXT_NODE) {
  6489. const contentText = range.endContainer.splitText(range.endOffset);
  6490. treeWalker.nextNode();
  6491. addHighLightedNode(contentText.previousSibling);
  6492. } else {
  6493. addHighLightedNode(range.endContainer.childNodes[range.endOffset]);
  6494. }
  6495. highlightNodes = false;
  6496. }
  6497. }
  6498. range.collapse();
  6499. }
  6500. }
  6501. }
  6502. highlightedNodes.forEach(node => highlightNode(node));
  6503. function addHighLightedNode(node) {
  6504. if (node && node.textContent.trim()) {
  6505. if (node.nodeType == node.TEXT_NODE && node.parentElement.childNodes.length == 1 && node.parentElement.classList.contains(HIGHLIGHT_CLASS)) {
  6506. highlightedNodes.add(node.parentElement);
  6507. } else {
  6508. highlightedNodes.add(node);
  6509. }
  6510. }
  6511. }
  6512. function highlightNode(node) {
  6513. if (node.nodeType == node.ELEMENT_NODE) {
  6514. resetHighlightedElement(node);
  6515. node.classList.add(HIGHLIGHT_CLASS);
  6516. node.classList.add(highlightColor);
  6517. node.dataset.singlefileHighlightId = highlightId;
  6518. } else if (node.parentElement) {
  6519. highlightTextNode(node);
  6520. }
  6521. }
  6522. function highlightTextNode(node) {
  6523. const spanElement = document.createElement("span");
  6524. spanElement.classList.add(HIGHLIGHT_CLASS);
  6525. spanElement.classList.add(highlightColor);
  6526. spanElement.textContent = node.textContent;
  6527. spanElement.dataset.singlefileHighlightId = highlightId;
  6528. node.parentNode.replaceChild(spanElement, node);
  6529. return spanElement;
  6530. }
  6531. }
  6532. function getParents(element) {
  6533. const path = [];
  6534. while (element) {
  6535. path.push(element);
  6536. element = element.parentElement;
  6537. }
  6538. return path;
  6539. }
  6540. function formatPage(applySystemTheme) {
  6541. if (pageCompressContent) {
  6542. serializeShadowRoots(document);
  6543. previousContent = document.documentElement.cloneNode(true);
  6544. deserializeShadowRoots(document);
  6545. } else {
  6546. previousContent = getContent(false, []);
  6547. }
  6548. const shadowRoots = {};
  6549. const classesToPreserve = ["single-file-highlight", "single-file-highlight-yellow", "single-file-highlight-green", "single-file-highlight-pink", "single-file-highlight-blue"];
  6550. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  6551. shadowRoots[containerElement.dataset.noteId] = containerElement.shadowRoot;
  6552. const className = "singlefile-note-id-" + containerElement.dataset.noteId;
  6553. containerElement.classList.add(className);
  6554. classesToPreserve.push(className);
  6555. });
  6556. const article = new Readability(document, { classesToPreserve }).parse();
  6557. removedElements = [];
  6558. removedElementIndex = 0;
  6559. document.body.innerHTML = "";
  6560. const domParser = new DOMParser();
  6561. const doc = domParser.parseFromString(article.content, "text/html");
  6562. const contentEditable = document.body.contentEditable;
  6563. document.documentElement.replaceChild(doc.body, document.body);
  6564. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  6565. const noteId = (Array.from(containerElement.classList).find(className => /singlefile-note-id-\d+/.test(className))).split("singlefile-note-id-")[1];
  6566. containerElement.classList.remove("singlefile-note-id-" + noteId);
  6567. containerElement.dataset.noteId = noteId;
  6568. if (!containerElement.shadowRoot) {
  6569. containerElement.attachShadow({ mode: "open" });
  6570. containerElement.shadowRoot.appendChild(shadowRoots[noteId]);
  6571. }
  6572. });
  6573. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => shadowRoots[containerElement.dataset.noteId].childNodes.forEach(node => containerElement.shadowRoot.appendChild(node)));
  6574. document.body.contentEditable = contentEditable;
  6575. document.head.querySelectorAll("style").forEach(styleElement => styleElement.remove());
  6576. const styleElement = document.createElement("style");
  6577. styleElement.textContent = STYLE_FORMATTED_PAGE;
  6578. document.head.appendChild(styleElement);
  6579. document.body.classList.add("moz-reader-content");
  6580. document.body.classList.add("content-width6");
  6581. document.body.classList.add("reader-show-element");
  6582. document.body.classList.add("sans-serif");
  6583. document.body.classList.add("container");
  6584. document.body.classList.add("line-height4");
  6585. const prefersColorSchemeDark = matchMedia("(prefers-color-scheme: dark)");
  6586. if (applySystemTheme && prefersColorSchemeDark && prefersColorSchemeDark.matches) {
  6587. document.body.classList.add("dark");
  6588. }
  6589. document.body.style.setProperty("display", "block");
  6590. document.body.style.setProperty("padding", "24px");
  6591. const titleElement = document.createElement("h1");
  6592. titleElement.classList.add("reader-title");
  6593. titleElement.textContent = article.title;
  6594. document.body.insertBefore(titleElement, document.body.firstChild);
  6595. document.querySelectorAll("a[href]").forEach(element => {
  6596. const href = element.getAttribute("href").trim();
  6597. if (href.startsWith(document.baseURI + "#")) {
  6598. element.setAttribute("href", href.substring(document.baseURI.length));
  6599. }
  6600. });
  6601. document.documentElement.appendChild(getStyleElement(HIGHLIGHTS_WEB_STYLESHEET));
  6602. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  6603. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  6604. reflowNotes();
  6605. onUpdate(false);
  6606. }
  6607. async function cancelFormatPage() {
  6608. if (previousContent) {
  6609. const contentEditable = document.body.contentEditable;
  6610. if (pageCompressContent) {
  6611. document.replaceChild(previousContent, document.documentElement);
  6612. deserializeShadowRoots(document);
  6613. await initPage();
  6614. } else {
  6615. await init({ content: previousContent }, { reset: true });
  6616. }
  6617. document.body.contentEditable = contentEditable;
  6618. onUpdate(false);
  6619. previousContent = null;
  6620. }
  6621. }
  6622. function getContent(compressHTML, updatedResources) {
  6623. unhighlightCutElement();
  6624. serializeShadowRoots(document);
  6625. const doc = document.cloneNode(true);
  6626. disableHighlight(doc);
  6627. resetSelectedElements(doc);
  6628. deserializeShadowRoots(doc);
  6629. deserializeShadowRoots(document);
  6630. doc.documentElement.classList.remove(CUT_MODE_CLASS);
  6631. doc.querySelectorAll("[" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "]").forEach(element => {
  6632. element.textContent = element.getAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  6633. element.removeAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  6634. });
  6635. doc.querySelectorAll("." + MASK_CLASS + ", " + singlefile.helper.INFOBAR_TAGNAME + ", ." + REMOVED_CONTENT_CLASS).forEach(maskElement => maskElement.remove());
  6636. if (includeInfobar) {
  6637. singlefile.helper.appendInfobar(doc, singlefile.helper.extractInfobarData(doc));
  6638. }
  6639. doc.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  6640. doc.querySelectorAll(`template[${SHADOWROOT_ATTRIBUTE_NAME}]`).forEach(templateElement => {
  6641. const noteElement = templateElement.querySelector("." + NOTE_CLASS);
  6642. if (noteElement) {
  6643. noteElement.classList.remove(NOTE_HIDDEN_CLASS);
  6644. }
  6645. const mainElement = templateElement.querySelector("textarea");
  6646. if (mainElement) {
  6647. mainElement.textContent = mainElement.value;
  6648. }
  6649. });
  6650. doc.querySelectorAll("iframe").forEach(element => {
  6651. const pointerEvents = "pointer-events";
  6652. element.style.setProperty(pointerEvents, element.style.getPropertyValue("-sf-" + pointerEvents), element.style.getPropertyPriority("-sf-" + pointerEvents));
  6653. element.style.removeProperty("-sf-" + pointerEvents);
  6654. });
  6655. doc.body.removeAttribute("contentEditable");
  6656. const newResources = Object.keys(updatedResources).filter(url => updatedResources[url].type == "stylesheet").map(url => updatedResources[url]);
  6657. newResources.forEach(resource => {
  6658. const element = doc.createElement("style");
  6659. doc.body.appendChild(element);
  6660. element.textContent = resource.content;
  6661. });
  6662. if (pageCompressContent) {
  6663. const pageFilename = pageResources
  6664. .filter(resource => resource.filename.endsWith("index.html"))
  6665. .sort((resourceLeft, resourceRight) => resourceLeft.filename.length - resourceRight.filename.length)[0].filename;
  6666. const resources = pageResources.filter(resource => resource.parentResources.includes(pageFilename));
  6667. doc.querySelectorAll("[src]").forEach(element => resources.forEach(resource => {
  6668. if (element.src == resource.content) {
  6669. element.src = resource.name;
  6670. }
  6671. }));
  6672. let content = singlefile.helper.serialize(doc, compressHTML);
  6673. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  6674. resources.forEach(resource => {
  6675. const searchRegExp = new RegExp(resource.content.replace(REGEXP_ESCAPE, "\\$1"), "g");
  6676. const position = content.search(searchRegExp);
  6677. if (position != -1) {
  6678. content = content.replace(searchRegExp, resource.name);
  6679. }
  6680. });
  6681. return content + "<script " + SCRIPT_TEMPLATE_SHADOW_ROOT + ">" + getEmbedScript() + "</script>";
  6682. } else {
  6683. return singlefile.helper.serialize(doc, compressHTML) + "<script " + SCRIPT_TEMPLATE_SHADOW_ROOT + ">" + getEmbedScript() + "</script>";
  6684. }
  6685. }
  6686. function onUpdate(saved) {
  6687. window.parent.postMessage(JSON.stringify({ "method": "onUpdate", saved }), "*");
  6688. }
  6689. function waitResourcesLoad() {
  6690. return new Promise(resolve => {
  6691. let counterMutations = 0;
  6692. const done = () => {
  6693. observer.disconnect();
  6694. resolve();
  6695. };
  6696. let timeoutInit = setTimeout(done, 100);
  6697. const observer = new MutationObserver(() => {
  6698. if (counterMutations < 20) {
  6699. counterMutations++;
  6700. clearTimeout(timeoutInit);
  6701. timeoutInit = setTimeout(done, 100);
  6702. } else {
  6703. done();
  6704. }
  6705. });
  6706. observer.observe(document, { subtree: true, childList: true, attributes: true });
  6707. });
  6708. }
  6709. function reflowNotes() {
  6710. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  6711. const noteElement = containerElement.shadowRoot.querySelector("." + NOTE_CLASS);
  6712. const noteBoundingRect = noteElement.getBoundingClientRect();
  6713. const anchorElement = getAnchorElement(containerElement);
  6714. const anchorBoundingRect = anchorElement.getBoundingClientRect();
  6715. const maxX = anchorBoundingRect.x + Math.max(0, anchorBoundingRect.width - noteBoundingRect.width);
  6716. const minX = anchorBoundingRect.x;
  6717. const maxY = anchorBoundingRect.y + Math.max(0, anchorBoundingRect.height - NOTE_HEADER_HEIGHT);
  6718. const minY = anchorBoundingRect.y;
  6719. let left = parseInt(noteElement.style.getPropertyValue("left"));
  6720. let top = parseInt(noteElement.style.getPropertyValue("top"));
  6721. if (noteBoundingRect.x > maxX) {
  6722. left -= noteBoundingRect.x - maxX;
  6723. }
  6724. if (noteBoundingRect.x < minX) {
  6725. left += minX - noteBoundingRect.x;
  6726. }
  6727. if (noteBoundingRect.y > maxY) {
  6728. top -= noteBoundingRect.y - maxY;
  6729. }
  6730. if (noteBoundingRect.y < minY) {
  6731. top += minY - noteBoundingRect.y;
  6732. }
  6733. noteElement.style.setProperty("position", "absolute");
  6734. noteElement.style.setProperty("left", left + "px");
  6735. noteElement.style.setProperty("top", top + "px");
  6736. });
  6737. }
  6738. function resetHighlightedElement(element) {
  6739. element.classList.remove(HIGHLIGHT_CLASS);
  6740. element.classList.remove("single-file-highlight-yellow");
  6741. element.classList.remove("single-file-highlight-pink");
  6742. element.classList.remove("single-file-highlight-blue");
  6743. element.classList.remove("single-file-highlight-green");
  6744. delete element.dataset.singlefileHighlightId;
  6745. }
  6746. function serializeShadowRoots(node) {
  6747. node.querySelectorAll("*").forEach(element => {
  6748. const shadowRoot = getShadowRoot(element);
  6749. if (shadowRoot) {
  6750. serializeShadowRoots(shadowRoot);
  6751. const templateElement = document.createElement("template");
  6752. templateElement.setAttribute(SHADOWROOT_ATTRIBUTE_NAME, "open");
  6753. Array.from(shadowRoot.childNodes).forEach(childNode => templateElement.appendChild(childNode));
  6754. element.appendChild(templateElement);
  6755. }
  6756. });
  6757. }
  6758. function deserializeShadowRoots(node) {
  6759. node.querySelectorAll(`template[${SHADOWROOT_ATTRIBUTE_NAME}]`).forEach(element => {
  6760. if (element.parentElement) {
  6761. let shadowRoot = getShadowRoot(element.parentElement);
  6762. if (shadowRoot) {
  6763. Array.from(element.childNodes).forEach(node => shadowRoot.appendChild(node));
  6764. element.remove();
  6765. } else {
  6766. try {
  6767. shadowRoot = element.parentElement.attachShadow({ mode: "open" });
  6768. const contentDocument = (new DOMParser()).parseFromString(element.innerHTML, "text/html");
  6769. Array.from(contentDocument.head.childNodes).forEach(node => shadowRoot.appendChild(node));
  6770. Array.from(contentDocument.body.childNodes).forEach(node => shadowRoot.appendChild(node));
  6771. } catch (error) {
  6772. // ignored
  6773. }
  6774. }
  6775. if (shadowRoot) {
  6776. deserializeShadowRoots(shadowRoot);
  6777. }
  6778. }
  6779. });
  6780. }
  6781. function getMaskElement(className, containerClassName) {
  6782. let maskElement = document.documentElement.querySelector("." + className);
  6783. if (!maskElement) {
  6784. maskElement = document.createElement("div");
  6785. const maskContainerElement = document.createElement("div");
  6786. if (containerClassName) {
  6787. maskContainerElement.classList.add(containerClassName);
  6788. }
  6789. maskContainerElement.classList.add(MASK_CLASS);
  6790. const firstNote = document.querySelector(NOTE_TAGNAME);
  6791. if (firstNote && firstNote.parentElement == document.documentElement) {
  6792. document.documentElement.insertBefore(maskContainerElement, firstNote);
  6793. } else {
  6794. document.documentElement.appendChild(maskContainerElement);
  6795. }
  6796. maskElement.classList.add(className);
  6797. const maskShadow = maskContainerElement.attachShadow({ mode: "open" });
  6798. maskShadow.appendChild(getStyleElement(MASK_WEB_STYLESHEET));
  6799. maskShadow.appendChild(maskElement);
  6800. return maskElement;
  6801. }
  6802. }
  6803. function getEmbedScript() {
  6804. return minifyText(`(() => {
  6805. document.currentScript.remove();
  6806. const processNode = node => {
  6807. node.querySelectorAll("template[${SHADOWROOT_ATTRIBUTE_NAME}]").forEach(element=>{
  6808. let shadowRoot = getShadowRoot(element.parentElement);
  6809. if (!shadowRoot) {
  6810. try {
  6811. shadowRoot = element.parentElement.attachShadow({mode:element.getAttribute("${SHADOWROOT_ATTRIBUTE_NAME}")});
  6812. shadowRoot.innerHTML = element.innerHTML;
  6813. element.remove();
  6814. } catch (error) {}
  6815. if (shadowRoot) {
  6816. processNode(shadowRoot);
  6817. }
  6818. }
  6819. })
  6820. };
  6821. const FORBIDDEN_TAG_NAMES = ${JSON.stringify(FORBIDDEN_TAG_NAMES)};
  6822. const NOTE_TAGNAME = ${JSON.stringify(NOTE_TAGNAME)};
  6823. const NOTE_CLASS = ${JSON.stringify(NOTE_CLASS)};
  6824. const NOTE_ANCHORED_CLASS = ${JSON.stringify(NOTE_ANCHORED_CLASS)};
  6825. const NOTE_SELECTED_CLASS = ${JSON.stringify(NOTE_SELECTED_CLASS)};
  6826. const NOTE_MOVING_CLASS = ${JSON.stringify(NOTE_MOVING_CLASS)};
  6827. const NOTE_MASK_MOVING_CLASS = ${JSON.stringify(NOTE_MASK_MOVING_CLASS)};
  6828. const MASK_CLASS = ${JSON.stringify(MASK_CLASS)};
  6829. const HIGHLIGHT_CLASS = ${JSON.stringify(HIGHLIGHT_CLASS)};
  6830. const NOTES_WEB_STYLESHEET = ${JSON.stringify(NOTES_WEB_STYLESHEET)};
  6831. const MASK_WEB_STYLESHEET = ${JSON.stringify(MASK_WEB_STYLESHEET)};
  6832. const NOTE_HEADER_HEIGHT = ${JSON.stringify(NOTE_HEADER_HEIGHT)};
  6833. const PAGE_MASK_ACTIVE_CLASS = ${JSON.stringify(PAGE_MASK_ACTIVE_CLASS)};
  6834. const REMOVED_CONTENT_CLASS = ${JSON.stringify(REMOVED_CONTENT_CLASS)};
  6835. const reflowNotes = ${minifyText(reflowNotes.toString())};
  6836. const addNoteRef = ${minifyText(addNoteRef.toString())};
  6837. const deleteNoteRef = ${minifyText(deleteNoteRef.toString())};
  6838. const getNoteRefs = ${minifyText(getNoteRefs.toString())};
  6839. const setNoteRefs = ${minifyText(setNoteRefs.toString())};
  6840. const getAnchorElement = ${minifyText(getAnchorElement.toString())};
  6841. const getMaskElement = ${minifyText(getMaskElement.toString())};
  6842. const getStyleElement = ${minifyText(getStyleElement.toString())};
  6843. const attachNoteListeners = ${minifyText(attachNoteListeners.toString())};
  6844. const anchorNote = ${minifyText(anchorNote.toString())};
  6845. const getPosition = ${minifyText(getPosition.toString())};
  6846. const onMouseUp = ${minifyText(onMouseUp.toString())};
  6847. const getShadowRoot = ${minifyText(getShadowRoot.toString())};
  6848. const waitResourcesLoad = ${minifyText(waitResourcesLoad.toString())};
  6849. const maskNoteElement = getMaskElement(${JSON.stringify(NOTE_MASK_CLASS)});
  6850. const maskPageElement = getMaskElement(${JSON.stringify(PAGE_MASK_CLASS)}, ${JSON.stringify(PAGE_MASK_CONTAINER_CLASS)});
  6851. let selectedNote, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, collapseNoteTimeout, cuttingMode, cuttingOuterMode;
  6852. window.onresize = reflowNotes;
  6853. window.onUpdate = () => {};
  6854. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  6855. processNode(document);
  6856. reflowNotes();
  6857. document.querySelectorAll(${JSON.stringify(NOTE_TAGNAME)}).forEach(noteElement => attachNoteListeners(noteElement));
  6858. if (document.documentElement.dataset.sfz !== undefined) {
  6859. waitResourcesLoad().then(reflowNotes);
  6860. }
  6861. })()`);
  6862. }
  6863. function getStyleElement(stylesheet) {
  6864. const linkElement = document.createElement("style");
  6865. linkElement.textContent = stylesheet;
  6866. return linkElement;
  6867. }
  6868. function getAnchorElement(containerElement) {
  6869. return document.querySelector("[data-single-file-note-refs~=\"" + containerElement.dataset.noteId + "\"]") || document.documentElement;
  6870. }
  6871. function addNoteRef(anchorElement, noteId) {
  6872. const noteRefs = getNoteRefs(anchorElement);
  6873. noteRefs.push(noteId);
  6874. setNoteRefs(anchorElement, noteRefs);
  6875. }
  6876. function deleteNoteRef(containerElement, noteId) {
  6877. const anchorElement = getAnchorElement(containerElement);
  6878. const noteRefs = getNoteRefs(anchorElement).filter(noteRefs => noteRefs != noteId);
  6879. if (noteRefs.length) {
  6880. setNoteRefs(anchorElement, noteRefs);
  6881. } else {
  6882. delete anchorElement.dataset.singleFileNoteRefs;
  6883. }
  6884. }
  6885. function getNoteRefs(anchorElement) {
  6886. return anchorElement.dataset.singleFileNoteRefs ? anchorElement.dataset.singleFileNoteRefs.split(" ") : [];
  6887. }
  6888. function setNoteRefs(anchorElement, noteRefs) {
  6889. anchorElement.dataset.singleFileNoteRefs = noteRefs.join(" ");
  6890. }
  6891. function minifyText(text) {
  6892. return text.replace(/[\n\t\s]+/g, " ");
  6893. }
  6894. function isAncestor(element, otherElement) {
  6895. return otherElement.parentElement && (element == otherElement.parentElement || isAncestor(element, otherElement.parentElement));
  6896. }
  6897. function getShadowRoot(element) {
  6898. const chrome = window.chrome;
  6899. if (element.openOrClosedShadowRoot) {
  6900. return element.openOrClosedShadowRoot;
  6901. } else if (chrome && chrome.dom && chrome.dom.openOrClosedShadowRoot) {
  6902. try {
  6903. return chrome.dom.openOrClosedShadowRoot(element);
  6904. } catch (error) {
  6905. return element.shadowRoot;
  6906. }
  6907. } else {
  6908. return element.shadowRoot;
  6909. }
  6910. }
  6911. function detectSavedPage(document) {
  6912. const firstDocumentChild = document.documentElement.firstChild;
  6913. return firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  6914. (firstDocumentChild.textContent.includes(COMMENT_HEADER) || firstDocumentChild.textContent.includes(COMMENT_HEADER_LEGACY));
  6915. }
  6916. })(typeof globalThis == "object" ? globalThis : window);
  6917. })();