browser.min.js 508 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734
  1. "use strict";
  2. var ZenFS = (() => {
  3. var __create = Object.create;
  4. var __defProp = Object.defineProperty;
  5. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  6. var __getOwnPropNames = Object.getOwnPropertyNames;
  7. var __getProtoOf = Object.getPrototypeOf;
  8. var __hasOwnProp = Object.prototype.hasOwnProperty;
  9. var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  10. var __commonJS = (cb, mod) => function __require() {
  11. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  12. };
  13. var __export = (target, all) => {
  14. for (var name in all)
  15. __defProp(target, name, { get: all[name], enumerable: true });
  16. };
  17. var __copyProps = (to, from, except, desc) => {
  18. if (from && typeof from === "object" || typeof from === "function") {
  19. for (let key of __getOwnPropNames(from))
  20. if (!__hasOwnProp.call(to, key) && key !== except)
  21. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  22. }
  23. return to;
  24. };
  25. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  26. // If the importer is in node compatibility mode or this is not an ESM
  27. // file that has been converted to a CommonJS file using a Babel-
  28. // compatible transform (i.e. "__esModule" has not been set), then set
  29. // "default" to the CommonJS "module.exports" for node compatibility.
  30. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  31. mod
  32. ));
  33. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  34. // node_modules/base64-js/index.js
  35. var require_base64_js = __commonJS({
  36. "node_modules/base64-js/index.js"(exports) {
  37. "use strict";
  38. exports.byteLength = byteLength;
  39. exports.toByteArray = toByteArray;
  40. exports.fromByteArray = fromByteArray;
  41. var lookup = [];
  42. var revLookup = [];
  43. var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
  44. var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  45. for (i = 0, len = code.length; i < len; ++i) {
  46. lookup[i] = code[i];
  47. revLookup[code.charCodeAt(i)] = i;
  48. }
  49. var i;
  50. var len;
  51. revLookup["-".charCodeAt(0)] = 62;
  52. revLookup["_".charCodeAt(0)] = 63;
  53. function getLens(b64) {
  54. var len2 = b64.length;
  55. if (len2 % 4 > 0) {
  56. throw new Error("Invalid string. Length must be a multiple of 4");
  57. }
  58. var validLen = b64.indexOf("=");
  59. if (validLen === -1) validLen = len2;
  60. var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
  61. return [validLen, placeHoldersLen];
  62. }
  63. __name(getLens, "getLens");
  64. function byteLength(b64) {
  65. var lens = getLens(b64);
  66. var validLen = lens[0];
  67. var placeHoldersLen = lens[1];
  68. return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  69. }
  70. __name(byteLength, "byteLength");
  71. function _byteLength(b64, validLen, placeHoldersLen) {
  72. return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  73. }
  74. __name(_byteLength, "_byteLength");
  75. function toByteArray(b64) {
  76. var tmp;
  77. var lens = getLens(b64);
  78. var validLen = lens[0];
  79. var placeHoldersLen = lens[1];
  80. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
  81. var curByte = 0;
  82. var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
  83. var i2;
  84. for (i2 = 0; i2 < len2; i2 += 4) {
  85. tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
  86. arr[curByte++] = tmp >> 16 & 255;
  87. arr[curByte++] = tmp >> 8 & 255;
  88. arr[curByte++] = tmp & 255;
  89. }
  90. if (placeHoldersLen === 2) {
  91. tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
  92. arr[curByte++] = tmp & 255;
  93. }
  94. if (placeHoldersLen === 1) {
  95. tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
  96. arr[curByte++] = tmp >> 8 & 255;
  97. arr[curByte++] = tmp & 255;
  98. }
  99. return arr;
  100. }
  101. __name(toByteArray, "toByteArray");
  102. function tripletToBase64(num) {
  103. return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
  104. }
  105. __name(tripletToBase64, "tripletToBase64");
  106. function encodeChunk(uint8, start, end) {
  107. var tmp;
  108. var output = [];
  109. for (var i2 = start; i2 < end; i2 += 3) {
  110. tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
  111. output.push(tripletToBase64(tmp));
  112. }
  113. return output.join("");
  114. }
  115. __name(encodeChunk, "encodeChunk");
  116. function fromByteArray(uint8) {
  117. var tmp;
  118. var len2 = uint8.length;
  119. var extraBytes = len2 % 3;
  120. var parts = [];
  121. var maxChunkLength = 16383;
  122. for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
  123. parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
  124. }
  125. if (extraBytes === 1) {
  126. tmp = uint8[len2 - 1];
  127. parts.push(
  128. lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
  129. );
  130. } else if (extraBytes === 2) {
  131. tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
  132. parts.push(
  133. lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
  134. );
  135. }
  136. return parts.join("");
  137. }
  138. __name(fromByteArray, "fromByteArray");
  139. }
  140. });
  141. // node_modules/ieee754/index.js
  142. var require_ieee754 = __commonJS({
  143. "node_modules/ieee754/index.js"(exports) {
  144. exports.read = function(buffer, offset, isLE, mLen, nBytes) {
  145. var e, m;
  146. var eLen = nBytes * 8 - mLen - 1;
  147. var eMax = (1 << eLen) - 1;
  148. var eBias = eMax >> 1;
  149. var nBits = -7;
  150. var i = isLE ? nBytes - 1 : 0;
  151. var d = isLE ? -1 : 1;
  152. var s = buffer[offset + i];
  153. i += d;
  154. e = s & (1 << -nBits) - 1;
  155. s >>= -nBits;
  156. nBits += eLen;
  157. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
  158. }
  159. m = e & (1 << -nBits) - 1;
  160. e >>= -nBits;
  161. nBits += mLen;
  162. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
  163. }
  164. if (e === 0) {
  165. e = 1 - eBias;
  166. } else if (e === eMax) {
  167. return m ? NaN : (s ? -1 : 1) * Infinity;
  168. } else {
  169. m = m + Math.pow(2, mLen);
  170. e = e - eBias;
  171. }
  172. return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  173. };
  174. exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
  175. var e, m, c;
  176. var eLen = nBytes * 8 - mLen - 1;
  177. var eMax = (1 << eLen) - 1;
  178. var eBias = eMax >> 1;
  179. var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  180. var i = isLE ? 0 : nBytes - 1;
  181. var d = isLE ? 1 : -1;
  182. var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  183. value = Math.abs(value);
  184. if (isNaN(value) || value === Infinity) {
  185. m = isNaN(value) ? 1 : 0;
  186. e = eMax;
  187. } else {
  188. e = Math.floor(Math.log(value) / Math.LN2);
  189. if (value * (c = Math.pow(2, -e)) < 1) {
  190. e--;
  191. c *= 2;
  192. }
  193. if (e + eBias >= 1) {
  194. value += rt / c;
  195. } else {
  196. value += rt * Math.pow(2, 1 - eBias);
  197. }
  198. if (value * c >= 2) {
  199. e++;
  200. c /= 2;
  201. }
  202. if (e + eBias >= eMax) {
  203. m = 0;
  204. e = eMax;
  205. } else if (e + eBias >= 1) {
  206. m = (value * c - 1) * Math.pow(2, mLen);
  207. e = e + eBias;
  208. } else {
  209. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  210. e = 0;
  211. }
  212. }
  213. for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
  214. }
  215. e = e << mLen | m;
  216. eLen += mLen;
  217. for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
  218. }
  219. buffer[offset + i - d] |= s * 128;
  220. };
  221. }
  222. });
  223. // node_modules/buffer/index.js
  224. var require_buffer = __commonJS({
  225. "node_modules/buffer/index.js"(exports) {
  226. "use strict";
  227. var base64 = require_base64_js();
  228. var ieee754 = require_ieee754();
  229. var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
  230. exports.Buffer = Buffer4;
  231. exports.SlowBuffer = SlowBuffer;
  232. exports.INSPECT_MAX_BYTES = 50;
  233. var K_MAX_LENGTH = 2147483647;
  234. exports.kMaxLength = K_MAX_LENGTH;
  235. Buffer4.TYPED_ARRAY_SUPPORT = typedArraySupport();
  236. if (!Buffer4.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
  237. console.error(
  238. "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
  239. );
  240. }
  241. function typedArraySupport() {
  242. try {
  243. const arr = new Uint8Array(1);
  244. const proto = { foo: /* @__PURE__ */ __name(function() {
  245. return 42;
  246. }, "foo") };
  247. Object.setPrototypeOf(proto, Uint8Array.prototype);
  248. Object.setPrototypeOf(arr, proto);
  249. return arr.foo() === 42;
  250. } catch (e) {
  251. return false;
  252. }
  253. }
  254. __name(typedArraySupport, "typedArraySupport");
  255. Object.defineProperty(Buffer4.prototype, "parent", {
  256. enumerable: true,
  257. get: /* @__PURE__ */ __name(function() {
  258. if (!Buffer4.isBuffer(this)) return void 0;
  259. return this.buffer;
  260. }, "get")
  261. });
  262. Object.defineProperty(Buffer4.prototype, "offset", {
  263. enumerable: true,
  264. get: /* @__PURE__ */ __name(function() {
  265. if (!Buffer4.isBuffer(this)) return void 0;
  266. return this.byteOffset;
  267. }, "get")
  268. });
  269. function createBuffer(length) {
  270. if (length > K_MAX_LENGTH) {
  271. throw new RangeError('The value "' + length + '" is invalid for option "size"');
  272. }
  273. const buf = new Uint8Array(length);
  274. Object.setPrototypeOf(buf, Buffer4.prototype);
  275. return buf;
  276. }
  277. __name(createBuffer, "createBuffer");
  278. function Buffer4(arg, encodingOrOffset, length) {
  279. if (typeof arg === "number") {
  280. if (typeof encodingOrOffset === "string") {
  281. throw new TypeError(
  282. 'The "string" argument must be of type string. Received type number'
  283. );
  284. }
  285. return allocUnsafe(arg);
  286. }
  287. return from(arg, encodingOrOffset, length);
  288. }
  289. __name(Buffer4, "Buffer");
  290. Buffer4.poolSize = 8192;
  291. function from(value, encodingOrOffset, length) {
  292. if (typeof value === "string") {
  293. return fromString(value, encodingOrOffset);
  294. }
  295. if (ArrayBuffer.isView(value)) {
  296. return fromArrayView(value);
  297. }
  298. if (value == null) {
  299. throw new TypeError(
  300. "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
  301. );
  302. }
  303. if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
  304. return fromArrayBuffer(value, encodingOrOffset, length);
  305. }
  306. if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
  307. return fromArrayBuffer(value, encodingOrOffset, length);
  308. }
  309. if (typeof value === "number") {
  310. throw new TypeError(
  311. 'The "value" argument must not be of type number. Received type number'
  312. );
  313. }
  314. const valueOf = value.valueOf && value.valueOf();
  315. if (valueOf != null && valueOf !== value) {
  316. return Buffer4.from(valueOf, encodingOrOffset, length);
  317. }
  318. const b = fromObject(value);
  319. if (b) return b;
  320. if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
  321. return Buffer4.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
  322. }
  323. throw new TypeError(
  324. "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
  325. );
  326. }
  327. __name(from, "from");
  328. Buffer4.from = function(value, encodingOrOffset, length) {
  329. return from(value, encodingOrOffset, length);
  330. };
  331. Object.setPrototypeOf(Buffer4.prototype, Uint8Array.prototype);
  332. Object.setPrototypeOf(Buffer4, Uint8Array);
  333. function assertSize(size) {
  334. if (typeof size !== "number") {
  335. throw new TypeError('"size" argument must be of type number');
  336. } else if (size < 0) {
  337. throw new RangeError('The value "' + size + '" is invalid for option "size"');
  338. }
  339. }
  340. __name(assertSize, "assertSize");
  341. function alloc(size, fill, encoding) {
  342. assertSize(size);
  343. if (size <= 0) {
  344. return createBuffer(size);
  345. }
  346. if (fill !== void 0) {
  347. return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
  348. }
  349. return createBuffer(size);
  350. }
  351. __name(alloc, "alloc");
  352. Buffer4.alloc = function(size, fill, encoding) {
  353. return alloc(size, fill, encoding);
  354. };
  355. function allocUnsafe(size) {
  356. assertSize(size);
  357. return createBuffer(size < 0 ? 0 : checked(size) | 0);
  358. }
  359. __name(allocUnsafe, "allocUnsafe");
  360. Buffer4.allocUnsafe = function(size) {
  361. return allocUnsafe(size);
  362. };
  363. Buffer4.allocUnsafeSlow = function(size) {
  364. return allocUnsafe(size);
  365. };
  366. function fromString(string, encoding) {
  367. if (typeof encoding !== "string" || encoding === "") {
  368. encoding = "utf8";
  369. }
  370. if (!Buffer4.isEncoding(encoding)) {
  371. throw new TypeError("Unknown encoding: " + encoding);
  372. }
  373. const length = byteLength(string, encoding) | 0;
  374. let buf = createBuffer(length);
  375. const actual = buf.write(string, encoding);
  376. if (actual !== length) {
  377. buf = buf.slice(0, actual);
  378. }
  379. return buf;
  380. }
  381. __name(fromString, "fromString");
  382. function fromArrayLike(array) {
  383. const length = array.length < 0 ? 0 : checked(array.length) | 0;
  384. const buf = createBuffer(length);
  385. for (let i = 0; i < length; i += 1) {
  386. buf[i] = array[i] & 255;
  387. }
  388. return buf;
  389. }
  390. __name(fromArrayLike, "fromArrayLike");
  391. function fromArrayView(arrayView) {
  392. if (isInstance(arrayView, Uint8Array)) {
  393. const copy = new Uint8Array(arrayView);
  394. return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
  395. }
  396. return fromArrayLike(arrayView);
  397. }
  398. __name(fromArrayView, "fromArrayView");
  399. function fromArrayBuffer(array, byteOffset, length) {
  400. if (byteOffset < 0 || array.byteLength < byteOffset) {
  401. throw new RangeError('"offset" is outside of buffer bounds');
  402. }
  403. if (array.byteLength < byteOffset + (length || 0)) {
  404. throw new RangeError('"length" is outside of buffer bounds');
  405. }
  406. let buf;
  407. if (byteOffset === void 0 && length === void 0) {
  408. buf = new Uint8Array(array);
  409. } else if (length === void 0) {
  410. buf = new Uint8Array(array, byteOffset);
  411. } else {
  412. buf = new Uint8Array(array, byteOffset, length);
  413. }
  414. Object.setPrototypeOf(buf, Buffer4.prototype);
  415. return buf;
  416. }
  417. __name(fromArrayBuffer, "fromArrayBuffer");
  418. function fromObject(obj) {
  419. if (Buffer4.isBuffer(obj)) {
  420. const len = checked(obj.length) | 0;
  421. const buf = createBuffer(len);
  422. if (buf.length === 0) {
  423. return buf;
  424. }
  425. obj.copy(buf, 0, 0, len);
  426. return buf;
  427. }
  428. if (obj.length !== void 0) {
  429. if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
  430. return createBuffer(0);
  431. }
  432. return fromArrayLike(obj);
  433. }
  434. if (obj.type === "Buffer" && Array.isArray(obj.data)) {
  435. return fromArrayLike(obj.data);
  436. }
  437. }
  438. __name(fromObject, "fromObject");
  439. function checked(length) {
  440. if (length >= K_MAX_LENGTH) {
  441. throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
  442. }
  443. return length | 0;
  444. }
  445. __name(checked, "checked");
  446. function SlowBuffer(length) {
  447. if (+length != length) {
  448. length = 0;
  449. }
  450. return Buffer4.alloc(+length);
  451. }
  452. __name(SlowBuffer, "SlowBuffer");
  453. Buffer4.isBuffer = /* @__PURE__ */ __name(function isBuffer(b) {
  454. return b != null && b._isBuffer === true && b !== Buffer4.prototype;
  455. }, "isBuffer");
  456. Buffer4.compare = /* @__PURE__ */ __name(function compare(a, b) {
  457. if (isInstance(a, Uint8Array)) a = Buffer4.from(a, a.offset, a.byteLength);
  458. if (isInstance(b, Uint8Array)) b = Buffer4.from(b, b.offset, b.byteLength);
  459. if (!Buffer4.isBuffer(a) || !Buffer4.isBuffer(b)) {
  460. throw new TypeError(
  461. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  462. );
  463. }
  464. if (a === b) return 0;
  465. let x = a.length;
  466. let y = b.length;
  467. for (let i = 0, len = Math.min(x, y); i < len; ++i) {
  468. if (a[i] !== b[i]) {
  469. x = a[i];
  470. y = b[i];
  471. break;
  472. }
  473. }
  474. if (x < y) return -1;
  475. if (y < x) return 1;
  476. return 0;
  477. }, "compare");
  478. Buffer4.isEncoding = /* @__PURE__ */ __name(function isEncoding(encoding) {
  479. switch (String(encoding).toLowerCase()) {
  480. case "hex":
  481. case "utf8":
  482. case "utf-8":
  483. case "ascii":
  484. case "latin1":
  485. case "binary":
  486. case "base64":
  487. case "ucs2":
  488. case "ucs-2":
  489. case "utf16le":
  490. case "utf-16le":
  491. return true;
  492. default:
  493. return false;
  494. }
  495. }, "isEncoding");
  496. Buffer4.concat = /* @__PURE__ */ __name(function concat(list, length) {
  497. if (!Array.isArray(list)) {
  498. throw new TypeError('"list" argument must be an Array of Buffers');
  499. }
  500. if (list.length === 0) {
  501. return Buffer4.alloc(0);
  502. }
  503. let i;
  504. if (length === void 0) {
  505. length = 0;
  506. for (i = 0; i < list.length; ++i) {
  507. length += list[i].length;
  508. }
  509. }
  510. const buffer = Buffer4.allocUnsafe(length);
  511. let pos = 0;
  512. for (i = 0; i < list.length; ++i) {
  513. let buf = list[i];
  514. if (isInstance(buf, Uint8Array)) {
  515. if (pos + buf.length > buffer.length) {
  516. if (!Buffer4.isBuffer(buf)) buf = Buffer4.from(buf);
  517. buf.copy(buffer, pos);
  518. } else {
  519. Uint8Array.prototype.set.call(
  520. buffer,
  521. buf,
  522. pos
  523. );
  524. }
  525. } else if (!Buffer4.isBuffer(buf)) {
  526. throw new TypeError('"list" argument must be an Array of Buffers');
  527. } else {
  528. buf.copy(buffer, pos);
  529. }
  530. pos += buf.length;
  531. }
  532. return buffer;
  533. }, "concat");
  534. function byteLength(string, encoding) {
  535. if (Buffer4.isBuffer(string)) {
  536. return string.length;
  537. }
  538. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  539. return string.byteLength;
  540. }
  541. if (typeof string !== "string") {
  542. throw new TypeError(
  543. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
  544. );
  545. }
  546. const len = string.length;
  547. const mustMatch = arguments.length > 2 && arguments[2] === true;
  548. if (!mustMatch && len === 0) return 0;
  549. let loweredCase = false;
  550. for (; ; ) {
  551. switch (encoding) {
  552. case "ascii":
  553. case "latin1":
  554. case "binary":
  555. return len;
  556. case "utf8":
  557. case "utf-8":
  558. return utf8ToBytes(string).length;
  559. case "ucs2":
  560. case "ucs-2":
  561. case "utf16le":
  562. case "utf-16le":
  563. return len * 2;
  564. case "hex":
  565. return len >>> 1;
  566. case "base64":
  567. return base64ToBytes(string).length;
  568. default:
  569. if (loweredCase) {
  570. return mustMatch ? -1 : utf8ToBytes(string).length;
  571. }
  572. encoding = ("" + encoding).toLowerCase();
  573. loweredCase = true;
  574. }
  575. }
  576. }
  577. __name(byteLength, "byteLength");
  578. Buffer4.byteLength = byteLength;
  579. function slowToString(encoding, start, end) {
  580. let loweredCase = false;
  581. if (start === void 0 || start < 0) {
  582. start = 0;
  583. }
  584. if (start > this.length) {
  585. return "";
  586. }
  587. if (end === void 0 || end > this.length) {
  588. end = this.length;
  589. }
  590. if (end <= 0) {
  591. return "";
  592. }
  593. end >>>= 0;
  594. start >>>= 0;
  595. if (end <= start) {
  596. return "";
  597. }
  598. if (!encoding) encoding = "utf8";
  599. while (true) {
  600. switch (encoding) {
  601. case "hex":
  602. return hexSlice(this, start, end);
  603. case "utf8":
  604. case "utf-8":
  605. return utf8Slice(this, start, end);
  606. case "ascii":
  607. return asciiSlice(this, start, end);
  608. case "latin1":
  609. case "binary":
  610. return latin1Slice(this, start, end);
  611. case "base64":
  612. return base64Slice(this, start, end);
  613. case "ucs2":
  614. case "ucs-2":
  615. case "utf16le":
  616. case "utf-16le":
  617. return utf16leSlice(this, start, end);
  618. default:
  619. if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
  620. encoding = (encoding + "").toLowerCase();
  621. loweredCase = true;
  622. }
  623. }
  624. }
  625. __name(slowToString, "slowToString");
  626. Buffer4.prototype._isBuffer = true;
  627. function swap(b, n, m) {
  628. const i = b[n];
  629. b[n] = b[m];
  630. b[m] = i;
  631. }
  632. __name(swap, "swap");
  633. Buffer4.prototype.swap16 = /* @__PURE__ */ __name(function swap16() {
  634. const len = this.length;
  635. if (len % 2 !== 0) {
  636. throw new RangeError("Buffer size must be a multiple of 16-bits");
  637. }
  638. for (let i = 0; i < len; i += 2) {
  639. swap(this, i, i + 1);
  640. }
  641. return this;
  642. }, "swap16");
  643. Buffer4.prototype.swap32 = /* @__PURE__ */ __name(function swap32() {
  644. const len = this.length;
  645. if (len % 4 !== 0) {
  646. throw new RangeError("Buffer size must be a multiple of 32-bits");
  647. }
  648. for (let i = 0; i < len; i += 4) {
  649. swap(this, i, i + 3);
  650. swap(this, i + 1, i + 2);
  651. }
  652. return this;
  653. }, "swap32");
  654. Buffer4.prototype.swap64 = /* @__PURE__ */ __name(function swap64() {
  655. const len = this.length;
  656. if (len % 8 !== 0) {
  657. throw new RangeError("Buffer size must be a multiple of 64-bits");
  658. }
  659. for (let i = 0; i < len; i += 8) {
  660. swap(this, i, i + 7);
  661. swap(this, i + 1, i + 6);
  662. swap(this, i + 2, i + 5);
  663. swap(this, i + 3, i + 4);
  664. }
  665. return this;
  666. }, "swap64");
  667. Buffer4.prototype.toString = /* @__PURE__ */ __name(function toString() {
  668. const length = this.length;
  669. if (length === 0) return "";
  670. if (arguments.length === 0) return utf8Slice(this, 0, length);
  671. return slowToString.apply(this, arguments);
  672. }, "toString");
  673. Buffer4.prototype.toLocaleString = Buffer4.prototype.toString;
  674. Buffer4.prototype.equals = /* @__PURE__ */ __name(function equals(b) {
  675. if (!Buffer4.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
  676. if (this === b) return true;
  677. return Buffer4.compare(this, b) === 0;
  678. }, "equals");
  679. Buffer4.prototype.inspect = /* @__PURE__ */ __name(function inspect() {
  680. let str = "";
  681. const max = exports.INSPECT_MAX_BYTES;
  682. str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
  683. if (this.length > max) str += " ... ";
  684. return "<Buffer " + str + ">";
  685. }, "inspect");
  686. if (customInspectSymbol) {
  687. Buffer4.prototype[customInspectSymbol] = Buffer4.prototype.inspect;
  688. }
  689. Buffer4.prototype.compare = /* @__PURE__ */ __name(function compare(target, start, end, thisStart, thisEnd) {
  690. if (isInstance(target, Uint8Array)) {
  691. target = Buffer4.from(target, target.offset, target.byteLength);
  692. }
  693. if (!Buffer4.isBuffer(target)) {
  694. throw new TypeError(
  695. 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
  696. );
  697. }
  698. if (start === void 0) {
  699. start = 0;
  700. }
  701. if (end === void 0) {
  702. end = target ? target.length : 0;
  703. }
  704. if (thisStart === void 0) {
  705. thisStart = 0;
  706. }
  707. if (thisEnd === void 0) {
  708. thisEnd = this.length;
  709. }
  710. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  711. throw new RangeError("out of range index");
  712. }
  713. if (thisStart >= thisEnd && start >= end) {
  714. return 0;
  715. }
  716. if (thisStart >= thisEnd) {
  717. return -1;
  718. }
  719. if (start >= end) {
  720. return 1;
  721. }
  722. start >>>= 0;
  723. end >>>= 0;
  724. thisStart >>>= 0;
  725. thisEnd >>>= 0;
  726. if (this === target) return 0;
  727. let x = thisEnd - thisStart;
  728. let y = end - start;
  729. const len = Math.min(x, y);
  730. const thisCopy = this.slice(thisStart, thisEnd);
  731. const targetCopy = target.slice(start, end);
  732. for (let i = 0; i < len; ++i) {
  733. if (thisCopy[i] !== targetCopy[i]) {
  734. x = thisCopy[i];
  735. y = targetCopy[i];
  736. break;
  737. }
  738. }
  739. if (x < y) return -1;
  740. if (y < x) return 1;
  741. return 0;
  742. }, "compare");
  743. function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  744. if (buffer.length === 0) return -1;
  745. if (typeof byteOffset === "string") {
  746. encoding = byteOffset;
  747. byteOffset = 0;
  748. } else if (byteOffset > 2147483647) {
  749. byteOffset = 2147483647;
  750. } else if (byteOffset < -2147483648) {
  751. byteOffset = -2147483648;
  752. }
  753. byteOffset = +byteOffset;
  754. if (numberIsNaN(byteOffset)) {
  755. byteOffset = dir ? 0 : buffer.length - 1;
  756. }
  757. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  758. if (byteOffset >= buffer.length) {
  759. if (dir) return -1;
  760. else byteOffset = buffer.length - 1;
  761. } else if (byteOffset < 0) {
  762. if (dir) byteOffset = 0;
  763. else return -1;
  764. }
  765. if (typeof val === "string") {
  766. val = Buffer4.from(val, encoding);
  767. }
  768. if (Buffer4.isBuffer(val)) {
  769. if (val.length === 0) {
  770. return -1;
  771. }
  772. return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
  773. } else if (typeof val === "number") {
  774. val = val & 255;
  775. if (typeof Uint8Array.prototype.indexOf === "function") {
  776. if (dir) {
  777. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
  778. } else {
  779. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
  780. }
  781. }
  782. return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
  783. }
  784. throw new TypeError("val must be string, number or Buffer");
  785. }
  786. __name(bidirectionalIndexOf, "bidirectionalIndexOf");
  787. function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  788. let indexSize = 1;
  789. let arrLength = arr.length;
  790. let valLength = val.length;
  791. if (encoding !== void 0) {
  792. encoding = String(encoding).toLowerCase();
  793. if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
  794. if (arr.length < 2 || val.length < 2) {
  795. return -1;
  796. }
  797. indexSize = 2;
  798. arrLength /= 2;
  799. valLength /= 2;
  800. byteOffset /= 2;
  801. }
  802. }
  803. function read2(buf, i2) {
  804. if (indexSize === 1) {
  805. return buf[i2];
  806. } else {
  807. return buf.readUInt16BE(i2 * indexSize);
  808. }
  809. }
  810. __name(read2, "read");
  811. let i;
  812. if (dir) {
  813. let foundIndex = -1;
  814. for (i = byteOffset; i < arrLength; i++) {
  815. if (read2(arr, i) === read2(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  816. if (foundIndex === -1) foundIndex = i;
  817. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
  818. } else {
  819. if (foundIndex !== -1) i -= i - foundIndex;
  820. foundIndex = -1;
  821. }
  822. }
  823. } else {
  824. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  825. for (i = byteOffset; i >= 0; i--) {
  826. let found = true;
  827. for (let j = 0; j < valLength; j++) {
  828. if (read2(arr, i + j) !== read2(val, j)) {
  829. found = false;
  830. break;
  831. }
  832. }
  833. if (found) return i;
  834. }
  835. }
  836. return -1;
  837. }
  838. __name(arrayIndexOf, "arrayIndexOf");
  839. Buffer4.prototype.includes = /* @__PURE__ */ __name(function includes(val, byteOffset, encoding) {
  840. return this.indexOf(val, byteOffset, encoding) !== -1;
  841. }, "includes");
  842. Buffer4.prototype.indexOf = /* @__PURE__ */ __name(function indexOf(val, byteOffset, encoding) {
  843. return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
  844. }, "indexOf");
  845. Buffer4.prototype.lastIndexOf = /* @__PURE__ */ __name(function lastIndexOf(val, byteOffset, encoding) {
  846. return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
  847. }, "lastIndexOf");
  848. function hexWrite(buf, string, offset, length) {
  849. offset = Number(offset) || 0;
  850. const remaining = buf.length - offset;
  851. if (!length) {
  852. length = remaining;
  853. } else {
  854. length = Number(length);
  855. if (length > remaining) {
  856. length = remaining;
  857. }
  858. }
  859. const strLen = string.length;
  860. if (length > strLen / 2) {
  861. length = strLen / 2;
  862. }
  863. let i;
  864. for (i = 0; i < length; ++i) {
  865. const parsed = parseInt(string.substr(i * 2, 2), 16);
  866. if (numberIsNaN(parsed)) return i;
  867. buf[offset + i] = parsed;
  868. }
  869. return i;
  870. }
  871. __name(hexWrite, "hexWrite");
  872. function utf8Write(buf, string, offset, length) {
  873. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
  874. }
  875. __name(utf8Write, "utf8Write");
  876. function asciiWrite(buf, string, offset, length) {
  877. return blitBuffer(asciiToBytes(string), buf, offset, length);
  878. }
  879. __name(asciiWrite, "asciiWrite");
  880. function base64Write(buf, string, offset, length) {
  881. return blitBuffer(base64ToBytes(string), buf, offset, length);
  882. }
  883. __name(base64Write, "base64Write");
  884. function ucs2Write(buf, string, offset, length) {
  885. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
  886. }
  887. __name(ucs2Write, "ucs2Write");
  888. Buffer4.prototype.write = /* @__PURE__ */ __name(function write2(string, offset, length, encoding) {
  889. if (offset === void 0) {
  890. encoding = "utf8";
  891. length = this.length;
  892. offset = 0;
  893. } else if (length === void 0 && typeof offset === "string") {
  894. encoding = offset;
  895. length = this.length;
  896. offset = 0;
  897. } else if (isFinite(offset)) {
  898. offset = offset >>> 0;
  899. if (isFinite(length)) {
  900. length = length >>> 0;
  901. if (encoding === void 0) encoding = "utf8";
  902. } else {
  903. encoding = length;
  904. length = void 0;
  905. }
  906. } else {
  907. throw new Error(
  908. "Buffer.write(string, encoding, offset[, length]) is no longer supported"
  909. );
  910. }
  911. const remaining = this.length - offset;
  912. if (length === void 0 || length > remaining) length = remaining;
  913. if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
  914. throw new RangeError("Attempt to write outside buffer bounds");
  915. }
  916. if (!encoding) encoding = "utf8";
  917. let loweredCase = false;
  918. for (; ; ) {
  919. switch (encoding) {
  920. case "hex":
  921. return hexWrite(this, string, offset, length);
  922. case "utf8":
  923. case "utf-8":
  924. return utf8Write(this, string, offset, length);
  925. case "ascii":
  926. case "latin1":
  927. case "binary":
  928. return asciiWrite(this, string, offset, length);
  929. case "base64":
  930. return base64Write(this, string, offset, length);
  931. case "ucs2":
  932. case "ucs-2":
  933. case "utf16le":
  934. case "utf-16le":
  935. return ucs2Write(this, string, offset, length);
  936. default:
  937. if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
  938. encoding = ("" + encoding).toLowerCase();
  939. loweredCase = true;
  940. }
  941. }
  942. }, "write");
  943. Buffer4.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
  944. return {
  945. type: "Buffer",
  946. data: Array.prototype.slice.call(this._arr || this, 0)
  947. };
  948. }, "toJSON");
  949. function base64Slice(buf, start, end) {
  950. if (start === 0 && end === buf.length) {
  951. return base64.fromByteArray(buf);
  952. } else {
  953. return base64.fromByteArray(buf.slice(start, end));
  954. }
  955. }
  956. __name(base64Slice, "base64Slice");
  957. function utf8Slice(buf, start, end) {
  958. end = Math.min(buf.length, end);
  959. const res = [];
  960. let i = start;
  961. while (i < end) {
  962. const firstByte = buf[i];
  963. let codePoint = null;
  964. let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
  965. if (i + bytesPerSequence <= end) {
  966. let secondByte, thirdByte, fourthByte, tempCodePoint;
  967. switch (bytesPerSequence) {
  968. case 1:
  969. if (firstByte < 128) {
  970. codePoint = firstByte;
  971. }
  972. break;
  973. case 2:
  974. secondByte = buf[i + 1];
  975. if ((secondByte & 192) === 128) {
  976. tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
  977. if (tempCodePoint > 127) {
  978. codePoint = tempCodePoint;
  979. }
  980. }
  981. break;
  982. case 3:
  983. secondByte = buf[i + 1];
  984. thirdByte = buf[i + 2];
  985. if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
  986. tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
  987. if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
  988. codePoint = tempCodePoint;
  989. }
  990. }
  991. break;
  992. case 4:
  993. secondByte = buf[i + 1];
  994. thirdByte = buf[i + 2];
  995. fourthByte = buf[i + 3];
  996. if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
  997. tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
  998. if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
  999. codePoint = tempCodePoint;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. if (codePoint === null) {
  1005. codePoint = 65533;
  1006. bytesPerSequence = 1;
  1007. } else if (codePoint > 65535) {
  1008. codePoint -= 65536;
  1009. res.push(codePoint >>> 10 & 1023 | 55296);
  1010. codePoint = 56320 | codePoint & 1023;
  1011. }
  1012. res.push(codePoint);
  1013. i += bytesPerSequence;
  1014. }
  1015. return decodeCodePointsArray(res);
  1016. }
  1017. __name(utf8Slice, "utf8Slice");
  1018. var MAX_ARGUMENTS_LENGTH = 4096;
  1019. function decodeCodePointsArray(codePoints) {
  1020. const len = codePoints.length;
  1021. if (len <= MAX_ARGUMENTS_LENGTH) {
  1022. return String.fromCharCode.apply(String, codePoints);
  1023. }
  1024. let res = "";
  1025. let i = 0;
  1026. while (i < len) {
  1027. res += String.fromCharCode.apply(
  1028. String,
  1029. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1030. );
  1031. }
  1032. return res;
  1033. }
  1034. __name(decodeCodePointsArray, "decodeCodePointsArray");
  1035. function asciiSlice(buf, start, end) {
  1036. let ret = "";
  1037. end = Math.min(buf.length, end);
  1038. for (let i = start; i < end; ++i) {
  1039. ret += String.fromCharCode(buf[i] & 127);
  1040. }
  1041. return ret;
  1042. }
  1043. __name(asciiSlice, "asciiSlice");
  1044. function latin1Slice(buf, start, end) {
  1045. let ret = "";
  1046. end = Math.min(buf.length, end);
  1047. for (let i = start; i < end; ++i) {
  1048. ret += String.fromCharCode(buf[i]);
  1049. }
  1050. return ret;
  1051. }
  1052. __name(latin1Slice, "latin1Slice");
  1053. function hexSlice(buf, start, end) {
  1054. const len = buf.length;
  1055. if (!start || start < 0) start = 0;
  1056. if (!end || end < 0 || end > len) end = len;
  1057. let out = "";
  1058. for (let i = start; i < end; ++i) {
  1059. out += hexSliceLookupTable[buf[i]];
  1060. }
  1061. return out;
  1062. }
  1063. __name(hexSlice, "hexSlice");
  1064. function utf16leSlice(buf, start, end) {
  1065. const bytes = buf.slice(start, end);
  1066. let res = "";
  1067. for (let i = 0; i < bytes.length - 1; i += 2) {
  1068. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  1069. }
  1070. return res;
  1071. }
  1072. __name(utf16leSlice, "utf16leSlice");
  1073. Buffer4.prototype.slice = /* @__PURE__ */ __name(function slice(start, end) {
  1074. const len = this.length;
  1075. start = ~~start;
  1076. end = end === void 0 ? len : ~~end;
  1077. if (start < 0) {
  1078. start += len;
  1079. if (start < 0) start = 0;
  1080. } else if (start > len) {
  1081. start = len;
  1082. }
  1083. if (end < 0) {
  1084. end += len;
  1085. if (end < 0) end = 0;
  1086. } else if (end > len) {
  1087. end = len;
  1088. }
  1089. if (end < start) end = start;
  1090. const newBuf = this.subarray(start, end);
  1091. Object.setPrototypeOf(newBuf, Buffer4.prototype);
  1092. return newBuf;
  1093. }, "slice");
  1094. function checkOffset(offset, ext, length) {
  1095. if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
  1096. if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
  1097. }
  1098. __name(checkOffset, "checkOffset");
  1099. Buffer4.prototype.readUintLE = Buffer4.prototype.readUIntLE = /* @__PURE__ */ __name(function readUIntLE(offset, byteLength2, noAssert) {
  1100. offset = offset >>> 0;
  1101. byteLength2 = byteLength2 >>> 0;
  1102. if (!noAssert) checkOffset(offset, byteLength2, this.length);
  1103. let val = this[offset];
  1104. let mul = 1;
  1105. let i = 0;
  1106. while (++i < byteLength2 && (mul *= 256)) {
  1107. val += this[offset + i] * mul;
  1108. }
  1109. return val;
  1110. }, "readUIntLE");
  1111. Buffer4.prototype.readUintBE = Buffer4.prototype.readUIntBE = /* @__PURE__ */ __name(function readUIntBE(offset, byteLength2, noAssert) {
  1112. offset = offset >>> 0;
  1113. byteLength2 = byteLength2 >>> 0;
  1114. if (!noAssert) {
  1115. checkOffset(offset, byteLength2, this.length);
  1116. }
  1117. let val = this[offset + --byteLength2];
  1118. let mul = 1;
  1119. while (byteLength2 > 0 && (mul *= 256)) {
  1120. val += this[offset + --byteLength2] * mul;
  1121. }
  1122. return val;
  1123. }, "readUIntBE");
  1124. Buffer4.prototype.readUint8 = Buffer4.prototype.readUInt8 = /* @__PURE__ */ __name(function readUInt8(offset, noAssert) {
  1125. offset = offset >>> 0;
  1126. if (!noAssert) checkOffset(offset, 1, this.length);
  1127. return this[offset];
  1128. }, "readUInt8");
  1129. Buffer4.prototype.readUint16LE = Buffer4.prototype.readUInt16LE = /* @__PURE__ */ __name(function readUInt16LE(offset, noAssert) {
  1130. offset = offset >>> 0;
  1131. if (!noAssert) checkOffset(offset, 2, this.length);
  1132. return this[offset] | this[offset + 1] << 8;
  1133. }, "readUInt16LE");
  1134. Buffer4.prototype.readUint16BE = Buffer4.prototype.readUInt16BE = /* @__PURE__ */ __name(function readUInt16BE(offset, noAssert) {
  1135. offset = offset >>> 0;
  1136. if (!noAssert) checkOffset(offset, 2, this.length);
  1137. return this[offset] << 8 | this[offset + 1];
  1138. }, "readUInt16BE");
  1139. Buffer4.prototype.readUint32LE = Buffer4.prototype.readUInt32LE = /* @__PURE__ */ __name(function readUInt32LE(offset, noAssert) {
  1140. offset = offset >>> 0;
  1141. if (!noAssert) checkOffset(offset, 4, this.length);
  1142. return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
  1143. }, "readUInt32LE");
  1144. Buffer4.prototype.readUint32BE = Buffer4.prototype.readUInt32BE = /* @__PURE__ */ __name(function readUInt32BE(offset, noAssert) {
  1145. offset = offset >>> 0;
  1146. if (!noAssert) checkOffset(offset, 4, this.length);
  1147. return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
  1148. }, "readUInt32BE");
  1149. Buffer4.prototype.readBigUInt64LE = defineBigIntMethod(/* @__PURE__ */ __name(function readBigUInt64LE(offset) {
  1150. offset = offset >>> 0;
  1151. validateNumber(offset, "offset");
  1152. const first = this[offset];
  1153. const last = this[offset + 7];
  1154. if (first === void 0 || last === void 0) {
  1155. boundsError(offset, this.length - 8);
  1156. }
  1157. const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
  1158. const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
  1159. return BigInt(lo) + (BigInt(hi) << BigInt(32));
  1160. }, "readBigUInt64LE"));
  1161. Buffer4.prototype.readBigUInt64BE = defineBigIntMethod(/* @__PURE__ */ __name(function readBigUInt64BE(offset) {
  1162. offset = offset >>> 0;
  1163. validateNumber(offset, "offset");
  1164. const first = this[offset];
  1165. const last = this[offset + 7];
  1166. if (first === void 0 || last === void 0) {
  1167. boundsError(offset, this.length - 8);
  1168. }
  1169. const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
  1170. const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
  1171. return (BigInt(hi) << BigInt(32)) + BigInt(lo);
  1172. }, "readBigUInt64BE"));
  1173. Buffer4.prototype.readIntLE = /* @__PURE__ */ __name(function readIntLE(offset, byteLength2, noAssert) {
  1174. offset = offset >>> 0;
  1175. byteLength2 = byteLength2 >>> 0;
  1176. if (!noAssert) checkOffset(offset, byteLength2, this.length);
  1177. let val = this[offset];
  1178. let mul = 1;
  1179. let i = 0;
  1180. while (++i < byteLength2 && (mul *= 256)) {
  1181. val += this[offset + i] * mul;
  1182. }
  1183. mul *= 128;
  1184. if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
  1185. return val;
  1186. }, "readIntLE");
  1187. Buffer4.prototype.readIntBE = /* @__PURE__ */ __name(function readIntBE(offset, byteLength2, noAssert) {
  1188. offset = offset >>> 0;
  1189. byteLength2 = byteLength2 >>> 0;
  1190. if (!noAssert) checkOffset(offset, byteLength2, this.length);
  1191. let i = byteLength2;
  1192. let mul = 1;
  1193. let val = this[offset + --i];
  1194. while (i > 0 && (mul *= 256)) {
  1195. val += this[offset + --i] * mul;
  1196. }
  1197. mul *= 128;
  1198. if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
  1199. return val;
  1200. }, "readIntBE");
  1201. Buffer4.prototype.readInt8 = /* @__PURE__ */ __name(function readInt8(offset, noAssert) {
  1202. offset = offset >>> 0;
  1203. if (!noAssert) checkOffset(offset, 1, this.length);
  1204. if (!(this[offset] & 128)) return this[offset];
  1205. return (255 - this[offset] + 1) * -1;
  1206. }, "readInt8");
  1207. Buffer4.prototype.readInt16LE = /* @__PURE__ */ __name(function readInt16LE(offset, noAssert) {
  1208. offset = offset >>> 0;
  1209. if (!noAssert) checkOffset(offset, 2, this.length);
  1210. const val = this[offset] | this[offset + 1] << 8;
  1211. return val & 32768 ? val | 4294901760 : val;
  1212. }, "readInt16LE");
  1213. Buffer4.prototype.readInt16BE = /* @__PURE__ */ __name(function readInt16BE(offset, noAssert) {
  1214. offset = offset >>> 0;
  1215. if (!noAssert) checkOffset(offset, 2, this.length);
  1216. const val = this[offset + 1] | this[offset] << 8;
  1217. return val & 32768 ? val | 4294901760 : val;
  1218. }, "readInt16BE");
  1219. Buffer4.prototype.readInt32LE = /* @__PURE__ */ __name(function readInt32LE(offset, noAssert) {
  1220. offset = offset >>> 0;
  1221. if (!noAssert) checkOffset(offset, 4, this.length);
  1222. return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
  1223. }, "readInt32LE");
  1224. Buffer4.prototype.readInt32BE = /* @__PURE__ */ __name(function readInt32BE(offset, noAssert) {
  1225. offset = offset >>> 0;
  1226. if (!noAssert) checkOffset(offset, 4, this.length);
  1227. return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
  1228. }, "readInt32BE");
  1229. Buffer4.prototype.readBigInt64LE = defineBigIntMethod(/* @__PURE__ */ __name(function readBigInt64LE(offset) {
  1230. offset = offset >>> 0;
  1231. validateNumber(offset, "offset");
  1232. const first = this[offset];
  1233. const last = this[offset + 7];
  1234. if (first === void 0 || last === void 0) {
  1235. boundsError(offset, this.length - 8);
  1236. }
  1237. const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
  1238. return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
  1239. }, "readBigInt64LE"));
  1240. Buffer4.prototype.readBigInt64BE = defineBigIntMethod(/* @__PURE__ */ __name(function readBigInt64BE(offset) {
  1241. offset = offset >>> 0;
  1242. validateNumber(offset, "offset");
  1243. const first = this[offset];
  1244. const last = this[offset + 7];
  1245. if (first === void 0 || last === void 0) {
  1246. boundsError(offset, this.length - 8);
  1247. }
  1248. const val = (first << 24) + // Overflow
  1249. this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
  1250. return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
  1251. }, "readBigInt64BE"));
  1252. Buffer4.prototype.readFloatLE = /* @__PURE__ */ __name(function readFloatLE(offset, noAssert) {
  1253. offset = offset >>> 0;
  1254. if (!noAssert) checkOffset(offset, 4, this.length);
  1255. return ieee754.read(this, offset, true, 23, 4);
  1256. }, "readFloatLE");
  1257. Buffer4.prototype.readFloatBE = /* @__PURE__ */ __name(function readFloatBE(offset, noAssert) {
  1258. offset = offset >>> 0;
  1259. if (!noAssert) checkOffset(offset, 4, this.length);
  1260. return ieee754.read(this, offset, false, 23, 4);
  1261. }, "readFloatBE");
  1262. Buffer4.prototype.readDoubleLE = /* @__PURE__ */ __name(function readDoubleLE(offset, noAssert) {
  1263. offset = offset >>> 0;
  1264. if (!noAssert) checkOffset(offset, 8, this.length);
  1265. return ieee754.read(this, offset, true, 52, 8);
  1266. }, "readDoubleLE");
  1267. Buffer4.prototype.readDoubleBE = /* @__PURE__ */ __name(function readDoubleBE(offset, noAssert) {
  1268. offset = offset >>> 0;
  1269. if (!noAssert) checkOffset(offset, 8, this.length);
  1270. return ieee754.read(this, offset, false, 52, 8);
  1271. }, "readDoubleBE");
  1272. function checkInt(buf, value, offset, ext, max, min) {
  1273. if (!Buffer4.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
  1274. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
  1275. if (offset + ext > buf.length) throw new RangeError("Index out of range");
  1276. }
  1277. __name(checkInt, "checkInt");
  1278. Buffer4.prototype.writeUintLE = Buffer4.prototype.writeUIntLE = /* @__PURE__ */ __name(function writeUIntLE(value, offset, byteLength2, noAssert) {
  1279. value = +value;
  1280. offset = offset >>> 0;
  1281. byteLength2 = byteLength2 >>> 0;
  1282. if (!noAssert) {
  1283. const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
  1284. checkInt(this, value, offset, byteLength2, maxBytes, 0);
  1285. }
  1286. let mul = 1;
  1287. let i = 0;
  1288. this[offset] = value & 255;
  1289. while (++i < byteLength2 && (mul *= 256)) {
  1290. this[offset + i] = value / mul & 255;
  1291. }
  1292. return offset + byteLength2;
  1293. }, "writeUIntLE");
  1294. Buffer4.prototype.writeUintBE = Buffer4.prototype.writeUIntBE = /* @__PURE__ */ __name(function writeUIntBE(value, offset, byteLength2, noAssert) {
  1295. value = +value;
  1296. offset = offset >>> 0;
  1297. byteLength2 = byteLength2 >>> 0;
  1298. if (!noAssert) {
  1299. const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
  1300. checkInt(this, value, offset, byteLength2, maxBytes, 0);
  1301. }
  1302. let i = byteLength2 - 1;
  1303. let mul = 1;
  1304. this[offset + i] = value & 255;
  1305. while (--i >= 0 && (mul *= 256)) {
  1306. this[offset + i] = value / mul & 255;
  1307. }
  1308. return offset + byteLength2;
  1309. }, "writeUIntBE");
  1310. Buffer4.prototype.writeUint8 = Buffer4.prototype.writeUInt8 = /* @__PURE__ */ __name(function writeUInt8(value, offset, noAssert) {
  1311. value = +value;
  1312. offset = offset >>> 0;
  1313. if (!noAssert) checkInt(this, value, offset, 1, 255, 0);
  1314. this[offset] = value & 255;
  1315. return offset + 1;
  1316. }, "writeUInt8");
  1317. Buffer4.prototype.writeUint16LE = Buffer4.prototype.writeUInt16LE = /* @__PURE__ */ __name(function writeUInt16LE(value, offset, noAssert) {
  1318. value = +value;
  1319. offset = offset >>> 0;
  1320. if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
  1321. this[offset] = value & 255;
  1322. this[offset + 1] = value >>> 8;
  1323. return offset + 2;
  1324. }, "writeUInt16LE");
  1325. Buffer4.prototype.writeUint16BE = Buffer4.prototype.writeUInt16BE = /* @__PURE__ */ __name(function writeUInt16BE(value, offset, noAssert) {
  1326. value = +value;
  1327. offset = offset >>> 0;
  1328. if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
  1329. this[offset] = value >>> 8;
  1330. this[offset + 1] = value & 255;
  1331. return offset + 2;
  1332. }, "writeUInt16BE");
  1333. Buffer4.prototype.writeUint32LE = Buffer4.prototype.writeUInt32LE = /* @__PURE__ */ __name(function writeUInt32LE(value, offset, noAssert) {
  1334. value = +value;
  1335. offset = offset >>> 0;
  1336. if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
  1337. this[offset + 3] = value >>> 24;
  1338. this[offset + 2] = value >>> 16;
  1339. this[offset + 1] = value >>> 8;
  1340. this[offset] = value & 255;
  1341. return offset + 4;
  1342. }, "writeUInt32LE");
  1343. Buffer4.prototype.writeUint32BE = Buffer4.prototype.writeUInt32BE = /* @__PURE__ */ __name(function writeUInt32BE(value, offset, noAssert) {
  1344. value = +value;
  1345. offset = offset >>> 0;
  1346. if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
  1347. this[offset] = value >>> 24;
  1348. this[offset + 1] = value >>> 16;
  1349. this[offset + 2] = value >>> 8;
  1350. this[offset + 3] = value & 255;
  1351. return offset + 4;
  1352. }, "writeUInt32BE");
  1353. function wrtBigUInt64LE(buf, value, offset, min, max) {
  1354. checkIntBI(value, min, max, buf, offset, 7);
  1355. let lo = Number(value & BigInt(4294967295));
  1356. buf[offset++] = lo;
  1357. lo = lo >> 8;
  1358. buf[offset++] = lo;
  1359. lo = lo >> 8;
  1360. buf[offset++] = lo;
  1361. lo = lo >> 8;
  1362. buf[offset++] = lo;
  1363. let hi = Number(value >> BigInt(32) & BigInt(4294967295));
  1364. buf[offset++] = hi;
  1365. hi = hi >> 8;
  1366. buf[offset++] = hi;
  1367. hi = hi >> 8;
  1368. buf[offset++] = hi;
  1369. hi = hi >> 8;
  1370. buf[offset++] = hi;
  1371. return offset;
  1372. }
  1373. __name(wrtBigUInt64LE, "wrtBigUInt64LE");
  1374. function wrtBigUInt64BE(buf, value, offset, min, max) {
  1375. checkIntBI(value, min, max, buf, offset, 7);
  1376. let lo = Number(value & BigInt(4294967295));
  1377. buf[offset + 7] = lo;
  1378. lo = lo >> 8;
  1379. buf[offset + 6] = lo;
  1380. lo = lo >> 8;
  1381. buf[offset + 5] = lo;
  1382. lo = lo >> 8;
  1383. buf[offset + 4] = lo;
  1384. let hi = Number(value >> BigInt(32) & BigInt(4294967295));
  1385. buf[offset + 3] = hi;
  1386. hi = hi >> 8;
  1387. buf[offset + 2] = hi;
  1388. hi = hi >> 8;
  1389. buf[offset + 1] = hi;
  1390. hi = hi >> 8;
  1391. buf[offset] = hi;
  1392. return offset + 8;
  1393. }
  1394. __name(wrtBigUInt64BE, "wrtBigUInt64BE");
  1395. Buffer4.prototype.writeBigUInt64LE = defineBigIntMethod(/* @__PURE__ */ __name(function writeBigUInt64LE(value, offset = 0) {
  1396. return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
  1397. }, "writeBigUInt64LE"));
  1398. Buffer4.prototype.writeBigUInt64BE = defineBigIntMethod(/* @__PURE__ */ __name(function writeBigUInt64BE(value, offset = 0) {
  1399. return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
  1400. }, "writeBigUInt64BE"));
  1401. Buffer4.prototype.writeIntLE = /* @__PURE__ */ __name(function writeIntLE(value, offset, byteLength2, noAssert) {
  1402. value = +value;
  1403. offset = offset >>> 0;
  1404. if (!noAssert) {
  1405. const limit = Math.pow(2, 8 * byteLength2 - 1);
  1406. checkInt(this, value, offset, byteLength2, limit - 1, -limit);
  1407. }
  1408. let i = 0;
  1409. let mul = 1;
  1410. let sub = 0;
  1411. this[offset] = value & 255;
  1412. while (++i < byteLength2 && (mul *= 256)) {
  1413. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1414. sub = 1;
  1415. }
  1416. this[offset + i] = (value / mul >> 0) - sub & 255;
  1417. }
  1418. return offset + byteLength2;
  1419. }, "writeIntLE");
  1420. Buffer4.prototype.writeIntBE = /* @__PURE__ */ __name(function writeIntBE(value, offset, byteLength2, noAssert) {
  1421. value = +value;
  1422. offset = offset >>> 0;
  1423. if (!noAssert) {
  1424. const limit = Math.pow(2, 8 * byteLength2 - 1);
  1425. checkInt(this, value, offset, byteLength2, limit - 1, -limit);
  1426. }
  1427. let i = byteLength2 - 1;
  1428. let mul = 1;
  1429. let sub = 0;
  1430. this[offset + i] = value & 255;
  1431. while (--i >= 0 && (mul *= 256)) {
  1432. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1433. sub = 1;
  1434. }
  1435. this[offset + i] = (value / mul >> 0) - sub & 255;
  1436. }
  1437. return offset + byteLength2;
  1438. }, "writeIntBE");
  1439. Buffer4.prototype.writeInt8 = /* @__PURE__ */ __name(function writeInt8(value, offset, noAssert) {
  1440. value = +value;
  1441. offset = offset >>> 0;
  1442. if (!noAssert) checkInt(this, value, offset, 1, 127, -128);
  1443. if (value < 0) value = 255 + value + 1;
  1444. this[offset] = value & 255;
  1445. return offset + 1;
  1446. }, "writeInt8");
  1447. Buffer4.prototype.writeInt16LE = /* @__PURE__ */ __name(function writeInt16LE(value, offset, noAssert) {
  1448. value = +value;
  1449. offset = offset >>> 0;
  1450. if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
  1451. this[offset] = value & 255;
  1452. this[offset + 1] = value >>> 8;
  1453. return offset + 2;
  1454. }, "writeInt16LE");
  1455. Buffer4.prototype.writeInt16BE = /* @__PURE__ */ __name(function writeInt16BE(value, offset, noAssert) {
  1456. value = +value;
  1457. offset = offset >>> 0;
  1458. if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
  1459. this[offset] = value >>> 8;
  1460. this[offset + 1] = value & 255;
  1461. return offset + 2;
  1462. }, "writeInt16BE");
  1463. Buffer4.prototype.writeInt32LE = /* @__PURE__ */ __name(function writeInt32LE(value, offset, noAssert) {
  1464. value = +value;
  1465. offset = offset >>> 0;
  1466. if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
  1467. this[offset] = value & 255;
  1468. this[offset + 1] = value >>> 8;
  1469. this[offset + 2] = value >>> 16;
  1470. this[offset + 3] = value >>> 24;
  1471. return offset + 4;
  1472. }, "writeInt32LE");
  1473. Buffer4.prototype.writeInt32BE = /* @__PURE__ */ __name(function writeInt32BE(value, offset, noAssert) {
  1474. value = +value;
  1475. offset = offset >>> 0;
  1476. if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
  1477. if (value < 0) value = 4294967295 + value + 1;
  1478. this[offset] = value >>> 24;
  1479. this[offset + 1] = value >>> 16;
  1480. this[offset + 2] = value >>> 8;
  1481. this[offset + 3] = value & 255;
  1482. return offset + 4;
  1483. }, "writeInt32BE");
  1484. Buffer4.prototype.writeBigInt64LE = defineBigIntMethod(/* @__PURE__ */ __name(function writeBigInt64LE(value, offset = 0) {
  1485. return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
  1486. }, "writeBigInt64LE"));
  1487. Buffer4.prototype.writeBigInt64BE = defineBigIntMethod(/* @__PURE__ */ __name(function writeBigInt64BE(value, offset = 0) {
  1488. return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
  1489. }, "writeBigInt64BE"));
  1490. function checkIEEE754(buf, value, offset, ext, max, min) {
  1491. if (offset + ext > buf.length) throw new RangeError("Index out of range");
  1492. if (offset < 0) throw new RangeError("Index out of range");
  1493. }
  1494. __name(checkIEEE754, "checkIEEE754");
  1495. function writeFloat(buf, value, offset, littleEndian, noAssert) {
  1496. value = +value;
  1497. offset = offset >>> 0;
  1498. if (!noAssert) {
  1499. checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22);
  1500. }
  1501. ieee754.write(buf, value, offset, littleEndian, 23, 4);
  1502. return offset + 4;
  1503. }
  1504. __name(writeFloat, "writeFloat");
  1505. Buffer4.prototype.writeFloatLE = /* @__PURE__ */ __name(function writeFloatLE(value, offset, noAssert) {
  1506. return writeFloat(this, value, offset, true, noAssert);
  1507. }, "writeFloatLE");
  1508. Buffer4.prototype.writeFloatBE = /* @__PURE__ */ __name(function writeFloatBE(value, offset, noAssert) {
  1509. return writeFloat(this, value, offset, false, noAssert);
  1510. }, "writeFloatBE");
  1511. function writeDouble(buf, value, offset, littleEndian, noAssert) {
  1512. value = +value;
  1513. offset = offset >>> 0;
  1514. if (!noAssert) {
  1515. checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292);
  1516. }
  1517. ieee754.write(buf, value, offset, littleEndian, 52, 8);
  1518. return offset + 8;
  1519. }
  1520. __name(writeDouble, "writeDouble");
  1521. Buffer4.prototype.writeDoubleLE = /* @__PURE__ */ __name(function writeDoubleLE(value, offset, noAssert) {
  1522. return writeDouble(this, value, offset, true, noAssert);
  1523. }, "writeDoubleLE");
  1524. Buffer4.prototype.writeDoubleBE = /* @__PURE__ */ __name(function writeDoubleBE(value, offset, noAssert) {
  1525. return writeDouble(this, value, offset, false, noAssert);
  1526. }, "writeDoubleBE");
  1527. Buffer4.prototype.copy = /* @__PURE__ */ __name(function copy(target, targetStart, start, end) {
  1528. if (!Buffer4.isBuffer(target)) throw new TypeError("argument should be a Buffer");
  1529. if (!start) start = 0;
  1530. if (!end && end !== 0) end = this.length;
  1531. if (targetStart >= target.length) targetStart = target.length;
  1532. if (!targetStart) targetStart = 0;
  1533. if (end > 0 && end < start) end = start;
  1534. if (end === start) return 0;
  1535. if (target.length === 0 || this.length === 0) return 0;
  1536. if (targetStart < 0) {
  1537. throw new RangeError("targetStart out of bounds");
  1538. }
  1539. if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
  1540. if (end < 0) throw new RangeError("sourceEnd out of bounds");
  1541. if (end > this.length) end = this.length;
  1542. if (target.length - targetStart < end - start) {
  1543. end = target.length - targetStart + start;
  1544. }
  1545. const len = end - start;
  1546. if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
  1547. this.copyWithin(targetStart, start, end);
  1548. } else {
  1549. Uint8Array.prototype.set.call(
  1550. target,
  1551. this.subarray(start, end),
  1552. targetStart
  1553. );
  1554. }
  1555. return len;
  1556. }, "copy");
  1557. Buffer4.prototype.fill = /* @__PURE__ */ __name(function fill(val, start, end, encoding) {
  1558. if (typeof val === "string") {
  1559. if (typeof start === "string") {
  1560. encoding = start;
  1561. start = 0;
  1562. end = this.length;
  1563. } else if (typeof end === "string") {
  1564. encoding = end;
  1565. end = this.length;
  1566. }
  1567. if (encoding !== void 0 && typeof encoding !== "string") {
  1568. throw new TypeError("encoding must be a string");
  1569. }
  1570. if (typeof encoding === "string" && !Buffer4.isEncoding(encoding)) {
  1571. throw new TypeError("Unknown encoding: " + encoding);
  1572. }
  1573. if (val.length === 1) {
  1574. const code = val.charCodeAt(0);
  1575. if (encoding === "utf8" && code < 128 || encoding === "latin1") {
  1576. val = code;
  1577. }
  1578. }
  1579. } else if (typeof val === "number") {
  1580. val = val & 255;
  1581. } else if (typeof val === "boolean") {
  1582. val = Number(val);
  1583. }
  1584. if (start < 0 || this.length < start || this.length < end) {
  1585. throw new RangeError("Out of range index");
  1586. }
  1587. if (end <= start) {
  1588. return this;
  1589. }
  1590. start = start >>> 0;
  1591. end = end === void 0 ? this.length : end >>> 0;
  1592. if (!val) val = 0;
  1593. let i;
  1594. if (typeof val === "number") {
  1595. for (i = start; i < end; ++i) {
  1596. this[i] = val;
  1597. }
  1598. } else {
  1599. const bytes = Buffer4.isBuffer(val) ? val : Buffer4.from(val, encoding);
  1600. const len = bytes.length;
  1601. if (len === 0) {
  1602. throw new TypeError('The value "' + val + '" is invalid for argument "value"');
  1603. }
  1604. for (i = 0; i < end - start; ++i) {
  1605. this[i + start] = bytes[i % len];
  1606. }
  1607. }
  1608. return this;
  1609. }, "fill");
  1610. var errors = {};
  1611. function E(sym, getMessage, Base) {
  1612. errors[sym] = class NodeError extends Base {
  1613. static {
  1614. __name(this, "NodeError");
  1615. }
  1616. constructor() {
  1617. super();
  1618. Object.defineProperty(this, "message", {
  1619. value: getMessage.apply(this, arguments),
  1620. writable: true,
  1621. configurable: true
  1622. });
  1623. this.name = `${this.name} [${sym}]`;
  1624. this.stack;
  1625. delete this.name;
  1626. }
  1627. get code() {
  1628. return sym;
  1629. }
  1630. set code(value) {
  1631. Object.defineProperty(this, "code", {
  1632. configurable: true,
  1633. enumerable: true,
  1634. value,
  1635. writable: true
  1636. });
  1637. }
  1638. toString() {
  1639. return `${this.name} [${sym}]: ${this.message}`;
  1640. }
  1641. };
  1642. }
  1643. __name(E, "E");
  1644. E(
  1645. "ERR_BUFFER_OUT_OF_BOUNDS",
  1646. function(name) {
  1647. if (name) {
  1648. return `${name} is outside of buffer bounds`;
  1649. }
  1650. return "Attempt to access memory outside buffer bounds";
  1651. },
  1652. RangeError
  1653. );
  1654. E(
  1655. "ERR_INVALID_ARG_TYPE",
  1656. function(name, actual) {
  1657. return `The "${name}" argument must be of type number. Received type ${typeof actual}`;
  1658. },
  1659. TypeError
  1660. );
  1661. E(
  1662. "ERR_OUT_OF_RANGE",
  1663. function(str, range, input) {
  1664. let msg = `The value of "${str}" is out of range.`;
  1665. let received = input;
  1666. if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
  1667. received = addNumericalSeparator(String(input));
  1668. } else if (typeof input === "bigint") {
  1669. received = String(input);
  1670. if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
  1671. received = addNumericalSeparator(received);
  1672. }
  1673. received += "n";
  1674. }
  1675. msg += ` It must be ${range}. Received ${received}`;
  1676. return msg;
  1677. },
  1678. RangeError
  1679. );
  1680. function addNumericalSeparator(val) {
  1681. let res = "";
  1682. let i = val.length;
  1683. const start = val[0] === "-" ? 1 : 0;
  1684. for (; i >= start + 4; i -= 3) {
  1685. res = `_${val.slice(i - 3, i)}${res}`;
  1686. }
  1687. return `${val.slice(0, i)}${res}`;
  1688. }
  1689. __name(addNumericalSeparator, "addNumericalSeparator");
  1690. function checkBounds(buf, offset, byteLength2) {
  1691. validateNumber(offset, "offset");
  1692. if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) {
  1693. boundsError(offset, buf.length - (byteLength2 + 1));
  1694. }
  1695. }
  1696. __name(checkBounds, "checkBounds");
  1697. function checkIntBI(value, min, max, buf, offset, byteLength2) {
  1698. if (value > max || value < min) {
  1699. const n = typeof min === "bigint" ? "n" : "";
  1700. let range;
  1701. if (byteLength2 > 3) {
  1702. if (min === 0 || min === BigInt(0)) {
  1703. range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`;
  1704. } else {
  1705. range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`;
  1706. }
  1707. } else {
  1708. range = `>= ${min}${n} and <= ${max}${n}`;
  1709. }
  1710. throw new errors.ERR_OUT_OF_RANGE("value", range, value);
  1711. }
  1712. checkBounds(buf, offset, byteLength2);
  1713. }
  1714. __name(checkIntBI, "checkIntBI");
  1715. function validateNumber(value, name) {
  1716. if (typeof value !== "number") {
  1717. throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value);
  1718. }
  1719. }
  1720. __name(validateNumber, "validateNumber");
  1721. function boundsError(value, length, type) {
  1722. if (Math.floor(value) !== value) {
  1723. validateNumber(value, type);
  1724. throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value);
  1725. }
  1726. if (length < 0) {
  1727. throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
  1728. }
  1729. throw new errors.ERR_OUT_OF_RANGE(
  1730. type || "offset",
  1731. `>= ${type ? 1 : 0} and <= ${length}`,
  1732. value
  1733. );
  1734. }
  1735. __name(boundsError, "boundsError");
  1736. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
  1737. function base64clean(str) {
  1738. str = str.split("=")[0];
  1739. str = str.trim().replace(INVALID_BASE64_RE, "");
  1740. if (str.length < 2) return "";
  1741. while (str.length % 4 !== 0) {
  1742. str = str + "=";
  1743. }
  1744. return str;
  1745. }
  1746. __name(base64clean, "base64clean");
  1747. function utf8ToBytes(string, units) {
  1748. units = units || Infinity;
  1749. let codePoint;
  1750. const length = string.length;
  1751. let leadSurrogate = null;
  1752. const bytes = [];
  1753. for (let i = 0; i < length; ++i) {
  1754. codePoint = string.charCodeAt(i);
  1755. if (codePoint > 55295 && codePoint < 57344) {
  1756. if (!leadSurrogate) {
  1757. if (codePoint > 56319) {
  1758. if ((units -= 3) > -1) bytes.push(239, 191, 189);
  1759. continue;
  1760. } else if (i + 1 === length) {
  1761. if ((units -= 3) > -1) bytes.push(239, 191, 189);
  1762. continue;
  1763. }
  1764. leadSurrogate = codePoint;
  1765. continue;
  1766. }
  1767. if (codePoint < 56320) {
  1768. if ((units -= 3) > -1) bytes.push(239, 191, 189);
  1769. leadSurrogate = codePoint;
  1770. continue;
  1771. }
  1772. codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
  1773. } else if (leadSurrogate) {
  1774. if ((units -= 3) > -1) bytes.push(239, 191, 189);
  1775. }
  1776. leadSurrogate = null;
  1777. if (codePoint < 128) {
  1778. if ((units -= 1) < 0) break;
  1779. bytes.push(codePoint);
  1780. } else if (codePoint < 2048) {
  1781. if ((units -= 2) < 0) break;
  1782. bytes.push(
  1783. codePoint >> 6 | 192,
  1784. codePoint & 63 | 128
  1785. );
  1786. } else if (codePoint < 65536) {
  1787. if ((units -= 3) < 0) break;
  1788. bytes.push(
  1789. codePoint >> 12 | 224,
  1790. codePoint >> 6 & 63 | 128,
  1791. codePoint & 63 | 128
  1792. );
  1793. } else if (codePoint < 1114112) {
  1794. if ((units -= 4) < 0) break;
  1795. bytes.push(
  1796. codePoint >> 18 | 240,
  1797. codePoint >> 12 & 63 | 128,
  1798. codePoint >> 6 & 63 | 128,
  1799. codePoint & 63 | 128
  1800. );
  1801. } else {
  1802. throw new Error("Invalid code point");
  1803. }
  1804. }
  1805. return bytes;
  1806. }
  1807. __name(utf8ToBytes, "utf8ToBytes");
  1808. function asciiToBytes(str) {
  1809. const byteArray = [];
  1810. for (let i = 0; i < str.length; ++i) {
  1811. byteArray.push(str.charCodeAt(i) & 255);
  1812. }
  1813. return byteArray;
  1814. }
  1815. __name(asciiToBytes, "asciiToBytes");
  1816. function utf16leToBytes(str, units) {
  1817. let c, hi, lo;
  1818. const byteArray = [];
  1819. for (let i = 0; i < str.length; ++i) {
  1820. if ((units -= 2) < 0) break;
  1821. c = str.charCodeAt(i);
  1822. hi = c >> 8;
  1823. lo = c % 256;
  1824. byteArray.push(lo);
  1825. byteArray.push(hi);
  1826. }
  1827. return byteArray;
  1828. }
  1829. __name(utf16leToBytes, "utf16leToBytes");
  1830. function base64ToBytes(str) {
  1831. return base64.toByteArray(base64clean(str));
  1832. }
  1833. __name(base64ToBytes, "base64ToBytes");
  1834. function blitBuffer(src, dst, offset, length) {
  1835. let i;
  1836. for (i = 0; i < length; ++i) {
  1837. if (i + offset >= dst.length || i >= src.length) break;
  1838. dst[i + offset] = src[i];
  1839. }
  1840. return i;
  1841. }
  1842. __name(blitBuffer, "blitBuffer");
  1843. function isInstance(obj, type) {
  1844. return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
  1845. }
  1846. __name(isInstance, "isInstance");
  1847. function numberIsNaN(obj) {
  1848. return obj !== obj;
  1849. }
  1850. __name(numberIsNaN, "numberIsNaN");
  1851. var hexSliceLookupTable = function() {
  1852. const alphabet = "0123456789abcdef";
  1853. const table = new Array(256);
  1854. for (let i = 0; i < 16; ++i) {
  1855. const i16 = i * 16;
  1856. for (let j = 0; j < 16; ++j) {
  1857. table[i16 + j] = alphabet[i] + alphabet[j];
  1858. }
  1859. }
  1860. return table;
  1861. }();
  1862. function defineBigIntMethod(fn) {
  1863. return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
  1864. }
  1865. __name(defineBigIntMethod, "defineBigIntMethod");
  1866. function BufferBigIntNotDefined() {
  1867. throw new Error("BigInt not supported");
  1868. }
  1869. __name(BufferBigIntNotDefined, "BufferBigIntNotDefined");
  1870. }
  1871. });
  1872. // node_modules/readable-stream/lib/ours/primordials.js
  1873. var require_primordials = __commonJS({
  1874. "node_modules/readable-stream/lib/ours/primordials.js"(exports, module) {
  1875. "use strict";
  1876. module.exports = {
  1877. ArrayIsArray: /* @__PURE__ */ __name(function(self2) {
  1878. return Array.isArray(self2);
  1879. }, "ArrayIsArray"),
  1880. ArrayPrototypeIncludes: /* @__PURE__ */ __name(function(self2, el) {
  1881. return self2.includes(el);
  1882. }, "ArrayPrototypeIncludes"),
  1883. ArrayPrototypeIndexOf: /* @__PURE__ */ __name(function(self2, el) {
  1884. return self2.indexOf(el);
  1885. }, "ArrayPrototypeIndexOf"),
  1886. ArrayPrototypeJoin: /* @__PURE__ */ __name(function(self2, sep) {
  1887. return self2.join(sep);
  1888. }, "ArrayPrototypeJoin"),
  1889. ArrayPrototypeMap: /* @__PURE__ */ __name(function(self2, fn) {
  1890. return self2.map(fn);
  1891. }, "ArrayPrototypeMap"),
  1892. ArrayPrototypePop: /* @__PURE__ */ __name(function(self2, el) {
  1893. return self2.pop(el);
  1894. }, "ArrayPrototypePop"),
  1895. ArrayPrototypePush: /* @__PURE__ */ __name(function(self2, el) {
  1896. return self2.push(el);
  1897. }, "ArrayPrototypePush"),
  1898. ArrayPrototypeSlice: /* @__PURE__ */ __name(function(self2, start, end) {
  1899. return self2.slice(start, end);
  1900. }, "ArrayPrototypeSlice"),
  1901. Error,
  1902. FunctionPrototypeCall: /* @__PURE__ */ __name(function(fn, thisArgs, ...args) {
  1903. return fn.call(thisArgs, ...args);
  1904. }, "FunctionPrototypeCall"),
  1905. FunctionPrototypeSymbolHasInstance: /* @__PURE__ */ __name(function(self2, instance) {
  1906. return Function.prototype[Symbol.hasInstance].call(self2, instance);
  1907. }, "FunctionPrototypeSymbolHasInstance"),
  1908. MathFloor: Math.floor,
  1909. Number,
  1910. NumberIsInteger: Number.isInteger,
  1911. NumberIsNaN: Number.isNaN,
  1912. NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,
  1913. NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,
  1914. NumberParseInt: Number.parseInt,
  1915. ObjectDefineProperties: /* @__PURE__ */ __name(function(self2, props) {
  1916. return Object.defineProperties(self2, props);
  1917. }, "ObjectDefineProperties"),
  1918. ObjectDefineProperty: /* @__PURE__ */ __name(function(self2, name, prop) {
  1919. return Object.defineProperty(self2, name, prop);
  1920. }, "ObjectDefineProperty"),
  1921. ObjectGetOwnPropertyDescriptor: /* @__PURE__ */ __name(function(self2, name) {
  1922. return Object.getOwnPropertyDescriptor(self2, name);
  1923. }, "ObjectGetOwnPropertyDescriptor"),
  1924. ObjectKeys: /* @__PURE__ */ __name(function(obj) {
  1925. return Object.keys(obj);
  1926. }, "ObjectKeys"),
  1927. ObjectSetPrototypeOf: /* @__PURE__ */ __name(function(target, proto) {
  1928. return Object.setPrototypeOf(target, proto);
  1929. }, "ObjectSetPrototypeOf"),
  1930. Promise,
  1931. PromisePrototypeCatch: /* @__PURE__ */ __name(function(self2, fn) {
  1932. return self2.catch(fn);
  1933. }, "PromisePrototypeCatch"),
  1934. PromisePrototypeThen: /* @__PURE__ */ __name(function(self2, thenFn, catchFn) {
  1935. return self2.then(thenFn, catchFn);
  1936. }, "PromisePrototypeThen"),
  1937. PromiseReject: /* @__PURE__ */ __name(function(err) {
  1938. return Promise.reject(err);
  1939. }, "PromiseReject"),
  1940. PromiseResolve: /* @__PURE__ */ __name(function(val) {
  1941. return Promise.resolve(val);
  1942. }, "PromiseResolve"),
  1943. ReflectApply: Reflect.apply,
  1944. RegExpPrototypeTest: /* @__PURE__ */ __name(function(self2, value) {
  1945. return self2.test(value);
  1946. }, "RegExpPrototypeTest"),
  1947. SafeSet: Set,
  1948. String,
  1949. StringPrototypeSlice: /* @__PURE__ */ __name(function(self2, start, end) {
  1950. return self2.slice(start, end);
  1951. }, "StringPrototypeSlice"),
  1952. StringPrototypeToLowerCase: /* @__PURE__ */ __name(function(self2) {
  1953. return self2.toLowerCase();
  1954. }, "StringPrototypeToLowerCase"),
  1955. StringPrototypeToUpperCase: /* @__PURE__ */ __name(function(self2) {
  1956. return self2.toUpperCase();
  1957. }, "StringPrototypeToUpperCase"),
  1958. StringPrototypeTrim: /* @__PURE__ */ __name(function(self2) {
  1959. return self2.trim();
  1960. }, "StringPrototypeTrim"),
  1961. Symbol,
  1962. SymbolFor: Symbol.for,
  1963. SymbolAsyncIterator: Symbol.asyncIterator,
  1964. SymbolHasInstance: Symbol.hasInstance,
  1965. SymbolIterator: Symbol.iterator,
  1966. SymbolDispose: Symbol.dispose || Symbol("Symbol.dispose"),
  1967. SymbolAsyncDispose: Symbol.asyncDispose || Symbol("Symbol.asyncDispose"),
  1968. TypedArrayPrototypeSet: /* @__PURE__ */ __name(function(self2, buf, len) {
  1969. return self2.set(buf, len);
  1970. }, "TypedArrayPrototypeSet"),
  1971. Boolean,
  1972. Uint8Array
  1973. };
  1974. }
  1975. });
  1976. // node_modules/abort-controller/browser.js
  1977. var require_browser = __commonJS({
  1978. "node_modules/abort-controller/browser.js"(exports, module) {
  1979. "use strict";
  1980. var { AbortController, AbortSignal } = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : (
  1981. /* otherwise */
  1982. void 0
  1983. );
  1984. module.exports = AbortController;
  1985. module.exports.AbortSignal = AbortSignal;
  1986. module.exports.default = AbortController;
  1987. }
  1988. });
  1989. // node_modules/events/events.js
  1990. var require_events = __commonJS({
  1991. "node_modules/events/events.js"(exports, module) {
  1992. "use strict";
  1993. var R = typeof Reflect === "object" ? Reflect : null;
  1994. var ReflectApply = R && typeof R.apply === "function" ? R.apply : /* @__PURE__ */ __name(function ReflectApply2(target, receiver, args) {
  1995. return Function.prototype.apply.call(target, receiver, args);
  1996. }, "ReflectApply");
  1997. var ReflectOwnKeys;
  1998. if (R && typeof R.ownKeys === "function") {
  1999. ReflectOwnKeys = R.ownKeys;
  2000. } else if (Object.getOwnPropertySymbols) {
  2001. ReflectOwnKeys = /* @__PURE__ */ __name(function ReflectOwnKeys2(target) {
  2002. return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
  2003. }, "ReflectOwnKeys");
  2004. } else {
  2005. ReflectOwnKeys = /* @__PURE__ */ __name(function ReflectOwnKeys2(target) {
  2006. return Object.getOwnPropertyNames(target);
  2007. }, "ReflectOwnKeys");
  2008. }
  2009. function ProcessEmitWarning(warning) {
  2010. if (console && console.warn) console.warn(warning);
  2011. }
  2012. __name(ProcessEmitWarning, "ProcessEmitWarning");
  2013. var NumberIsNaN = Number.isNaN || /* @__PURE__ */ __name(function NumberIsNaN2(value) {
  2014. return value !== value;
  2015. }, "NumberIsNaN");
  2016. function EventEmitter() {
  2017. EventEmitter.init.call(this);
  2018. }
  2019. __name(EventEmitter, "EventEmitter");
  2020. module.exports = EventEmitter;
  2021. module.exports.once = once;
  2022. EventEmitter.EventEmitter = EventEmitter;
  2023. EventEmitter.prototype._events = void 0;
  2024. EventEmitter.prototype._eventsCount = 0;
  2025. EventEmitter.prototype._maxListeners = void 0;
  2026. var defaultMaxListeners = 10;
  2027. function checkListener(listener) {
  2028. if (typeof listener !== "function") {
  2029. throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  2030. }
  2031. }
  2032. __name(checkListener, "checkListener");
  2033. Object.defineProperty(EventEmitter, "defaultMaxListeners", {
  2034. enumerable: true,
  2035. get: /* @__PURE__ */ __name(function() {
  2036. return defaultMaxListeners;
  2037. }, "get"),
  2038. set: /* @__PURE__ */ __name(function(arg) {
  2039. if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) {
  2040. throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".");
  2041. }
  2042. defaultMaxListeners = arg;
  2043. }, "set")
  2044. });
  2045. EventEmitter.init = function() {
  2046. if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
  2047. this._events = /* @__PURE__ */ Object.create(null);
  2048. this._eventsCount = 0;
  2049. }
  2050. this._maxListeners = this._maxListeners || void 0;
  2051. };
  2052. EventEmitter.prototype.setMaxListeners = /* @__PURE__ */ __name(function setMaxListeners(n) {
  2053. if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) {
  2054. throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + ".");
  2055. }
  2056. this._maxListeners = n;
  2057. return this;
  2058. }, "setMaxListeners");
  2059. function _getMaxListeners(that) {
  2060. if (that._maxListeners === void 0)
  2061. return EventEmitter.defaultMaxListeners;
  2062. return that._maxListeners;
  2063. }
  2064. __name(_getMaxListeners, "_getMaxListeners");
  2065. EventEmitter.prototype.getMaxListeners = /* @__PURE__ */ __name(function getMaxListeners() {
  2066. return _getMaxListeners(this);
  2067. }, "getMaxListeners");
  2068. EventEmitter.prototype.emit = /* @__PURE__ */ __name(function emit(type) {
  2069. var args = [];
  2070. for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  2071. var doError = type === "error";
  2072. var events = this._events;
  2073. if (events !== void 0)
  2074. doError = doError && events.error === void 0;
  2075. else if (!doError)
  2076. return false;
  2077. if (doError) {
  2078. var er;
  2079. if (args.length > 0)
  2080. er = args[0];
  2081. if (er instanceof Error) {
  2082. throw er;
  2083. }
  2084. var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
  2085. err.context = er;
  2086. throw err;
  2087. }
  2088. var handler = events[type];
  2089. if (handler === void 0)
  2090. return false;
  2091. if (typeof handler === "function") {
  2092. ReflectApply(handler, this, args);
  2093. } else {
  2094. var len = handler.length;
  2095. var listeners = arrayClone(handler, len);
  2096. for (var i = 0; i < len; ++i)
  2097. ReflectApply(listeners[i], this, args);
  2098. }
  2099. return true;
  2100. }, "emit");
  2101. function _addListener(target, type, listener, prepend) {
  2102. var m;
  2103. var events;
  2104. var existing;
  2105. checkListener(listener);
  2106. events = target._events;
  2107. if (events === void 0) {
  2108. events = target._events = /* @__PURE__ */ Object.create(null);
  2109. target._eventsCount = 0;
  2110. } else {
  2111. if (events.newListener !== void 0) {
  2112. target.emit(
  2113. "newListener",
  2114. type,
  2115. listener.listener ? listener.listener : listener
  2116. );
  2117. events = target._events;
  2118. }
  2119. existing = events[type];
  2120. }
  2121. if (existing === void 0) {
  2122. existing = events[type] = listener;
  2123. ++target._eventsCount;
  2124. } else {
  2125. if (typeof existing === "function") {
  2126. existing = events[type] = prepend ? [listener, existing] : [existing, listener];
  2127. } else if (prepend) {
  2128. existing.unshift(listener);
  2129. } else {
  2130. existing.push(listener);
  2131. }
  2132. m = _getMaxListeners(target);
  2133. if (m > 0 && existing.length > m && !existing.warned) {
  2134. existing.warned = true;
  2135. var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
  2136. w.name = "MaxListenersExceededWarning";
  2137. w.emitter = target;
  2138. w.type = type;
  2139. w.count = existing.length;
  2140. ProcessEmitWarning(w);
  2141. }
  2142. }
  2143. return target;
  2144. }
  2145. __name(_addListener, "_addListener");
  2146. EventEmitter.prototype.addListener = /* @__PURE__ */ __name(function addListener(type, listener) {
  2147. return _addListener(this, type, listener, false);
  2148. }, "addListener");
  2149. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  2150. EventEmitter.prototype.prependListener = /* @__PURE__ */ __name(function prependListener(type, listener) {
  2151. return _addListener(this, type, listener, true);
  2152. }, "prependListener");
  2153. function onceWrapper() {
  2154. if (!this.fired) {
  2155. this.target.removeListener(this.type, this.wrapFn);
  2156. this.fired = true;
  2157. if (arguments.length === 0)
  2158. return this.listener.call(this.target);
  2159. return this.listener.apply(this.target, arguments);
  2160. }
  2161. }
  2162. __name(onceWrapper, "onceWrapper");
  2163. function _onceWrap(target, type, listener) {
  2164. var state = { fired: false, wrapFn: void 0, target, type, listener };
  2165. var wrapped = onceWrapper.bind(state);
  2166. wrapped.listener = listener;
  2167. state.wrapFn = wrapped;
  2168. return wrapped;
  2169. }
  2170. __name(_onceWrap, "_onceWrap");
  2171. EventEmitter.prototype.once = /* @__PURE__ */ __name(function once2(type, listener) {
  2172. checkListener(listener);
  2173. this.on(type, _onceWrap(this, type, listener));
  2174. return this;
  2175. }, "once");
  2176. EventEmitter.prototype.prependOnceListener = /* @__PURE__ */ __name(function prependOnceListener(type, listener) {
  2177. checkListener(listener);
  2178. this.prependListener(type, _onceWrap(this, type, listener));
  2179. return this;
  2180. }, "prependOnceListener");
  2181. EventEmitter.prototype.removeListener = /* @__PURE__ */ __name(function removeListener(type, listener) {
  2182. var list, events, position, i, originalListener;
  2183. checkListener(listener);
  2184. events = this._events;
  2185. if (events === void 0)
  2186. return this;
  2187. list = events[type];
  2188. if (list === void 0)
  2189. return this;
  2190. if (list === listener || list.listener === listener) {
  2191. if (--this._eventsCount === 0)
  2192. this._events = /* @__PURE__ */ Object.create(null);
  2193. else {
  2194. delete events[type];
  2195. if (events.removeListener)
  2196. this.emit("removeListener", type, list.listener || listener);
  2197. }
  2198. } else if (typeof list !== "function") {
  2199. position = -1;
  2200. for (i = list.length - 1; i >= 0; i--) {
  2201. if (list[i] === listener || list[i].listener === listener) {
  2202. originalListener = list[i].listener;
  2203. position = i;
  2204. break;
  2205. }
  2206. }
  2207. if (position < 0)
  2208. return this;
  2209. if (position === 0)
  2210. list.shift();
  2211. else {
  2212. spliceOne(list, position);
  2213. }
  2214. if (list.length === 1)
  2215. events[type] = list[0];
  2216. if (events.removeListener !== void 0)
  2217. this.emit("removeListener", type, originalListener || listener);
  2218. }
  2219. return this;
  2220. }, "removeListener");
  2221. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  2222. EventEmitter.prototype.removeAllListeners = /* @__PURE__ */ __name(function removeAllListeners(type) {
  2223. var listeners, events, i;
  2224. events = this._events;
  2225. if (events === void 0)
  2226. return this;
  2227. if (events.removeListener === void 0) {
  2228. if (arguments.length === 0) {
  2229. this._events = /* @__PURE__ */ Object.create(null);
  2230. this._eventsCount = 0;
  2231. } else if (events[type] !== void 0) {
  2232. if (--this._eventsCount === 0)
  2233. this._events = /* @__PURE__ */ Object.create(null);
  2234. else
  2235. delete events[type];
  2236. }
  2237. return this;
  2238. }
  2239. if (arguments.length === 0) {
  2240. var keys = Object.keys(events);
  2241. var key;
  2242. for (i = 0; i < keys.length; ++i) {
  2243. key = keys[i];
  2244. if (key === "removeListener") continue;
  2245. this.removeAllListeners(key);
  2246. }
  2247. this.removeAllListeners("removeListener");
  2248. this._events = /* @__PURE__ */ Object.create(null);
  2249. this._eventsCount = 0;
  2250. return this;
  2251. }
  2252. listeners = events[type];
  2253. if (typeof listeners === "function") {
  2254. this.removeListener(type, listeners);
  2255. } else if (listeners !== void 0) {
  2256. for (i = listeners.length - 1; i >= 0; i--) {
  2257. this.removeListener(type, listeners[i]);
  2258. }
  2259. }
  2260. return this;
  2261. }, "removeAllListeners");
  2262. function _listeners(target, type, unwrap) {
  2263. var events = target._events;
  2264. if (events === void 0)
  2265. return [];
  2266. var evlistener = events[type];
  2267. if (evlistener === void 0)
  2268. return [];
  2269. if (typeof evlistener === "function")
  2270. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  2271. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  2272. }
  2273. __name(_listeners, "_listeners");
  2274. EventEmitter.prototype.listeners = /* @__PURE__ */ __name(function listeners(type) {
  2275. return _listeners(this, type, true);
  2276. }, "listeners");
  2277. EventEmitter.prototype.rawListeners = /* @__PURE__ */ __name(function rawListeners(type) {
  2278. return _listeners(this, type, false);
  2279. }, "rawListeners");
  2280. EventEmitter.listenerCount = function(emitter, type) {
  2281. if (typeof emitter.listenerCount === "function") {
  2282. return emitter.listenerCount(type);
  2283. } else {
  2284. return listenerCount.call(emitter, type);
  2285. }
  2286. };
  2287. EventEmitter.prototype.listenerCount = listenerCount;
  2288. function listenerCount(type) {
  2289. var events = this._events;
  2290. if (events !== void 0) {
  2291. var evlistener = events[type];
  2292. if (typeof evlistener === "function") {
  2293. return 1;
  2294. } else if (evlistener !== void 0) {
  2295. return evlistener.length;
  2296. }
  2297. }
  2298. return 0;
  2299. }
  2300. __name(listenerCount, "listenerCount");
  2301. EventEmitter.prototype.eventNames = /* @__PURE__ */ __name(function eventNames() {
  2302. return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
  2303. }, "eventNames");
  2304. function arrayClone(arr, n) {
  2305. var copy = new Array(n);
  2306. for (var i = 0; i < n; ++i)
  2307. copy[i] = arr[i];
  2308. return copy;
  2309. }
  2310. __name(arrayClone, "arrayClone");
  2311. function spliceOne(list, index) {
  2312. for (; index + 1 < list.length; index++)
  2313. list[index] = list[index + 1];
  2314. list.pop();
  2315. }
  2316. __name(spliceOne, "spliceOne");
  2317. function unwrapListeners(arr) {
  2318. var ret = new Array(arr.length);
  2319. for (var i = 0; i < ret.length; ++i) {
  2320. ret[i] = arr[i].listener || arr[i];
  2321. }
  2322. return ret;
  2323. }
  2324. __name(unwrapListeners, "unwrapListeners");
  2325. function once(emitter, name) {
  2326. return new Promise(function(resolve2, reject) {
  2327. function errorListener(err) {
  2328. emitter.removeListener(name, resolver);
  2329. reject(err);
  2330. }
  2331. __name(errorListener, "errorListener");
  2332. function resolver() {
  2333. if (typeof emitter.removeListener === "function") {
  2334. emitter.removeListener("error", errorListener);
  2335. }
  2336. resolve2([].slice.call(arguments));
  2337. }
  2338. __name(resolver, "resolver");
  2339. ;
  2340. eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
  2341. if (name !== "error") {
  2342. addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
  2343. }
  2344. });
  2345. }
  2346. __name(once, "once");
  2347. function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
  2348. if (typeof emitter.on === "function") {
  2349. eventTargetAgnosticAddListener(emitter, "error", handler, flags);
  2350. }
  2351. }
  2352. __name(addErrorHandlerIfEventEmitter, "addErrorHandlerIfEventEmitter");
  2353. function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
  2354. if (typeof emitter.on === "function") {
  2355. if (flags.once) {
  2356. emitter.once(name, listener);
  2357. } else {
  2358. emitter.on(name, listener);
  2359. }
  2360. } else if (typeof emitter.addEventListener === "function") {
  2361. emitter.addEventListener(name, /* @__PURE__ */ __name(function wrapListener(arg) {
  2362. if (flags.once) {
  2363. emitter.removeEventListener(name, wrapListener);
  2364. }
  2365. listener(arg);
  2366. }, "wrapListener"));
  2367. } else {
  2368. throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
  2369. }
  2370. }
  2371. __name(eventTargetAgnosticAddListener, "eventTargetAgnosticAddListener");
  2372. }
  2373. });
  2374. // node_modules/readable-stream/lib/ours/util.js
  2375. var require_util = __commonJS({
  2376. "node_modules/readable-stream/lib/ours/util.js"(exports, module) {
  2377. "use strict";
  2378. var bufferModule = require_buffer();
  2379. var { kResistStopPropagation, SymbolDispose } = require_primordials();
  2380. var AbortSignal = globalThis.AbortSignal || require_browser().AbortSignal;
  2381. var AbortController = globalThis.AbortController || require_browser().AbortController;
  2382. var AsyncFunction = Object.getPrototypeOf(async function() {
  2383. }).constructor;
  2384. var Blob2 = globalThis.Blob || bufferModule.Blob;
  2385. var isBlob = typeof Blob2 !== "undefined" ? /* @__PURE__ */ __name(function isBlob2(b) {
  2386. return b instanceof Blob2;
  2387. }, "isBlob") : /* @__PURE__ */ __name(function isBlob2(b) {
  2388. return false;
  2389. }, "isBlob");
  2390. var validateAbortSignal = /* @__PURE__ */ __name((signal, name) => {
  2391. if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) {
  2392. throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal);
  2393. }
  2394. }, "validateAbortSignal");
  2395. var validateFunction = /* @__PURE__ */ __name((value, name) => {
  2396. if (typeof value !== "function") throw new ERR_INVALID_ARG_TYPE(name, "Function", value);
  2397. }, "validateFunction");
  2398. var AggregateError = class extends Error {
  2399. static {
  2400. __name(this, "AggregateError");
  2401. }
  2402. constructor(errors) {
  2403. if (!Array.isArray(errors)) {
  2404. throw new TypeError(`Expected input to be an Array, got ${typeof errors}`);
  2405. }
  2406. let message = "";
  2407. for (let i = 0; i < errors.length; i++) {
  2408. message += ` ${errors[i].stack}
  2409. `;
  2410. }
  2411. super(message);
  2412. this.name = "AggregateError";
  2413. this.errors = errors;
  2414. }
  2415. };
  2416. module.exports = {
  2417. AggregateError,
  2418. kEmptyObject: Object.freeze({}),
  2419. once: /* @__PURE__ */ __name(function(callback) {
  2420. let called = false;
  2421. return function(...args) {
  2422. if (called) {
  2423. return;
  2424. }
  2425. called = true;
  2426. callback.apply(this, args);
  2427. };
  2428. }, "once"),
  2429. createDeferredPromise: /* @__PURE__ */ __name(function() {
  2430. let resolve2;
  2431. let reject;
  2432. const promise = new Promise((res, rej) => {
  2433. resolve2 = res;
  2434. reject = rej;
  2435. });
  2436. return {
  2437. promise,
  2438. resolve: resolve2,
  2439. reject
  2440. };
  2441. }, "createDeferredPromise"),
  2442. promisify: /* @__PURE__ */ __name(function(fn) {
  2443. return new Promise((resolve2, reject) => {
  2444. fn((err, ...args) => {
  2445. if (err) {
  2446. return reject(err);
  2447. }
  2448. return resolve2(...args);
  2449. });
  2450. });
  2451. }, "promisify"),
  2452. debuglog: /* @__PURE__ */ __name(function() {
  2453. return function() {
  2454. };
  2455. }, "debuglog"),
  2456. format: /* @__PURE__ */ __name(function(format, ...args) {
  2457. return format.replace(/%([sdifj])/g, function(...[_unused, type]) {
  2458. const replacement = args.shift();
  2459. if (type === "f") {
  2460. return replacement.toFixed(6);
  2461. } else if (type === "j") {
  2462. return JSON.stringify(replacement);
  2463. } else if (type === "s" && typeof replacement === "object") {
  2464. const ctor = replacement.constructor !== Object ? replacement.constructor.name : "";
  2465. return `${ctor} {}`.trim();
  2466. } else {
  2467. return replacement.toString();
  2468. }
  2469. });
  2470. }, "format"),
  2471. inspect: /* @__PURE__ */ __name(function(value) {
  2472. switch (typeof value) {
  2473. case "string":
  2474. if (value.includes("'")) {
  2475. if (!value.includes('"')) {
  2476. return `"${value}"`;
  2477. } else if (!value.includes("`") && !value.includes("${")) {
  2478. return `\`${value}\``;
  2479. }
  2480. }
  2481. return `'${value}'`;
  2482. case "number":
  2483. if (isNaN(value)) {
  2484. return "NaN";
  2485. } else if (Object.is(value, -0)) {
  2486. return String(value);
  2487. }
  2488. return value;
  2489. case "bigint":
  2490. return `${String(value)}n`;
  2491. case "boolean":
  2492. case "undefined":
  2493. return String(value);
  2494. case "object":
  2495. return "{}";
  2496. }
  2497. }, "inspect"),
  2498. types: {
  2499. isAsyncFunction: /* @__PURE__ */ __name(function(fn) {
  2500. return fn instanceof AsyncFunction;
  2501. }, "isAsyncFunction"),
  2502. isArrayBufferView: /* @__PURE__ */ __name(function(arr) {
  2503. return ArrayBuffer.isView(arr);
  2504. }, "isArrayBufferView")
  2505. },
  2506. isBlob,
  2507. deprecate: /* @__PURE__ */ __name(function(fn, message) {
  2508. return fn;
  2509. }, "deprecate"),
  2510. addAbortListener: require_events().addAbortListener || /* @__PURE__ */ __name(function addAbortListener(signal, listener) {
  2511. if (signal === void 0) {
  2512. throw new ERR_INVALID_ARG_TYPE("signal", "AbortSignal", signal);
  2513. }
  2514. validateAbortSignal(signal, "signal");
  2515. validateFunction(listener, "listener");
  2516. let removeEventListener;
  2517. if (signal.aborted) {
  2518. queueMicrotask(() => listener());
  2519. } else {
  2520. signal.addEventListener("abort", listener, {
  2521. __proto__: null,
  2522. once: true,
  2523. [kResistStopPropagation]: true
  2524. });
  2525. removeEventListener = /* @__PURE__ */ __name(() => {
  2526. signal.removeEventListener("abort", listener);
  2527. }, "removeEventListener");
  2528. }
  2529. return {
  2530. __proto__: null,
  2531. [SymbolDispose]() {
  2532. var _removeEventListener;
  2533. (_removeEventListener = removeEventListener) === null || _removeEventListener === void 0 ? void 0 : _removeEventListener();
  2534. }
  2535. };
  2536. }, "addAbortListener"),
  2537. AbortSignalAny: AbortSignal.any || /* @__PURE__ */ __name(function AbortSignalAny(signals) {
  2538. if (signals.length === 1) {
  2539. return signals[0];
  2540. }
  2541. const ac = new AbortController();
  2542. const abort = /* @__PURE__ */ __name(() => ac.abort(), "abort");
  2543. signals.forEach((signal) => {
  2544. validateAbortSignal(signal, "signals");
  2545. signal.addEventListener("abort", abort, {
  2546. once: true
  2547. });
  2548. });
  2549. ac.signal.addEventListener(
  2550. "abort",
  2551. () => {
  2552. signals.forEach((signal) => signal.removeEventListener("abort", abort));
  2553. },
  2554. {
  2555. once: true
  2556. }
  2557. );
  2558. return ac.signal;
  2559. }, "AbortSignalAny")
  2560. };
  2561. module.exports.promisify.custom = Symbol.for("nodejs.util.promisify.custom");
  2562. }
  2563. });
  2564. // node_modules/readable-stream/lib/ours/errors.js
  2565. var require_errors = __commonJS({
  2566. "node_modules/readable-stream/lib/ours/errors.js"(exports, module) {
  2567. "use strict";
  2568. var { format, inspect, AggregateError: CustomAggregateError } = require_util();
  2569. var AggregateError = globalThis.AggregateError || CustomAggregateError;
  2570. var kIsNodeError = Symbol("kIsNodeError");
  2571. var kTypes = [
  2572. "string",
  2573. "function",
  2574. "number",
  2575. "object",
  2576. // Accept 'Function' and 'Object' as alternative to the lower cased version.
  2577. "Function",
  2578. "Object",
  2579. "boolean",
  2580. "bigint",
  2581. "symbol"
  2582. ];
  2583. var classRegExp = /^([A-Z][a-z0-9]*)+$/;
  2584. var nodeInternalPrefix = "__node_internal_";
  2585. var codes = {};
  2586. function assert(value, message) {
  2587. if (!value) {
  2588. throw new codes.ERR_INTERNAL_ASSERTION(message);
  2589. }
  2590. }
  2591. __name(assert, "assert");
  2592. function addNumericalSeparator(val) {
  2593. let res = "";
  2594. let i = val.length;
  2595. const start = val[0] === "-" ? 1 : 0;
  2596. for (; i >= start + 4; i -= 3) {
  2597. res = `_${val.slice(i - 3, i)}${res}`;
  2598. }
  2599. return `${val.slice(0, i)}${res}`;
  2600. }
  2601. __name(addNumericalSeparator, "addNumericalSeparator");
  2602. function getMessage(key, msg, args) {
  2603. if (typeof msg === "function") {
  2604. assert(
  2605. msg.length <= args.length,
  2606. // Default options do not count.
  2607. `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`
  2608. );
  2609. return msg(...args);
  2610. }
  2611. const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length;
  2612. assert(
  2613. expectedLength === args.length,
  2614. `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`
  2615. );
  2616. if (args.length === 0) {
  2617. return msg;
  2618. }
  2619. return format(msg, ...args);
  2620. }
  2621. __name(getMessage, "getMessage");
  2622. function E(code, message, Base) {
  2623. if (!Base) {
  2624. Base = Error;
  2625. }
  2626. class NodeError extends Base {
  2627. static {
  2628. __name(this, "NodeError");
  2629. }
  2630. constructor(...args) {
  2631. super(getMessage(code, message, args));
  2632. }
  2633. toString() {
  2634. return `${this.name} [${code}]: ${this.message}`;
  2635. }
  2636. }
  2637. Object.defineProperties(NodeError.prototype, {
  2638. name: {
  2639. value: Base.name,
  2640. writable: true,
  2641. enumerable: false,
  2642. configurable: true
  2643. },
  2644. toString: {
  2645. value: /* @__PURE__ */ __name(function() {
  2646. return `${this.name} [${code}]: ${this.message}`;
  2647. }, "value"),
  2648. writable: true,
  2649. enumerable: false,
  2650. configurable: true
  2651. }
  2652. });
  2653. NodeError.prototype.code = code;
  2654. NodeError.prototype[kIsNodeError] = true;
  2655. codes[code] = NodeError;
  2656. }
  2657. __name(E, "E");
  2658. function hideStackFrames(fn) {
  2659. const hidden = nodeInternalPrefix + fn.name;
  2660. Object.defineProperty(fn, "name", {
  2661. value: hidden
  2662. });
  2663. return fn;
  2664. }
  2665. __name(hideStackFrames, "hideStackFrames");
  2666. function aggregateTwoErrors(innerError, outerError) {
  2667. if (innerError && outerError && innerError !== outerError) {
  2668. if (Array.isArray(outerError.errors)) {
  2669. outerError.errors.push(innerError);
  2670. return outerError;
  2671. }
  2672. const err = new AggregateError([outerError, innerError], outerError.message);
  2673. err.code = outerError.code;
  2674. return err;
  2675. }
  2676. return innerError || outerError;
  2677. }
  2678. __name(aggregateTwoErrors, "aggregateTwoErrors");
  2679. var AbortError = class extends Error {
  2680. static {
  2681. __name(this, "AbortError");
  2682. }
  2683. constructor(message = "The operation was aborted", options = void 0) {
  2684. if (options !== void 0 && typeof options !== "object") {
  2685. throw new codes.ERR_INVALID_ARG_TYPE("options", "Object", options);
  2686. }
  2687. super(message, options);
  2688. this.code = "ABORT_ERR";
  2689. this.name = "AbortError";
  2690. }
  2691. };
  2692. E("ERR_ASSERTION", "%s", Error);
  2693. E(
  2694. "ERR_INVALID_ARG_TYPE",
  2695. (name, expected, actual) => {
  2696. assert(typeof name === "string", "'name' must be a string");
  2697. if (!Array.isArray(expected)) {
  2698. expected = [expected];
  2699. }
  2700. let msg = "The ";
  2701. if (name.endsWith(" argument")) {
  2702. msg += `${name} `;
  2703. } else {
  2704. msg += `"${name}" ${name.includes(".") ? "property" : "argument"} `;
  2705. }
  2706. msg += "must be ";
  2707. const types = [];
  2708. const instances = [];
  2709. const other = [];
  2710. for (const value of expected) {
  2711. assert(typeof value === "string", "All expected entries have to be of type string");
  2712. if (kTypes.includes(value)) {
  2713. types.push(value.toLowerCase());
  2714. } else if (classRegExp.test(value)) {
  2715. instances.push(value);
  2716. } else {
  2717. assert(value !== "object", 'The value "object" should be written as "Object"');
  2718. other.push(value);
  2719. }
  2720. }
  2721. if (instances.length > 0) {
  2722. const pos = types.indexOf("object");
  2723. if (pos !== -1) {
  2724. types.splice(types, pos, 1);
  2725. instances.push("Object");
  2726. }
  2727. }
  2728. if (types.length > 0) {
  2729. switch (types.length) {
  2730. case 1:
  2731. msg += `of type ${types[0]}`;
  2732. break;
  2733. case 2:
  2734. msg += `one of type ${types[0]} or ${types[1]}`;
  2735. break;
  2736. default: {
  2737. const last = types.pop();
  2738. msg += `one of type ${types.join(", ")}, or ${last}`;
  2739. }
  2740. }
  2741. if (instances.length > 0 || other.length > 0) {
  2742. msg += " or ";
  2743. }
  2744. }
  2745. if (instances.length > 0) {
  2746. switch (instances.length) {
  2747. case 1:
  2748. msg += `an instance of ${instances[0]}`;
  2749. break;
  2750. case 2:
  2751. msg += `an instance of ${instances[0]} or ${instances[1]}`;
  2752. break;
  2753. default: {
  2754. const last = instances.pop();
  2755. msg += `an instance of ${instances.join(", ")}, or ${last}`;
  2756. }
  2757. }
  2758. if (other.length > 0) {
  2759. msg += " or ";
  2760. }
  2761. }
  2762. switch (other.length) {
  2763. case 0:
  2764. break;
  2765. case 1:
  2766. if (other[0].toLowerCase() !== other[0]) {
  2767. msg += "an ";
  2768. }
  2769. msg += `${other[0]}`;
  2770. break;
  2771. case 2:
  2772. msg += `one of ${other[0]} or ${other[1]}`;
  2773. break;
  2774. default: {
  2775. const last = other.pop();
  2776. msg += `one of ${other.join(", ")}, or ${last}`;
  2777. }
  2778. }
  2779. if (actual == null) {
  2780. msg += `. Received ${actual}`;
  2781. } else if (typeof actual === "function" && actual.name) {
  2782. msg += `. Received function ${actual.name}`;
  2783. } else if (typeof actual === "object") {
  2784. var _actual$constructor;
  2785. if ((_actual$constructor = actual.constructor) !== null && _actual$constructor !== void 0 && _actual$constructor.name) {
  2786. msg += `. Received an instance of ${actual.constructor.name}`;
  2787. } else {
  2788. const inspected = inspect(actual, {
  2789. depth: -1
  2790. });
  2791. msg += `. Received ${inspected}`;
  2792. }
  2793. } else {
  2794. let inspected = inspect(actual, {
  2795. colors: false
  2796. });
  2797. if (inspected.length > 25) {
  2798. inspected = `${inspected.slice(0, 25)}...`;
  2799. }
  2800. msg += `. Received type ${typeof actual} (${inspected})`;
  2801. }
  2802. return msg;
  2803. },
  2804. TypeError
  2805. );
  2806. E(
  2807. "ERR_INVALID_ARG_VALUE",
  2808. (name, value, reason = "is invalid") => {
  2809. let inspected = inspect(value);
  2810. if (inspected.length > 128) {
  2811. inspected = inspected.slice(0, 128) + "...";
  2812. }
  2813. const type = name.includes(".") ? "property" : "argument";
  2814. return `The ${type} '${name}' ${reason}. Received ${inspected}`;
  2815. },
  2816. TypeError
  2817. );
  2818. E(
  2819. "ERR_INVALID_RETURN_VALUE",
  2820. (input, name, value) => {
  2821. var _value$constructor;
  2822. const type = value !== null && value !== void 0 && (_value$constructor = value.constructor) !== null && _value$constructor !== void 0 && _value$constructor.name ? `instance of ${value.constructor.name}` : `type ${typeof value}`;
  2823. return `Expected ${input} to be returned from the "${name}" function but got ${type}.`;
  2824. },
  2825. TypeError
  2826. );
  2827. E(
  2828. "ERR_MISSING_ARGS",
  2829. (...args) => {
  2830. assert(args.length > 0, "At least one arg needs to be specified");
  2831. let msg;
  2832. const len = args.length;
  2833. args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(" or ");
  2834. switch (len) {
  2835. case 1:
  2836. msg += `The ${args[0]} argument`;
  2837. break;
  2838. case 2:
  2839. msg += `The ${args[0]} and ${args[1]} arguments`;
  2840. break;
  2841. default:
  2842. {
  2843. const last = args.pop();
  2844. msg += `The ${args.join(", ")}, and ${last} arguments`;
  2845. }
  2846. break;
  2847. }
  2848. return `${msg} must be specified`;
  2849. },
  2850. TypeError
  2851. );
  2852. E(
  2853. "ERR_OUT_OF_RANGE",
  2854. (str, range, input) => {
  2855. assert(range, 'Missing "range" argument');
  2856. let received;
  2857. if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
  2858. received = addNumericalSeparator(String(input));
  2859. } else if (typeof input === "bigint") {
  2860. received = String(input);
  2861. if (input > 2n ** 32n || input < -(2n ** 32n)) {
  2862. received = addNumericalSeparator(received);
  2863. }
  2864. received += "n";
  2865. } else {
  2866. received = inspect(input);
  2867. }
  2868. return `The value of "${str}" is out of range. It must be ${range}. Received ${received}`;
  2869. },
  2870. RangeError
  2871. );
  2872. E("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error);
  2873. E("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error);
  2874. E("ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", Error);
  2875. E("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error);
  2876. E("ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", Error);
  2877. E("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError);
  2878. E("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error);
  2879. E("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error);
  2880. E("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", Error);
  2881. E("ERR_STREAM_WRITE_AFTER_END", "write after end", Error);
  2882. E("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError);
  2883. module.exports = {
  2884. AbortError,
  2885. aggregateTwoErrors: hideStackFrames(aggregateTwoErrors),
  2886. hideStackFrames,
  2887. codes
  2888. };
  2889. }
  2890. });
  2891. // node_modules/readable-stream/lib/internal/validators.js
  2892. var require_validators = __commonJS({
  2893. "node_modules/readable-stream/lib/internal/validators.js"(exports, module) {
  2894. "use strict";
  2895. var {
  2896. ArrayIsArray,
  2897. ArrayPrototypeIncludes,
  2898. ArrayPrototypeJoin,
  2899. ArrayPrototypeMap,
  2900. NumberIsInteger,
  2901. NumberIsNaN,
  2902. NumberMAX_SAFE_INTEGER,
  2903. NumberMIN_SAFE_INTEGER,
  2904. NumberParseInt,
  2905. ObjectPrototypeHasOwnProperty,
  2906. RegExpPrototypeExec,
  2907. String: String2,
  2908. StringPrototypeToUpperCase,
  2909. StringPrototypeTrim
  2910. } = require_primordials();
  2911. var {
  2912. hideStackFrames,
  2913. codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL }
  2914. } = require_errors();
  2915. var { normalizeEncoding } = require_util();
  2916. var { isAsyncFunction, isArrayBufferView } = require_util().types;
  2917. var signals = {};
  2918. function isInt32(value) {
  2919. return value === (value | 0);
  2920. }
  2921. __name(isInt32, "isInt32");
  2922. function isUint32(value) {
  2923. return value === value >>> 0;
  2924. }
  2925. __name(isUint32, "isUint32");
  2926. var octalReg = /^[0-7]+$/;
  2927. var modeDesc = "must be a 32-bit unsigned integer or an octal string";
  2928. function parseFileMode(value, name, def) {
  2929. if (typeof value === "undefined") {
  2930. value = def;
  2931. }
  2932. if (typeof value === "string") {
  2933. if (RegExpPrototypeExec(octalReg, value) === null) {
  2934. throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc);
  2935. }
  2936. value = NumberParseInt(value, 8);
  2937. }
  2938. validateUint32(value, name);
  2939. return value;
  2940. }
  2941. __name(parseFileMode, "parseFileMode");
  2942. var validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => {
  2943. if (typeof value !== "number") throw new ERR_INVALID_ARG_TYPE2(name, "number", value);
  2944. if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, "an integer", value);
  2945. if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
  2946. });
  2947. var validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => {
  2948. if (typeof value !== "number") {
  2949. throw new ERR_INVALID_ARG_TYPE2(name, "number", value);
  2950. }
  2951. if (!NumberIsInteger(value)) {
  2952. throw new ERR_OUT_OF_RANGE(name, "an integer", value);
  2953. }
  2954. if (value < min || value > max) {
  2955. throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
  2956. }
  2957. });
  2958. var validateUint32 = hideStackFrames((value, name, positive = false) => {
  2959. if (typeof value !== "number") {
  2960. throw new ERR_INVALID_ARG_TYPE2(name, "number", value);
  2961. }
  2962. if (!NumberIsInteger(value)) {
  2963. throw new ERR_OUT_OF_RANGE(name, "an integer", value);
  2964. }
  2965. const min = positive ? 1 : 0;
  2966. const max = 4294967295;
  2967. if (value < min || value > max) {
  2968. throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
  2969. }
  2970. });
  2971. function validateString(value, name) {
  2972. if (typeof value !== "string") throw new ERR_INVALID_ARG_TYPE2(name, "string", value);
  2973. }
  2974. __name(validateString, "validateString");
  2975. function validateNumber(value, name, min = void 0, max) {
  2976. if (typeof value !== "number") throw new ERR_INVALID_ARG_TYPE2(name, "number", value);
  2977. if (min != null && value < min || max != null && value > max || (min != null || max != null) && NumberIsNaN(value)) {
  2978. throw new ERR_OUT_OF_RANGE(
  2979. name,
  2980. `${min != null ? `>= ${min}` : ""}${min != null && max != null ? " && " : ""}${max != null ? `<= ${max}` : ""}`,
  2981. value
  2982. );
  2983. }
  2984. }
  2985. __name(validateNumber, "validateNumber");
  2986. var validateOneOf = hideStackFrames((value, name, oneOf) => {
  2987. if (!ArrayPrototypeIncludes(oneOf, value)) {
  2988. const allowed = ArrayPrototypeJoin(
  2989. ArrayPrototypeMap(oneOf, (v) => typeof v === "string" ? `'${v}'` : String2(v)),
  2990. ", "
  2991. );
  2992. const reason = "must be one of: " + allowed;
  2993. throw new ERR_INVALID_ARG_VALUE(name, value, reason);
  2994. }
  2995. });
  2996. function validateBoolean(value, name) {
  2997. if (typeof value !== "boolean") throw new ERR_INVALID_ARG_TYPE2(name, "boolean", value);
  2998. }
  2999. __name(validateBoolean, "validateBoolean");
  3000. function getOwnPropertyValueOrDefault(options, key, defaultValue) {
  3001. return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key];
  3002. }
  3003. __name(getOwnPropertyValueOrDefault, "getOwnPropertyValueOrDefault");
  3004. var validateObject = hideStackFrames((value, name, options = null) => {
  3005. const allowArray = getOwnPropertyValueOrDefault(options, "allowArray", false);
  3006. const allowFunction = getOwnPropertyValueOrDefault(options, "allowFunction", false);
  3007. const nullable = getOwnPropertyValueOrDefault(options, "nullable", false);
  3008. if (!nullable && value === null || !allowArray && ArrayIsArray(value) || typeof value !== "object" && (!allowFunction || typeof value !== "function")) {
  3009. throw new ERR_INVALID_ARG_TYPE2(name, "Object", value);
  3010. }
  3011. });
  3012. var validateDictionary = hideStackFrames((value, name) => {
  3013. if (value != null && typeof value !== "object" && typeof value !== "function") {
  3014. throw new ERR_INVALID_ARG_TYPE2(name, "a dictionary", value);
  3015. }
  3016. });
  3017. var validateArray = hideStackFrames((value, name, minLength = 0) => {
  3018. if (!ArrayIsArray(value)) {
  3019. throw new ERR_INVALID_ARG_TYPE2(name, "Array", value);
  3020. }
  3021. if (value.length < minLength) {
  3022. const reason = `must be longer than ${minLength}`;
  3023. throw new ERR_INVALID_ARG_VALUE(name, value, reason);
  3024. }
  3025. });
  3026. function validateStringArray(value, name) {
  3027. validateArray(value, name);
  3028. for (let i = 0; i < value.length; i++) {
  3029. validateString(value[i], `${name}[${i}]`);
  3030. }
  3031. }
  3032. __name(validateStringArray, "validateStringArray");
  3033. function validateBooleanArray(value, name) {
  3034. validateArray(value, name);
  3035. for (let i = 0; i < value.length; i++) {
  3036. validateBoolean(value[i], `${name}[${i}]`);
  3037. }
  3038. }
  3039. __name(validateBooleanArray, "validateBooleanArray");
  3040. function validateAbortSignalArray(value, name) {
  3041. validateArray(value, name);
  3042. for (let i = 0; i < value.length; i++) {
  3043. const signal = value[i];
  3044. const indexedName = `${name}[${i}]`;
  3045. if (signal == null) {
  3046. throw new ERR_INVALID_ARG_TYPE2(indexedName, "AbortSignal", signal);
  3047. }
  3048. validateAbortSignal(signal, indexedName);
  3049. }
  3050. }
  3051. __name(validateAbortSignalArray, "validateAbortSignalArray");
  3052. function validateSignalName(signal, name = "signal") {
  3053. validateString(signal, name);
  3054. if (signals[signal] === void 0) {
  3055. if (signals[StringPrototypeToUpperCase(signal)] !== void 0) {
  3056. throw new ERR_UNKNOWN_SIGNAL(signal + " (signals must use all capital letters)");
  3057. }
  3058. throw new ERR_UNKNOWN_SIGNAL(signal);
  3059. }
  3060. }
  3061. __name(validateSignalName, "validateSignalName");
  3062. var validateBuffer = hideStackFrames((buffer, name = "buffer") => {
  3063. if (!isArrayBufferView(buffer)) {
  3064. throw new ERR_INVALID_ARG_TYPE2(name, ["Buffer", "TypedArray", "DataView"], buffer);
  3065. }
  3066. });
  3067. function validateEncoding(data, encoding) {
  3068. const normalizedEncoding = normalizeEncoding(encoding);
  3069. const length = data.length;
  3070. if (normalizedEncoding === "hex" && length % 2 !== 0) {
  3071. throw new ERR_INVALID_ARG_VALUE("encoding", encoding, `is invalid for data of length ${length}`);
  3072. }
  3073. }
  3074. __name(validateEncoding, "validateEncoding");
  3075. function validatePort(port, name = "Port", allowZero = true) {
  3076. if (typeof port !== "number" && typeof port !== "string" || typeof port === "string" && StringPrototypeTrim(port).length === 0 || +port !== +port >>> 0 || port > 65535 || port === 0 && !allowZero) {
  3077. throw new ERR_SOCKET_BAD_PORT(name, port, allowZero);
  3078. }
  3079. return port | 0;
  3080. }
  3081. __name(validatePort, "validatePort");
  3082. var validateAbortSignal = hideStackFrames((signal, name) => {
  3083. if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) {
  3084. throw new ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal);
  3085. }
  3086. });
  3087. var validateFunction = hideStackFrames((value, name) => {
  3088. if (typeof value !== "function") throw new ERR_INVALID_ARG_TYPE2(name, "Function", value);
  3089. });
  3090. var validatePlainFunction = hideStackFrames((value, name) => {
  3091. if (typeof value !== "function" || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE2(name, "Function", value);
  3092. });
  3093. var validateUndefined = hideStackFrames((value, name) => {
  3094. if (value !== void 0) throw new ERR_INVALID_ARG_TYPE2(name, "undefined", value);
  3095. });
  3096. function validateUnion(value, name, union) {
  3097. if (!ArrayPrototypeIncludes(union, value)) {
  3098. throw new ERR_INVALID_ARG_TYPE2(name, `('${ArrayPrototypeJoin(union, "|")}')`, value);
  3099. }
  3100. }
  3101. __name(validateUnion, "validateUnion");
  3102. var linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;
  3103. function validateLinkHeaderFormat(value, name) {
  3104. if (typeof value === "undefined" || !RegExpPrototypeExec(linkValueRegExp, value)) {
  3105. throw new ERR_INVALID_ARG_VALUE(
  3106. name,
  3107. value,
  3108. 'must be an array or string of format "</styles.css>; rel=preload; as=style"'
  3109. );
  3110. }
  3111. }
  3112. __name(validateLinkHeaderFormat, "validateLinkHeaderFormat");
  3113. function validateLinkHeaderValue(hints) {
  3114. if (typeof hints === "string") {
  3115. validateLinkHeaderFormat(hints, "hints");
  3116. return hints;
  3117. } else if (ArrayIsArray(hints)) {
  3118. const hintsLength = hints.length;
  3119. let result = "";
  3120. if (hintsLength === 0) {
  3121. return result;
  3122. }
  3123. for (let i = 0; i < hintsLength; i++) {
  3124. const link3 = hints[i];
  3125. validateLinkHeaderFormat(link3, "hints");
  3126. result += link3;
  3127. if (i !== hintsLength - 1) {
  3128. result += ", ";
  3129. }
  3130. }
  3131. return result;
  3132. }
  3133. throw new ERR_INVALID_ARG_VALUE(
  3134. "hints",
  3135. hints,
  3136. 'must be an array or string of format "</styles.css>; rel=preload; as=style"'
  3137. );
  3138. }
  3139. __name(validateLinkHeaderValue, "validateLinkHeaderValue");
  3140. module.exports = {
  3141. isInt32,
  3142. isUint32,
  3143. parseFileMode,
  3144. validateArray,
  3145. validateStringArray,
  3146. validateBooleanArray,
  3147. validateAbortSignalArray,
  3148. validateBoolean,
  3149. validateBuffer,
  3150. validateDictionary,
  3151. validateEncoding,
  3152. validateFunction,
  3153. validateInt32,
  3154. validateInteger,
  3155. validateNumber,
  3156. validateObject,
  3157. validateOneOf,
  3158. validatePlainFunction,
  3159. validatePort,
  3160. validateSignalName,
  3161. validateString,
  3162. validateUint32,
  3163. validateUndefined,
  3164. validateUnion,
  3165. validateAbortSignal,
  3166. validateLinkHeaderValue
  3167. };
  3168. }
  3169. });
  3170. // node_modules/process/browser.js
  3171. var require_browser2 = __commonJS({
  3172. "node_modules/process/browser.js"(exports, module) {
  3173. var process = module.exports = {};
  3174. var cachedSetTimeout;
  3175. var cachedClearTimeout;
  3176. function defaultSetTimout() {
  3177. throw new Error("setTimeout has not been defined");
  3178. }
  3179. __name(defaultSetTimout, "defaultSetTimout");
  3180. function defaultClearTimeout() {
  3181. throw new Error("clearTimeout has not been defined");
  3182. }
  3183. __name(defaultClearTimeout, "defaultClearTimeout");
  3184. (function() {
  3185. try {
  3186. if (typeof setTimeout === "function") {
  3187. cachedSetTimeout = setTimeout;
  3188. } else {
  3189. cachedSetTimeout = defaultSetTimout;
  3190. }
  3191. } catch (e) {
  3192. cachedSetTimeout = defaultSetTimout;
  3193. }
  3194. try {
  3195. if (typeof clearTimeout === "function") {
  3196. cachedClearTimeout = clearTimeout;
  3197. } else {
  3198. cachedClearTimeout = defaultClearTimeout;
  3199. }
  3200. } catch (e) {
  3201. cachedClearTimeout = defaultClearTimeout;
  3202. }
  3203. })();
  3204. function runTimeout(fun) {
  3205. if (cachedSetTimeout === setTimeout) {
  3206. return setTimeout(fun, 0);
  3207. }
  3208. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3209. cachedSetTimeout = setTimeout;
  3210. return setTimeout(fun, 0);
  3211. }
  3212. try {
  3213. return cachedSetTimeout(fun, 0);
  3214. } catch (e) {
  3215. try {
  3216. return cachedSetTimeout.call(null, fun, 0);
  3217. } catch (e2) {
  3218. return cachedSetTimeout.call(this, fun, 0);
  3219. }
  3220. }
  3221. }
  3222. __name(runTimeout, "runTimeout");
  3223. function runClearTimeout(marker) {
  3224. if (cachedClearTimeout === clearTimeout) {
  3225. return clearTimeout(marker);
  3226. }
  3227. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3228. cachedClearTimeout = clearTimeout;
  3229. return clearTimeout(marker);
  3230. }
  3231. try {
  3232. return cachedClearTimeout(marker);
  3233. } catch (e) {
  3234. try {
  3235. return cachedClearTimeout.call(null, marker);
  3236. } catch (e2) {
  3237. return cachedClearTimeout.call(this, marker);
  3238. }
  3239. }
  3240. }
  3241. __name(runClearTimeout, "runClearTimeout");
  3242. var queue = [];
  3243. var draining = false;
  3244. var currentQueue;
  3245. var queueIndex = -1;
  3246. function cleanUpNextTick() {
  3247. if (!draining || !currentQueue) {
  3248. return;
  3249. }
  3250. draining = false;
  3251. if (currentQueue.length) {
  3252. queue = currentQueue.concat(queue);
  3253. } else {
  3254. queueIndex = -1;
  3255. }
  3256. if (queue.length) {
  3257. drainQueue();
  3258. }
  3259. }
  3260. __name(cleanUpNextTick, "cleanUpNextTick");
  3261. function drainQueue() {
  3262. if (draining) {
  3263. return;
  3264. }
  3265. var timeout = runTimeout(cleanUpNextTick);
  3266. draining = true;
  3267. var len = queue.length;
  3268. while (len) {
  3269. currentQueue = queue;
  3270. queue = [];
  3271. while (++queueIndex < len) {
  3272. if (currentQueue) {
  3273. currentQueue[queueIndex].run();
  3274. }
  3275. }
  3276. queueIndex = -1;
  3277. len = queue.length;
  3278. }
  3279. currentQueue = null;
  3280. draining = false;
  3281. runClearTimeout(timeout);
  3282. }
  3283. __name(drainQueue, "drainQueue");
  3284. process.nextTick = function(fun) {
  3285. var args = new Array(arguments.length - 1);
  3286. if (arguments.length > 1) {
  3287. for (var i = 1; i < arguments.length; i++) {
  3288. args[i - 1] = arguments[i];
  3289. }
  3290. }
  3291. queue.push(new Item(fun, args));
  3292. if (queue.length === 1 && !draining) {
  3293. runTimeout(drainQueue);
  3294. }
  3295. };
  3296. function Item(fun, array) {
  3297. this.fun = fun;
  3298. this.array = array;
  3299. }
  3300. __name(Item, "Item");
  3301. Item.prototype.run = function() {
  3302. this.fun.apply(null, this.array);
  3303. };
  3304. process.title = "browser";
  3305. process.browser = true;
  3306. process.env = {};
  3307. process.argv = [];
  3308. process.version = "";
  3309. process.versions = {};
  3310. function noop() {
  3311. }
  3312. __name(noop, "noop");
  3313. process.on = noop;
  3314. process.addListener = noop;
  3315. process.once = noop;
  3316. process.off = noop;
  3317. process.removeListener = noop;
  3318. process.removeAllListeners = noop;
  3319. process.emit = noop;
  3320. process.prependListener = noop;
  3321. process.prependOnceListener = noop;
  3322. process.listeners = function(name) {
  3323. return [];
  3324. };
  3325. process.binding = function(name) {
  3326. throw new Error("process.binding is not supported");
  3327. };
  3328. process.cwd = function() {
  3329. return "/";
  3330. };
  3331. process.chdir = function(dir) {
  3332. throw new Error("process.chdir is not supported");
  3333. };
  3334. process.umask = function() {
  3335. return 0;
  3336. };
  3337. }
  3338. });
  3339. // node_modules/readable-stream/lib/internal/streams/utils.js
  3340. var require_utils = __commonJS({
  3341. "node_modules/readable-stream/lib/internal/streams/utils.js"(exports, module) {
  3342. "use strict";
  3343. var { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require_primordials();
  3344. var kIsDestroyed = SymbolFor("nodejs.stream.destroyed");
  3345. var kIsErrored = SymbolFor("nodejs.stream.errored");
  3346. var kIsReadable = SymbolFor("nodejs.stream.readable");
  3347. var kIsWritable = SymbolFor("nodejs.stream.writable");
  3348. var kIsDisturbed = SymbolFor("nodejs.stream.disturbed");
  3349. var kIsClosedPromise = SymbolFor("nodejs.webstream.isClosedPromise");
  3350. var kControllerErrorFunction = SymbolFor("nodejs.webstream.controllerErrorFunction");
  3351. function isReadableNodeStream(obj, strict = false) {
  3352. var _obj$_readableState;
  3353. return !!(obj && typeof obj.pipe === "function" && typeof obj.on === "function" && (!strict || typeof obj.pause === "function" && typeof obj.resume === "function") && (!obj._writableState || ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === void 0 ? void 0 : _obj$_readableState.readable) !== false) && // Duplex
  3354. (!obj._writableState || obj._readableState));
  3355. }
  3356. __name(isReadableNodeStream, "isReadableNodeStream");
  3357. function isWritableNodeStream(obj) {
  3358. var _obj$_writableState;
  3359. return !!(obj && typeof obj.write === "function" && typeof obj.on === "function" && (!obj._readableState || ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === void 0 ? void 0 : _obj$_writableState.writable) !== false));
  3360. }
  3361. __name(isWritableNodeStream, "isWritableNodeStream");
  3362. function isDuplexNodeStream(obj) {
  3363. return !!(obj && typeof obj.pipe === "function" && obj._readableState && typeof obj.on === "function" && typeof obj.write === "function");
  3364. }
  3365. __name(isDuplexNodeStream, "isDuplexNodeStream");
  3366. function isNodeStream(obj) {
  3367. return obj && (obj._readableState || obj._writableState || typeof obj.write === "function" && typeof obj.on === "function" || typeof obj.pipe === "function" && typeof obj.on === "function");
  3368. }
  3369. __name(isNodeStream, "isNodeStream");
  3370. function isReadableStream(obj) {
  3371. return !!(obj && !isNodeStream(obj) && typeof obj.pipeThrough === "function" && typeof obj.getReader === "function" && typeof obj.cancel === "function");
  3372. }
  3373. __name(isReadableStream, "isReadableStream");
  3374. function isWritableStream(obj) {
  3375. return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === "function" && typeof obj.abort === "function");
  3376. }
  3377. __name(isWritableStream, "isWritableStream");
  3378. function isTransformStream(obj) {
  3379. return !!(obj && !isNodeStream(obj) && typeof obj.readable === "object" && typeof obj.writable === "object");
  3380. }
  3381. __name(isTransformStream, "isTransformStream");
  3382. function isWebStream(obj) {
  3383. return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj);
  3384. }
  3385. __name(isWebStream, "isWebStream");
  3386. function isIterable(obj, isAsync) {
  3387. if (obj == null) return false;
  3388. if (isAsync === true) return typeof obj[SymbolAsyncIterator] === "function";
  3389. if (isAsync === false) return typeof obj[SymbolIterator] === "function";
  3390. return typeof obj[SymbolAsyncIterator] === "function" || typeof obj[SymbolIterator] === "function";
  3391. }
  3392. __name(isIterable, "isIterable");
  3393. function isDestroyed(stream) {
  3394. if (!isNodeStream(stream)) return null;
  3395. const wState = stream._writableState;
  3396. const rState = stream._readableState;
  3397. const state = wState || rState;
  3398. return !!(stream.destroyed || stream[kIsDestroyed] || state !== null && state !== void 0 && state.destroyed);
  3399. }
  3400. __name(isDestroyed, "isDestroyed");
  3401. function isWritableEnded(stream) {
  3402. if (!isWritableNodeStream(stream)) return null;
  3403. if (stream.writableEnded === true) return true;
  3404. const wState = stream._writableState;
  3405. if (wState !== null && wState !== void 0 && wState.errored) return false;
  3406. if (typeof (wState === null || wState === void 0 ? void 0 : wState.ended) !== "boolean") return null;
  3407. return wState.ended;
  3408. }
  3409. __name(isWritableEnded, "isWritableEnded");
  3410. function isWritableFinished(stream, strict) {
  3411. if (!isWritableNodeStream(stream)) return null;
  3412. if (stream.writableFinished === true) return true;
  3413. const wState = stream._writableState;
  3414. if (wState !== null && wState !== void 0 && wState.errored) return false;
  3415. if (typeof (wState === null || wState === void 0 ? void 0 : wState.finished) !== "boolean") return null;
  3416. return !!(wState.finished || strict === false && wState.ended === true && wState.length === 0);
  3417. }
  3418. __name(isWritableFinished, "isWritableFinished");
  3419. function isReadableEnded(stream) {
  3420. if (!isReadableNodeStream(stream)) return null;
  3421. if (stream.readableEnded === true) return true;
  3422. const rState = stream._readableState;
  3423. if (!rState || rState.errored) return false;
  3424. if (typeof (rState === null || rState === void 0 ? void 0 : rState.ended) !== "boolean") return null;
  3425. return rState.ended;
  3426. }
  3427. __name(isReadableEnded, "isReadableEnded");
  3428. function isReadableFinished(stream, strict) {
  3429. if (!isReadableNodeStream(stream)) return null;
  3430. const rState = stream._readableState;
  3431. if (rState !== null && rState !== void 0 && rState.errored) return false;
  3432. if (typeof (rState === null || rState === void 0 ? void 0 : rState.endEmitted) !== "boolean") return null;
  3433. return !!(rState.endEmitted || strict === false && rState.ended === true && rState.length === 0);
  3434. }
  3435. __name(isReadableFinished, "isReadableFinished");
  3436. function isReadable2(stream) {
  3437. if (stream && stream[kIsReadable] != null) return stream[kIsReadable];
  3438. if (typeof (stream === null || stream === void 0 ? void 0 : stream.readable) !== "boolean") return null;
  3439. if (isDestroyed(stream)) return false;
  3440. return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream);
  3441. }
  3442. __name(isReadable2, "isReadable");
  3443. function isWritable(stream) {
  3444. if (stream && stream[kIsWritable] != null) return stream[kIsWritable];
  3445. if (typeof (stream === null || stream === void 0 ? void 0 : stream.writable) !== "boolean") return null;
  3446. if (isDestroyed(stream)) return false;
  3447. return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream);
  3448. }
  3449. __name(isWritable, "isWritable");
  3450. function isFinished(stream, opts) {
  3451. if (!isNodeStream(stream)) {
  3452. return null;
  3453. }
  3454. if (isDestroyed(stream)) {
  3455. return true;
  3456. }
  3457. if ((opts === null || opts === void 0 ? void 0 : opts.readable) !== false && isReadable2(stream)) {
  3458. return false;
  3459. }
  3460. if ((opts === null || opts === void 0 ? void 0 : opts.writable) !== false && isWritable(stream)) {
  3461. return false;
  3462. }
  3463. return true;
  3464. }
  3465. __name(isFinished, "isFinished");
  3466. function isWritableErrored(stream) {
  3467. var _stream$_writableStat, _stream$_writableStat2;
  3468. if (!isNodeStream(stream)) {
  3469. return null;
  3470. }
  3471. if (stream.writableErrored) {
  3472. return stream.writableErrored;
  3473. }
  3474. return (_stream$_writableStat = (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === void 0 ? void 0 : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== void 0 ? _stream$_writableStat : null;
  3475. }
  3476. __name(isWritableErrored, "isWritableErrored");
  3477. function isReadableErrored(stream) {
  3478. var _stream$_readableStat, _stream$_readableStat2;
  3479. if (!isNodeStream(stream)) {
  3480. return null;
  3481. }
  3482. if (stream.readableErrored) {
  3483. return stream.readableErrored;
  3484. }
  3485. return (_stream$_readableStat = (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === void 0 ? void 0 : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== void 0 ? _stream$_readableStat : null;
  3486. }
  3487. __name(isReadableErrored, "isReadableErrored");
  3488. function isClosed(stream) {
  3489. if (!isNodeStream(stream)) {
  3490. return null;
  3491. }
  3492. if (typeof stream.closed === "boolean") {
  3493. return stream.closed;
  3494. }
  3495. const wState = stream._writableState;
  3496. const rState = stream._readableState;
  3497. if (typeof (wState === null || wState === void 0 ? void 0 : wState.closed) === "boolean" || typeof (rState === null || rState === void 0 ? void 0 : rState.closed) === "boolean") {
  3498. return (wState === null || wState === void 0 ? void 0 : wState.closed) || (rState === null || rState === void 0 ? void 0 : rState.closed);
  3499. }
  3500. if (typeof stream._closed === "boolean" && isOutgoingMessage(stream)) {
  3501. return stream._closed;
  3502. }
  3503. return null;
  3504. }
  3505. __name(isClosed, "isClosed");
  3506. function isOutgoingMessage(stream) {
  3507. return typeof stream._closed === "boolean" && typeof stream._defaultKeepAlive === "boolean" && typeof stream._removedConnection === "boolean" && typeof stream._removedContLen === "boolean";
  3508. }
  3509. __name(isOutgoingMessage, "isOutgoingMessage");
  3510. function isServerResponse(stream) {
  3511. return typeof stream._sent100 === "boolean" && isOutgoingMessage(stream);
  3512. }
  3513. __name(isServerResponse, "isServerResponse");
  3514. function isServerRequest(stream) {
  3515. var _stream$req;
  3516. return typeof stream._consuming === "boolean" && typeof stream._dumped === "boolean" && ((_stream$req = stream.req) === null || _stream$req === void 0 ? void 0 : _stream$req.upgradeOrConnect) === void 0;
  3517. }
  3518. __name(isServerRequest, "isServerRequest");
  3519. function willEmitClose(stream) {
  3520. if (!isNodeStream(stream)) return null;
  3521. const wState = stream._writableState;
  3522. const rState = stream._readableState;
  3523. const state = wState || rState;
  3524. return !state && isServerResponse(stream) || !!(state && state.autoDestroy && state.emitClose && state.closed === false);
  3525. }
  3526. __name(willEmitClose, "willEmitClose");
  3527. function isDisturbed(stream) {
  3528. var _stream$kIsDisturbed;
  3529. return !!(stream && ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== void 0 ? _stream$kIsDisturbed : stream.readableDidRead || stream.readableAborted));
  3530. }
  3531. __name(isDisturbed, "isDisturbed");
  3532. function isErrored(stream) {
  3533. var _ref, _ref2, _ref3, _ref4, _ref5, _stream$kIsErrored, _stream$_readableStat3, _stream$_writableStat3, _stream$_readableStat4, _stream$_writableStat4;
  3534. return !!(stream && ((_ref = (_ref2 = (_ref3 = (_ref4 = (_ref5 = (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== void 0 ? _stream$kIsErrored : stream.readableErrored) !== null && _ref5 !== void 0 ? _ref5 : stream.writableErrored) !== null && _ref4 !== void 0 ? _ref4 : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === void 0 ? void 0 : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== void 0 ? _ref3 : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === void 0 ? void 0 : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== void 0 ? _ref2 : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === void 0 ? void 0 : _stream$_readableStat4.errored) !== null && _ref !== void 0 ? _ref : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === void 0 ? void 0 : _stream$_writableStat4.errored));
  3535. }
  3536. __name(isErrored, "isErrored");
  3537. module.exports = {
  3538. isDestroyed,
  3539. kIsDestroyed,
  3540. isDisturbed,
  3541. kIsDisturbed,
  3542. isErrored,
  3543. kIsErrored,
  3544. isReadable: isReadable2,
  3545. kIsReadable,
  3546. kIsClosedPromise,
  3547. kControllerErrorFunction,
  3548. kIsWritable,
  3549. isClosed,
  3550. isDuplexNodeStream,
  3551. isFinished,
  3552. isIterable,
  3553. isReadableNodeStream,
  3554. isReadableStream,
  3555. isReadableEnded,
  3556. isReadableFinished,
  3557. isReadableErrored,
  3558. isNodeStream,
  3559. isWebStream,
  3560. isWritable,
  3561. isWritableNodeStream,
  3562. isWritableStream,
  3563. isWritableEnded,
  3564. isWritableFinished,
  3565. isWritableErrored,
  3566. isServerRequest,
  3567. isServerResponse,
  3568. willEmitClose,
  3569. isTransformStream
  3570. };
  3571. }
  3572. });
  3573. // node_modules/readable-stream/lib/internal/streams/end-of-stream.js
  3574. var require_end_of_stream = __commonJS({
  3575. "node_modules/readable-stream/lib/internal/streams/end-of-stream.js"(exports, module) {
  3576. var process = require_browser2();
  3577. var { AbortError, codes } = require_errors();
  3578. var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_STREAM_PREMATURE_CLOSE } = codes;
  3579. var { kEmptyObject, once } = require_util();
  3580. var { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require_validators();
  3581. var { Promise: Promise2, PromisePrototypeThen, SymbolDispose } = require_primordials();
  3582. var {
  3583. isClosed,
  3584. isReadable: isReadable2,
  3585. isReadableNodeStream,
  3586. isReadableStream,
  3587. isReadableFinished,
  3588. isReadableErrored,
  3589. isWritable,
  3590. isWritableNodeStream,
  3591. isWritableStream,
  3592. isWritableFinished,
  3593. isWritableErrored,
  3594. isNodeStream,
  3595. willEmitClose: _willEmitClose,
  3596. kIsClosedPromise
  3597. } = require_utils();
  3598. var addAbortListener;
  3599. function isRequest(stream) {
  3600. return stream.setHeader && typeof stream.abort === "function";
  3601. }
  3602. __name(isRequest, "isRequest");
  3603. var nop2 = /* @__PURE__ */ __name(() => {
  3604. }, "nop");
  3605. function eos(stream, options, callback) {
  3606. var _options$readable, _options$writable;
  3607. if (arguments.length === 2) {
  3608. callback = options;
  3609. options = kEmptyObject;
  3610. } else if (options == null) {
  3611. options = kEmptyObject;
  3612. } else {
  3613. validateObject(options, "options");
  3614. }
  3615. validateFunction(callback, "callback");
  3616. validateAbortSignal(options.signal, "options.signal");
  3617. callback = once(callback);
  3618. if (isReadableStream(stream) || isWritableStream(stream)) {
  3619. return eosWeb(stream, options, callback);
  3620. }
  3621. if (!isNodeStream(stream)) {
  3622. throw new ERR_INVALID_ARG_TYPE2("stream", ["ReadableStream", "WritableStream", "Stream"], stream);
  3623. }
  3624. const readable = (_options$readable = options.readable) !== null && _options$readable !== void 0 ? _options$readable : isReadableNodeStream(stream);
  3625. const writable = (_options$writable = options.writable) !== null && _options$writable !== void 0 ? _options$writable : isWritableNodeStream(stream);
  3626. const wState = stream._writableState;
  3627. const rState = stream._readableState;
  3628. const onlegacyfinish = /* @__PURE__ */ __name(() => {
  3629. if (!stream.writable) {
  3630. onfinish();
  3631. }
  3632. }, "onlegacyfinish");
  3633. let willEmitClose = _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable;
  3634. let writableFinished = isWritableFinished(stream, false);
  3635. const onfinish = /* @__PURE__ */ __name(() => {
  3636. writableFinished = true;
  3637. if (stream.destroyed) {
  3638. willEmitClose = false;
  3639. }
  3640. if (willEmitClose && (!stream.readable || readable)) {
  3641. return;
  3642. }
  3643. if (!readable || readableFinished) {
  3644. callback.call(stream);
  3645. }
  3646. }, "onfinish");
  3647. let readableFinished = isReadableFinished(stream, false);
  3648. const onend = /* @__PURE__ */ __name(() => {
  3649. readableFinished = true;
  3650. if (stream.destroyed) {
  3651. willEmitClose = false;
  3652. }
  3653. if (willEmitClose && (!stream.writable || writable)) {
  3654. return;
  3655. }
  3656. if (!writable || writableFinished) {
  3657. callback.call(stream);
  3658. }
  3659. }, "onend");
  3660. const onerror = /* @__PURE__ */ __name((err) => {
  3661. callback.call(stream, err);
  3662. }, "onerror");
  3663. let closed = isClosed(stream);
  3664. const onclose = /* @__PURE__ */ __name(() => {
  3665. closed = true;
  3666. const errored = isWritableErrored(stream) || isReadableErrored(stream);
  3667. if (errored && typeof errored !== "boolean") {
  3668. return callback.call(stream, errored);
  3669. }
  3670. if (readable && !readableFinished && isReadableNodeStream(stream, true)) {
  3671. if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE());
  3672. }
  3673. if (writable && !writableFinished) {
  3674. if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE());
  3675. }
  3676. callback.call(stream);
  3677. }, "onclose");
  3678. const onclosed = /* @__PURE__ */ __name(() => {
  3679. closed = true;
  3680. const errored = isWritableErrored(stream) || isReadableErrored(stream);
  3681. if (errored && typeof errored !== "boolean") {
  3682. return callback.call(stream, errored);
  3683. }
  3684. callback.call(stream);
  3685. }, "onclosed");
  3686. const onrequest = /* @__PURE__ */ __name(() => {
  3687. stream.req.on("finish", onfinish);
  3688. }, "onrequest");
  3689. if (isRequest(stream)) {
  3690. stream.on("complete", onfinish);
  3691. if (!willEmitClose) {
  3692. stream.on("abort", onclose);
  3693. }
  3694. if (stream.req) {
  3695. onrequest();
  3696. } else {
  3697. stream.on("request", onrequest);
  3698. }
  3699. } else if (writable && !wState) {
  3700. stream.on("end", onlegacyfinish);
  3701. stream.on("close", onlegacyfinish);
  3702. }
  3703. if (!willEmitClose && typeof stream.aborted === "boolean") {
  3704. stream.on("aborted", onclose);
  3705. }
  3706. stream.on("end", onend);
  3707. stream.on("finish", onfinish);
  3708. if (options.error !== false) {
  3709. stream.on("error", onerror);
  3710. }
  3711. stream.on("close", onclose);
  3712. if (closed) {
  3713. process.nextTick(onclose);
  3714. } else if (wState !== null && wState !== void 0 && wState.errorEmitted || rState !== null && rState !== void 0 && rState.errorEmitted) {
  3715. if (!willEmitClose) {
  3716. process.nextTick(onclosed);
  3717. }
  3718. } else if (!readable && (!willEmitClose || isReadable2(stream)) && (writableFinished || isWritable(stream) === false)) {
  3719. process.nextTick(onclosed);
  3720. } else if (!writable && (!willEmitClose || isWritable(stream)) && (readableFinished || isReadable2(stream) === false)) {
  3721. process.nextTick(onclosed);
  3722. } else if (rState && stream.req && stream.aborted) {
  3723. process.nextTick(onclosed);
  3724. }
  3725. const cleanup = /* @__PURE__ */ __name(() => {
  3726. callback = nop2;
  3727. stream.removeListener("aborted", onclose);
  3728. stream.removeListener("complete", onfinish);
  3729. stream.removeListener("abort", onclose);
  3730. stream.removeListener("request", onrequest);
  3731. if (stream.req) stream.req.removeListener("finish", onfinish);
  3732. stream.removeListener("end", onlegacyfinish);
  3733. stream.removeListener("close", onlegacyfinish);
  3734. stream.removeListener("finish", onfinish);
  3735. stream.removeListener("end", onend);
  3736. stream.removeListener("error", onerror);
  3737. stream.removeListener("close", onclose);
  3738. }, "cleanup");
  3739. if (options.signal && !closed) {
  3740. const abort = /* @__PURE__ */ __name(() => {
  3741. const endCallback = callback;
  3742. cleanup();
  3743. endCallback.call(
  3744. stream,
  3745. new AbortError(void 0, {
  3746. cause: options.signal.reason
  3747. })
  3748. );
  3749. }, "abort");
  3750. if (options.signal.aborted) {
  3751. process.nextTick(abort);
  3752. } else {
  3753. addAbortListener = addAbortListener || require_util().addAbortListener;
  3754. const disposable = addAbortListener(options.signal, abort);
  3755. const originalCallback = callback;
  3756. callback = once((...args) => {
  3757. disposable[SymbolDispose]();
  3758. originalCallback.apply(stream, args);
  3759. });
  3760. }
  3761. }
  3762. return cleanup;
  3763. }
  3764. __name(eos, "eos");
  3765. function eosWeb(stream, options, callback) {
  3766. let isAborted = false;
  3767. let abort = nop2;
  3768. if (options.signal) {
  3769. abort = /* @__PURE__ */ __name(() => {
  3770. isAborted = true;
  3771. callback.call(
  3772. stream,
  3773. new AbortError(void 0, {
  3774. cause: options.signal.reason
  3775. })
  3776. );
  3777. }, "abort");
  3778. if (options.signal.aborted) {
  3779. process.nextTick(abort);
  3780. } else {
  3781. addAbortListener = addAbortListener || require_util().addAbortListener;
  3782. const disposable = addAbortListener(options.signal, abort);
  3783. const originalCallback = callback;
  3784. callback = once((...args) => {
  3785. disposable[SymbolDispose]();
  3786. originalCallback.apply(stream, args);
  3787. });
  3788. }
  3789. }
  3790. const resolverFn = /* @__PURE__ */ __name((...args) => {
  3791. if (!isAborted) {
  3792. process.nextTick(() => callback.apply(stream, args));
  3793. }
  3794. }, "resolverFn");
  3795. PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn);
  3796. return nop2;
  3797. }
  3798. __name(eosWeb, "eosWeb");
  3799. function finished(stream, opts) {
  3800. var _opts;
  3801. let autoCleanup = false;
  3802. if (opts === null) {
  3803. opts = kEmptyObject;
  3804. }
  3805. if ((_opts = opts) !== null && _opts !== void 0 && _opts.cleanup) {
  3806. validateBoolean(opts.cleanup, "cleanup");
  3807. autoCleanup = opts.cleanup;
  3808. }
  3809. return new Promise2((resolve2, reject) => {
  3810. const cleanup = eos(stream, opts, (err) => {
  3811. if (autoCleanup) {
  3812. cleanup();
  3813. }
  3814. if (err) {
  3815. reject(err);
  3816. } else {
  3817. resolve2();
  3818. }
  3819. });
  3820. });
  3821. }
  3822. __name(finished, "finished");
  3823. module.exports = eos;
  3824. module.exports.finished = finished;
  3825. }
  3826. });
  3827. // node_modules/readable-stream/lib/internal/streams/destroy.js
  3828. var require_destroy = __commonJS({
  3829. "node_modules/readable-stream/lib/internal/streams/destroy.js"(exports, module) {
  3830. "use strict";
  3831. var process = require_browser2();
  3832. var {
  3833. aggregateTwoErrors,
  3834. codes: { ERR_MULTIPLE_CALLBACK },
  3835. AbortError
  3836. } = require_errors();
  3837. var { Symbol: Symbol2 } = require_primordials();
  3838. var { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require_utils();
  3839. var kDestroy = Symbol2("kDestroy");
  3840. var kConstruct = Symbol2("kConstruct");
  3841. function checkError(err, w, r) {
  3842. if (err) {
  3843. err.stack;
  3844. if (w && !w.errored) {
  3845. w.errored = err;
  3846. }
  3847. if (r && !r.errored) {
  3848. r.errored = err;
  3849. }
  3850. }
  3851. }
  3852. __name(checkError, "checkError");
  3853. function destroy(err, cb) {
  3854. const r = this._readableState;
  3855. const w = this._writableState;
  3856. const s = w || r;
  3857. if (w !== null && w !== void 0 && w.destroyed || r !== null && r !== void 0 && r.destroyed) {
  3858. if (typeof cb === "function") {
  3859. cb();
  3860. }
  3861. return this;
  3862. }
  3863. checkError(err, w, r);
  3864. if (w) {
  3865. w.destroyed = true;
  3866. }
  3867. if (r) {
  3868. r.destroyed = true;
  3869. }
  3870. if (!s.constructed) {
  3871. this.once(kDestroy, function(er) {
  3872. _destroy(this, aggregateTwoErrors(er, err), cb);
  3873. });
  3874. } else {
  3875. _destroy(this, err, cb);
  3876. }
  3877. return this;
  3878. }
  3879. __name(destroy, "destroy");
  3880. function _destroy(self2, err, cb) {
  3881. let called = false;
  3882. function onDestroy(err2) {
  3883. if (called) {
  3884. return;
  3885. }
  3886. called = true;
  3887. const r = self2._readableState;
  3888. const w = self2._writableState;
  3889. checkError(err2, w, r);
  3890. if (w) {
  3891. w.closed = true;
  3892. }
  3893. if (r) {
  3894. r.closed = true;
  3895. }
  3896. if (typeof cb === "function") {
  3897. cb(err2);
  3898. }
  3899. if (err2) {
  3900. process.nextTick(emitErrorCloseNT, self2, err2);
  3901. } else {
  3902. process.nextTick(emitCloseNT, self2);
  3903. }
  3904. }
  3905. __name(onDestroy, "onDestroy");
  3906. try {
  3907. self2._destroy(err || null, onDestroy);
  3908. } catch (err2) {
  3909. onDestroy(err2);
  3910. }
  3911. }
  3912. __name(_destroy, "_destroy");
  3913. function emitErrorCloseNT(self2, err) {
  3914. emitErrorNT(self2, err);
  3915. emitCloseNT(self2);
  3916. }
  3917. __name(emitErrorCloseNT, "emitErrorCloseNT");
  3918. function emitCloseNT(self2) {
  3919. const r = self2._readableState;
  3920. const w = self2._writableState;
  3921. if (w) {
  3922. w.closeEmitted = true;
  3923. }
  3924. if (r) {
  3925. r.closeEmitted = true;
  3926. }
  3927. if (w !== null && w !== void 0 && w.emitClose || r !== null && r !== void 0 && r.emitClose) {
  3928. self2.emit("close");
  3929. }
  3930. }
  3931. __name(emitCloseNT, "emitCloseNT");
  3932. function emitErrorNT(self2, err) {
  3933. const r = self2._readableState;
  3934. const w = self2._writableState;
  3935. if (w !== null && w !== void 0 && w.errorEmitted || r !== null && r !== void 0 && r.errorEmitted) {
  3936. return;
  3937. }
  3938. if (w) {
  3939. w.errorEmitted = true;
  3940. }
  3941. if (r) {
  3942. r.errorEmitted = true;
  3943. }
  3944. self2.emit("error", err);
  3945. }
  3946. __name(emitErrorNT, "emitErrorNT");
  3947. function undestroy() {
  3948. const r = this._readableState;
  3949. const w = this._writableState;
  3950. if (r) {
  3951. r.constructed = true;
  3952. r.closed = false;
  3953. r.closeEmitted = false;
  3954. r.destroyed = false;
  3955. r.errored = null;
  3956. r.errorEmitted = false;
  3957. r.reading = false;
  3958. r.ended = r.readable === false;
  3959. r.endEmitted = r.readable === false;
  3960. }
  3961. if (w) {
  3962. w.constructed = true;
  3963. w.destroyed = false;
  3964. w.closed = false;
  3965. w.closeEmitted = false;
  3966. w.errored = null;
  3967. w.errorEmitted = false;
  3968. w.finalCalled = false;
  3969. w.prefinished = false;
  3970. w.ended = w.writable === false;
  3971. w.ending = w.writable === false;
  3972. w.finished = w.writable === false;
  3973. }
  3974. }
  3975. __name(undestroy, "undestroy");
  3976. function errorOrDestroy(stream, err, sync) {
  3977. const r = stream._readableState;
  3978. const w = stream._writableState;
  3979. if (w !== null && w !== void 0 && w.destroyed || r !== null && r !== void 0 && r.destroyed) {
  3980. return this;
  3981. }
  3982. if (r !== null && r !== void 0 && r.autoDestroy || w !== null && w !== void 0 && w.autoDestroy)
  3983. stream.destroy(err);
  3984. else if (err) {
  3985. err.stack;
  3986. if (w && !w.errored) {
  3987. w.errored = err;
  3988. }
  3989. if (r && !r.errored) {
  3990. r.errored = err;
  3991. }
  3992. if (sync) {
  3993. process.nextTick(emitErrorNT, stream, err);
  3994. } else {
  3995. emitErrorNT(stream, err);
  3996. }
  3997. }
  3998. }
  3999. __name(errorOrDestroy, "errorOrDestroy");
  4000. function construct(stream, cb) {
  4001. if (typeof stream._construct !== "function") {
  4002. return;
  4003. }
  4004. const r = stream._readableState;
  4005. const w = stream._writableState;
  4006. if (r) {
  4007. r.constructed = false;
  4008. }
  4009. if (w) {
  4010. w.constructed = false;
  4011. }
  4012. stream.once(kConstruct, cb);
  4013. if (stream.listenerCount(kConstruct) > 1) {
  4014. return;
  4015. }
  4016. process.nextTick(constructNT, stream);
  4017. }
  4018. __name(construct, "construct");
  4019. function constructNT(stream) {
  4020. let called = false;
  4021. function onConstruct(err) {
  4022. if (called) {
  4023. errorOrDestroy(stream, err !== null && err !== void 0 ? err : new ERR_MULTIPLE_CALLBACK());
  4024. return;
  4025. }
  4026. called = true;
  4027. const r = stream._readableState;
  4028. const w = stream._writableState;
  4029. const s = w || r;
  4030. if (r) {
  4031. r.constructed = true;
  4032. }
  4033. if (w) {
  4034. w.constructed = true;
  4035. }
  4036. if (s.destroyed) {
  4037. stream.emit(kDestroy, err);
  4038. } else if (err) {
  4039. errorOrDestroy(stream, err, true);
  4040. } else {
  4041. process.nextTick(emitConstructNT, stream);
  4042. }
  4043. }
  4044. __name(onConstruct, "onConstruct");
  4045. try {
  4046. stream._construct((err) => {
  4047. process.nextTick(onConstruct, err);
  4048. });
  4049. } catch (err) {
  4050. process.nextTick(onConstruct, err);
  4051. }
  4052. }
  4053. __name(constructNT, "constructNT");
  4054. function emitConstructNT(stream) {
  4055. stream.emit(kConstruct);
  4056. }
  4057. __name(emitConstructNT, "emitConstructNT");
  4058. function isRequest(stream) {
  4059. return (stream === null || stream === void 0 ? void 0 : stream.setHeader) && typeof stream.abort === "function";
  4060. }
  4061. __name(isRequest, "isRequest");
  4062. function emitCloseLegacy(stream) {
  4063. stream.emit("close");
  4064. }
  4065. __name(emitCloseLegacy, "emitCloseLegacy");
  4066. function emitErrorCloseLegacy(stream, err) {
  4067. stream.emit("error", err);
  4068. process.nextTick(emitCloseLegacy, stream);
  4069. }
  4070. __name(emitErrorCloseLegacy, "emitErrorCloseLegacy");
  4071. function destroyer(stream, err) {
  4072. if (!stream || isDestroyed(stream)) {
  4073. return;
  4074. }
  4075. if (!err && !isFinished(stream)) {
  4076. err = new AbortError();
  4077. }
  4078. if (isServerRequest(stream)) {
  4079. stream.socket = null;
  4080. stream.destroy(err);
  4081. } else if (isRequest(stream)) {
  4082. stream.abort();
  4083. } else if (isRequest(stream.req)) {
  4084. stream.req.abort();
  4085. } else if (typeof stream.destroy === "function") {
  4086. stream.destroy(err);
  4087. } else if (typeof stream.close === "function") {
  4088. stream.close();
  4089. } else if (err) {
  4090. process.nextTick(emitErrorCloseLegacy, stream, err);
  4091. } else {
  4092. process.nextTick(emitCloseLegacy, stream);
  4093. }
  4094. if (!stream.destroyed) {
  4095. stream[kIsDestroyed] = true;
  4096. }
  4097. }
  4098. __name(destroyer, "destroyer");
  4099. module.exports = {
  4100. construct,
  4101. destroyer,
  4102. destroy,
  4103. undestroy,
  4104. errorOrDestroy
  4105. };
  4106. }
  4107. });
  4108. // node_modules/readable-stream/lib/internal/streams/legacy.js
  4109. var require_legacy = __commonJS({
  4110. "node_modules/readable-stream/lib/internal/streams/legacy.js"(exports, module) {
  4111. "use strict";
  4112. var { ArrayIsArray, ObjectSetPrototypeOf } = require_primordials();
  4113. var { EventEmitter: EE } = require_events();
  4114. function Stream(opts) {
  4115. EE.call(this, opts);
  4116. }
  4117. __name(Stream, "Stream");
  4118. ObjectSetPrototypeOf(Stream.prototype, EE.prototype);
  4119. ObjectSetPrototypeOf(Stream, EE);
  4120. Stream.prototype.pipe = function(dest, options) {
  4121. const source = this;
  4122. function ondata(chunk) {
  4123. if (dest.writable && dest.write(chunk) === false && source.pause) {
  4124. source.pause();
  4125. }
  4126. }
  4127. __name(ondata, "ondata");
  4128. source.on("data", ondata);
  4129. function ondrain() {
  4130. if (source.readable && source.resume) {
  4131. source.resume();
  4132. }
  4133. }
  4134. __name(ondrain, "ondrain");
  4135. dest.on("drain", ondrain);
  4136. if (!dest._isStdio && (!options || options.end !== false)) {
  4137. source.on("end", onend);
  4138. source.on("close", onclose);
  4139. }
  4140. let didOnEnd = false;
  4141. function onend() {
  4142. if (didOnEnd) return;
  4143. didOnEnd = true;
  4144. dest.end();
  4145. }
  4146. __name(onend, "onend");
  4147. function onclose() {
  4148. if (didOnEnd) return;
  4149. didOnEnd = true;
  4150. if (typeof dest.destroy === "function") dest.destroy();
  4151. }
  4152. __name(onclose, "onclose");
  4153. function onerror(er) {
  4154. cleanup();
  4155. if (EE.listenerCount(this, "error") === 0) {
  4156. this.emit("error", er);
  4157. }
  4158. }
  4159. __name(onerror, "onerror");
  4160. prependListener(source, "error", onerror);
  4161. prependListener(dest, "error", onerror);
  4162. function cleanup() {
  4163. source.removeListener("data", ondata);
  4164. dest.removeListener("drain", ondrain);
  4165. source.removeListener("end", onend);
  4166. source.removeListener("close", onclose);
  4167. source.removeListener("error", onerror);
  4168. dest.removeListener("error", onerror);
  4169. source.removeListener("end", cleanup);
  4170. source.removeListener("close", cleanup);
  4171. dest.removeListener("close", cleanup);
  4172. }
  4173. __name(cleanup, "cleanup");
  4174. source.on("end", cleanup);
  4175. source.on("close", cleanup);
  4176. dest.on("close", cleanup);
  4177. dest.emit("pipe", source);
  4178. return dest;
  4179. };
  4180. function prependListener(emitter, event, fn) {
  4181. if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn);
  4182. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);
  4183. else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn);
  4184. else emitter._events[event] = [fn, emitter._events[event]];
  4185. }
  4186. __name(prependListener, "prependListener");
  4187. module.exports = {
  4188. Stream,
  4189. prependListener
  4190. };
  4191. }
  4192. });
  4193. // node_modules/readable-stream/lib/internal/streams/add-abort-signal.js
  4194. var require_add_abort_signal = __commonJS({
  4195. "node_modules/readable-stream/lib/internal/streams/add-abort-signal.js"(exports, module) {
  4196. "use strict";
  4197. var { SymbolDispose } = require_primordials();
  4198. var { AbortError, codes } = require_errors();
  4199. var { isNodeStream, isWebStream, kControllerErrorFunction } = require_utils();
  4200. var eos = require_end_of_stream();
  4201. var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2 } = codes;
  4202. var addAbortListener;
  4203. var validateAbortSignal = /* @__PURE__ */ __name((signal, name) => {
  4204. if (typeof signal !== "object" || !("aborted" in signal)) {
  4205. throw new ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal);
  4206. }
  4207. }, "validateAbortSignal");
  4208. module.exports.addAbortSignal = /* @__PURE__ */ __name(function addAbortSignal(signal, stream) {
  4209. validateAbortSignal(signal, "signal");
  4210. if (!isNodeStream(stream) && !isWebStream(stream)) {
  4211. throw new ERR_INVALID_ARG_TYPE2("stream", ["ReadableStream", "WritableStream", "Stream"], stream);
  4212. }
  4213. return module.exports.addAbortSignalNoValidate(signal, stream);
  4214. }, "addAbortSignal");
  4215. module.exports.addAbortSignalNoValidate = function(signal, stream) {
  4216. if (typeof signal !== "object" || !("aborted" in signal)) {
  4217. return stream;
  4218. }
  4219. const onAbort = isNodeStream(stream) ? () => {
  4220. stream.destroy(
  4221. new AbortError(void 0, {
  4222. cause: signal.reason
  4223. })
  4224. );
  4225. } : () => {
  4226. stream[kControllerErrorFunction](
  4227. new AbortError(void 0, {
  4228. cause: signal.reason
  4229. })
  4230. );
  4231. };
  4232. if (signal.aborted) {
  4233. onAbort();
  4234. } else {
  4235. addAbortListener = addAbortListener || require_util().addAbortListener;
  4236. const disposable = addAbortListener(signal, onAbort);
  4237. eos(stream, disposable[SymbolDispose]);
  4238. }
  4239. return stream;
  4240. };
  4241. }
  4242. });
  4243. // node_modules/readable-stream/lib/internal/streams/buffer_list.js
  4244. var require_buffer_list = __commonJS({
  4245. "node_modules/readable-stream/lib/internal/streams/buffer_list.js"(exports, module) {
  4246. "use strict";
  4247. var { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array: Uint8Array2 } = require_primordials();
  4248. var { Buffer: Buffer4 } = require_buffer();
  4249. var { inspect } = require_util();
  4250. module.exports = class BufferList {
  4251. static {
  4252. __name(this, "BufferList");
  4253. }
  4254. constructor() {
  4255. this.head = null;
  4256. this.tail = null;
  4257. this.length = 0;
  4258. }
  4259. push(v) {
  4260. const entry = {
  4261. data: v,
  4262. next: null
  4263. };
  4264. if (this.length > 0) this.tail.next = entry;
  4265. else this.head = entry;
  4266. this.tail = entry;
  4267. ++this.length;
  4268. }
  4269. unshift(v) {
  4270. const entry = {
  4271. data: v,
  4272. next: this.head
  4273. };
  4274. if (this.length === 0) this.tail = entry;
  4275. this.head = entry;
  4276. ++this.length;
  4277. }
  4278. shift() {
  4279. if (this.length === 0) return;
  4280. const ret = this.head.data;
  4281. if (this.length === 1) this.head = this.tail = null;
  4282. else this.head = this.head.next;
  4283. --this.length;
  4284. return ret;
  4285. }
  4286. clear() {
  4287. this.head = this.tail = null;
  4288. this.length = 0;
  4289. }
  4290. join(s) {
  4291. if (this.length === 0) return "";
  4292. let p = this.head;
  4293. let ret = "" + p.data;
  4294. while ((p = p.next) !== null) ret += s + p.data;
  4295. return ret;
  4296. }
  4297. concat(n) {
  4298. if (this.length === 0) return Buffer4.alloc(0);
  4299. const ret = Buffer4.allocUnsafe(n >>> 0);
  4300. let p = this.head;
  4301. let i = 0;
  4302. while (p) {
  4303. TypedArrayPrototypeSet(ret, p.data, i);
  4304. i += p.data.length;
  4305. p = p.next;
  4306. }
  4307. return ret;
  4308. }
  4309. // Consumes a specified amount of bytes or characters from the buffered data.
  4310. consume(n, hasStrings) {
  4311. const data = this.head.data;
  4312. if (n < data.length) {
  4313. const slice = data.slice(0, n);
  4314. this.head.data = data.slice(n);
  4315. return slice;
  4316. }
  4317. if (n === data.length) {
  4318. return this.shift();
  4319. }
  4320. return hasStrings ? this._getString(n) : this._getBuffer(n);
  4321. }
  4322. first() {
  4323. return this.head.data;
  4324. }
  4325. *[SymbolIterator]() {
  4326. for (let p = this.head; p; p = p.next) {
  4327. yield p.data;
  4328. }
  4329. }
  4330. // Consumes a specified amount of characters from the buffered data.
  4331. _getString(n) {
  4332. let ret = "";
  4333. let p = this.head;
  4334. let c = 0;
  4335. do {
  4336. const str = p.data;
  4337. if (n > str.length) {
  4338. ret += str;
  4339. n -= str.length;
  4340. } else {
  4341. if (n === str.length) {
  4342. ret += str;
  4343. ++c;
  4344. if (p.next) this.head = p.next;
  4345. else this.head = this.tail = null;
  4346. } else {
  4347. ret += StringPrototypeSlice(str, 0, n);
  4348. this.head = p;
  4349. p.data = StringPrototypeSlice(str, n);
  4350. }
  4351. break;
  4352. }
  4353. ++c;
  4354. } while ((p = p.next) !== null);
  4355. this.length -= c;
  4356. return ret;
  4357. }
  4358. // Consumes a specified amount of bytes from the buffered data.
  4359. _getBuffer(n) {
  4360. const ret = Buffer4.allocUnsafe(n);
  4361. const retLen = n;
  4362. let p = this.head;
  4363. let c = 0;
  4364. do {
  4365. const buf = p.data;
  4366. if (n > buf.length) {
  4367. TypedArrayPrototypeSet(ret, buf, retLen - n);
  4368. n -= buf.length;
  4369. } else {
  4370. if (n === buf.length) {
  4371. TypedArrayPrototypeSet(ret, buf, retLen - n);
  4372. ++c;
  4373. if (p.next) this.head = p.next;
  4374. else this.head = this.tail = null;
  4375. } else {
  4376. TypedArrayPrototypeSet(ret, new Uint8Array2(buf.buffer, buf.byteOffset, n), retLen - n);
  4377. this.head = p;
  4378. p.data = buf.slice(n);
  4379. }
  4380. break;
  4381. }
  4382. ++c;
  4383. } while ((p = p.next) !== null);
  4384. this.length -= c;
  4385. return ret;
  4386. }
  4387. // Make sure the linked list only shows the minimal necessary information.
  4388. [Symbol.for("nodejs.util.inspect.custom")](_, options) {
  4389. return inspect(this, {
  4390. ...options,
  4391. // Only inspect one level.
  4392. depth: 0,
  4393. // It should not recurse.
  4394. customInspect: false
  4395. });
  4396. }
  4397. };
  4398. }
  4399. });
  4400. // node_modules/readable-stream/lib/internal/streams/state.js
  4401. var require_state = __commonJS({
  4402. "node_modules/readable-stream/lib/internal/streams/state.js"(exports, module) {
  4403. "use strict";
  4404. var { MathFloor, NumberIsInteger } = require_primordials();
  4405. var { validateInteger } = require_validators();
  4406. var { ERR_INVALID_ARG_VALUE } = require_errors().codes;
  4407. var defaultHighWaterMarkBytes = 16 * 1024;
  4408. var defaultHighWaterMarkObjectMode = 16;
  4409. function highWaterMarkFrom(options, isDuplex, duplexKey) {
  4410. return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
  4411. }
  4412. __name(highWaterMarkFrom, "highWaterMarkFrom");
  4413. function getDefaultHighWaterMark(objectMode) {
  4414. return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes;
  4415. }
  4416. __name(getDefaultHighWaterMark, "getDefaultHighWaterMark");
  4417. function setDefaultHighWaterMark(objectMode, value) {
  4418. validateInteger(value, "value", 0);
  4419. if (objectMode) {
  4420. defaultHighWaterMarkObjectMode = value;
  4421. } else {
  4422. defaultHighWaterMarkBytes = value;
  4423. }
  4424. }
  4425. __name(setDefaultHighWaterMark, "setDefaultHighWaterMark");
  4426. function getHighWaterMark(state, options, duplexKey, isDuplex) {
  4427. const hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  4428. if (hwm != null) {
  4429. if (!NumberIsInteger(hwm) || hwm < 0) {
  4430. const name = isDuplex ? `options.${duplexKey}` : "options.highWaterMark";
  4431. throw new ERR_INVALID_ARG_VALUE(name, hwm);
  4432. }
  4433. return MathFloor(hwm);
  4434. }
  4435. return getDefaultHighWaterMark(state.objectMode);
  4436. }
  4437. __name(getHighWaterMark, "getHighWaterMark");
  4438. module.exports = {
  4439. getHighWaterMark,
  4440. getDefaultHighWaterMark,
  4441. setDefaultHighWaterMark
  4442. };
  4443. }
  4444. });
  4445. // node_modules/safe-buffer/index.js
  4446. var require_safe_buffer = __commonJS({
  4447. "node_modules/safe-buffer/index.js"(exports, module) {
  4448. var buffer = require_buffer();
  4449. var Buffer4 = buffer.Buffer;
  4450. function copyProps(src, dst) {
  4451. for (var key in src) {
  4452. dst[key] = src[key];
  4453. }
  4454. }
  4455. __name(copyProps, "copyProps");
  4456. if (Buffer4.from && Buffer4.alloc && Buffer4.allocUnsafe && Buffer4.allocUnsafeSlow) {
  4457. module.exports = buffer;
  4458. } else {
  4459. copyProps(buffer, exports);
  4460. exports.Buffer = SafeBuffer;
  4461. }
  4462. function SafeBuffer(arg, encodingOrOffset, length) {
  4463. return Buffer4(arg, encodingOrOffset, length);
  4464. }
  4465. __name(SafeBuffer, "SafeBuffer");
  4466. SafeBuffer.prototype = Object.create(Buffer4.prototype);
  4467. copyProps(Buffer4, SafeBuffer);
  4468. SafeBuffer.from = function(arg, encodingOrOffset, length) {
  4469. if (typeof arg === "number") {
  4470. throw new TypeError("Argument must not be a number");
  4471. }
  4472. return Buffer4(arg, encodingOrOffset, length);
  4473. };
  4474. SafeBuffer.alloc = function(size, fill, encoding) {
  4475. if (typeof size !== "number") {
  4476. throw new TypeError("Argument must be a number");
  4477. }
  4478. var buf = Buffer4(size);
  4479. if (fill !== void 0) {
  4480. if (typeof encoding === "string") {
  4481. buf.fill(fill, encoding);
  4482. } else {
  4483. buf.fill(fill);
  4484. }
  4485. } else {
  4486. buf.fill(0);
  4487. }
  4488. return buf;
  4489. };
  4490. SafeBuffer.allocUnsafe = function(size) {
  4491. if (typeof size !== "number") {
  4492. throw new TypeError("Argument must be a number");
  4493. }
  4494. return Buffer4(size);
  4495. };
  4496. SafeBuffer.allocUnsafeSlow = function(size) {
  4497. if (typeof size !== "number") {
  4498. throw new TypeError("Argument must be a number");
  4499. }
  4500. return buffer.SlowBuffer(size);
  4501. };
  4502. }
  4503. });
  4504. // node_modules/string_decoder/lib/string_decoder.js
  4505. var require_string_decoder = __commonJS({
  4506. "node_modules/string_decoder/lib/string_decoder.js"(exports) {
  4507. "use strict";
  4508. var Buffer4 = require_safe_buffer().Buffer;
  4509. var isEncoding = Buffer4.isEncoding || function(encoding) {
  4510. encoding = "" + encoding;
  4511. switch (encoding && encoding.toLowerCase()) {
  4512. case "hex":
  4513. case "utf8":
  4514. case "utf-8":
  4515. case "ascii":
  4516. case "binary":
  4517. case "base64":
  4518. case "ucs2":
  4519. case "ucs-2":
  4520. case "utf16le":
  4521. case "utf-16le":
  4522. case "raw":
  4523. return true;
  4524. default:
  4525. return false;
  4526. }
  4527. };
  4528. function _normalizeEncoding(enc) {
  4529. if (!enc) return "utf8";
  4530. var retried;
  4531. while (true) {
  4532. switch (enc) {
  4533. case "utf8":
  4534. case "utf-8":
  4535. return "utf8";
  4536. case "ucs2":
  4537. case "ucs-2":
  4538. case "utf16le":
  4539. case "utf-16le":
  4540. return "utf16le";
  4541. case "latin1":
  4542. case "binary":
  4543. return "latin1";
  4544. case "base64":
  4545. case "ascii":
  4546. case "hex":
  4547. return enc;
  4548. default:
  4549. if (retried) return;
  4550. enc = ("" + enc).toLowerCase();
  4551. retried = true;
  4552. }
  4553. }
  4554. }
  4555. __name(_normalizeEncoding, "_normalizeEncoding");
  4556. function normalizeEncoding(enc) {
  4557. var nenc = _normalizeEncoding(enc);
  4558. if (typeof nenc !== "string" && (Buffer4.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc);
  4559. return nenc || enc;
  4560. }
  4561. __name(normalizeEncoding, "normalizeEncoding");
  4562. exports.StringDecoder = StringDecoder;
  4563. function StringDecoder(encoding) {
  4564. this.encoding = normalizeEncoding(encoding);
  4565. var nb;
  4566. switch (this.encoding) {
  4567. case "utf16le":
  4568. this.text = utf16Text;
  4569. this.end = utf16End;
  4570. nb = 4;
  4571. break;
  4572. case "utf8":
  4573. this.fillLast = utf8FillLast;
  4574. nb = 4;
  4575. break;
  4576. case "base64":
  4577. this.text = base64Text;
  4578. this.end = base64End;
  4579. nb = 3;
  4580. break;
  4581. default:
  4582. this.write = simpleWrite;
  4583. this.end = simpleEnd;
  4584. return;
  4585. }
  4586. this.lastNeed = 0;
  4587. this.lastTotal = 0;
  4588. this.lastChar = Buffer4.allocUnsafe(nb);
  4589. }
  4590. __name(StringDecoder, "StringDecoder");
  4591. StringDecoder.prototype.write = function(buf) {
  4592. if (buf.length === 0) return "";
  4593. var r;
  4594. var i;
  4595. if (this.lastNeed) {
  4596. r = this.fillLast(buf);
  4597. if (r === void 0) return "";
  4598. i = this.lastNeed;
  4599. this.lastNeed = 0;
  4600. } else {
  4601. i = 0;
  4602. }
  4603. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  4604. return r || "";
  4605. };
  4606. StringDecoder.prototype.end = utf8End;
  4607. StringDecoder.prototype.text = utf8Text;
  4608. StringDecoder.prototype.fillLast = function(buf) {
  4609. if (this.lastNeed <= buf.length) {
  4610. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  4611. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  4612. }
  4613. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  4614. this.lastNeed -= buf.length;
  4615. };
  4616. function utf8CheckByte(byte) {
  4617. if (byte <= 127) return 0;
  4618. else if (byte >> 5 === 6) return 2;
  4619. else if (byte >> 4 === 14) return 3;
  4620. else if (byte >> 3 === 30) return 4;
  4621. return byte >> 6 === 2 ? -1 : -2;
  4622. }
  4623. __name(utf8CheckByte, "utf8CheckByte");
  4624. function utf8CheckIncomplete(self2, buf, i) {
  4625. var j = buf.length - 1;
  4626. if (j < i) return 0;
  4627. var nb = utf8CheckByte(buf[j]);
  4628. if (nb >= 0) {
  4629. if (nb > 0) self2.lastNeed = nb - 1;
  4630. return nb;
  4631. }
  4632. if (--j < i || nb === -2) return 0;
  4633. nb = utf8CheckByte(buf[j]);
  4634. if (nb >= 0) {
  4635. if (nb > 0) self2.lastNeed = nb - 2;
  4636. return nb;
  4637. }
  4638. if (--j < i || nb === -2) return 0;
  4639. nb = utf8CheckByte(buf[j]);
  4640. if (nb >= 0) {
  4641. if (nb > 0) {
  4642. if (nb === 2) nb = 0;
  4643. else self2.lastNeed = nb - 3;
  4644. }
  4645. return nb;
  4646. }
  4647. return 0;
  4648. }
  4649. __name(utf8CheckIncomplete, "utf8CheckIncomplete");
  4650. function utf8CheckExtraBytes(self2, buf, p) {
  4651. if ((buf[0] & 192) !== 128) {
  4652. self2.lastNeed = 0;
  4653. return "\uFFFD";
  4654. }
  4655. if (self2.lastNeed > 1 && buf.length > 1) {
  4656. if ((buf[1] & 192) !== 128) {
  4657. self2.lastNeed = 1;
  4658. return "\uFFFD";
  4659. }
  4660. if (self2.lastNeed > 2 && buf.length > 2) {
  4661. if ((buf[2] & 192) !== 128) {
  4662. self2.lastNeed = 2;
  4663. return "\uFFFD";
  4664. }
  4665. }
  4666. }
  4667. }
  4668. __name(utf8CheckExtraBytes, "utf8CheckExtraBytes");
  4669. function utf8FillLast(buf) {
  4670. var p = this.lastTotal - this.lastNeed;
  4671. var r = utf8CheckExtraBytes(this, buf, p);
  4672. if (r !== void 0) return r;
  4673. if (this.lastNeed <= buf.length) {
  4674. buf.copy(this.lastChar, p, 0, this.lastNeed);
  4675. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  4676. }
  4677. buf.copy(this.lastChar, p, 0, buf.length);
  4678. this.lastNeed -= buf.length;
  4679. }
  4680. __name(utf8FillLast, "utf8FillLast");
  4681. function utf8Text(buf, i) {
  4682. var total = utf8CheckIncomplete(this, buf, i);
  4683. if (!this.lastNeed) return buf.toString("utf8", i);
  4684. this.lastTotal = total;
  4685. var end = buf.length - (total - this.lastNeed);
  4686. buf.copy(this.lastChar, 0, end);
  4687. return buf.toString("utf8", i, end);
  4688. }
  4689. __name(utf8Text, "utf8Text");
  4690. function utf8End(buf) {
  4691. var r = buf && buf.length ? this.write(buf) : "";
  4692. if (this.lastNeed) return r + "\uFFFD";
  4693. return r;
  4694. }
  4695. __name(utf8End, "utf8End");
  4696. function utf16Text(buf, i) {
  4697. if ((buf.length - i) % 2 === 0) {
  4698. var r = buf.toString("utf16le", i);
  4699. if (r) {
  4700. var c = r.charCodeAt(r.length - 1);
  4701. if (c >= 55296 && c <= 56319) {
  4702. this.lastNeed = 2;
  4703. this.lastTotal = 4;
  4704. this.lastChar[0] = buf[buf.length - 2];
  4705. this.lastChar[1] = buf[buf.length - 1];
  4706. return r.slice(0, -1);
  4707. }
  4708. }
  4709. return r;
  4710. }
  4711. this.lastNeed = 1;
  4712. this.lastTotal = 2;
  4713. this.lastChar[0] = buf[buf.length - 1];
  4714. return buf.toString("utf16le", i, buf.length - 1);
  4715. }
  4716. __name(utf16Text, "utf16Text");
  4717. function utf16End(buf) {
  4718. var r = buf && buf.length ? this.write(buf) : "";
  4719. if (this.lastNeed) {
  4720. var end = this.lastTotal - this.lastNeed;
  4721. return r + this.lastChar.toString("utf16le", 0, end);
  4722. }
  4723. return r;
  4724. }
  4725. __name(utf16End, "utf16End");
  4726. function base64Text(buf, i) {
  4727. var n = (buf.length - i) % 3;
  4728. if (n === 0) return buf.toString("base64", i);
  4729. this.lastNeed = 3 - n;
  4730. this.lastTotal = 3;
  4731. if (n === 1) {
  4732. this.lastChar[0] = buf[buf.length - 1];
  4733. } else {
  4734. this.lastChar[0] = buf[buf.length - 2];
  4735. this.lastChar[1] = buf[buf.length - 1];
  4736. }
  4737. return buf.toString("base64", i, buf.length - n);
  4738. }
  4739. __name(base64Text, "base64Text");
  4740. function base64End(buf) {
  4741. var r = buf && buf.length ? this.write(buf) : "";
  4742. if (this.lastNeed) return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed);
  4743. return r;
  4744. }
  4745. __name(base64End, "base64End");
  4746. function simpleWrite(buf) {
  4747. return buf.toString(this.encoding);
  4748. }
  4749. __name(simpleWrite, "simpleWrite");
  4750. function simpleEnd(buf) {
  4751. return buf && buf.length ? this.write(buf) : "";
  4752. }
  4753. __name(simpleEnd, "simpleEnd");
  4754. }
  4755. });
  4756. // node_modules/readable-stream/lib/internal/streams/from.js
  4757. var require_from = __commonJS({
  4758. "node_modules/readable-stream/lib/internal/streams/from.js"(exports, module) {
  4759. "use strict";
  4760. var process = require_browser2();
  4761. var { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require_primordials();
  4762. var { Buffer: Buffer4 } = require_buffer();
  4763. var { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_STREAM_NULL_VALUES } = require_errors().codes;
  4764. function from(Readable2, iterable, opts) {
  4765. let iterator;
  4766. if (typeof iterable === "string" || iterable instanceof Buffer4) {
  4767. return new Readable2({
  4768. objectMode: true,
  4769. ...opts,
  4770. read: /* @__PURE__ */ __name(function() {
  4771. this.push(iterable);
  4772. this.push(null);
  4773. }, "read")
  4774. });
  4775. }
  4776. let isAsync;
  4777. if (iterable && iterable[SymbolAsyncIterator]) {
  4778. isAsync = true;
  4779. iterator = iterable[SymbolAsyncIterator]();
  4780. } else if (iterable && iterable[SymbolIterator]) {
  4781. isAsync = false;
  4782. iterator = iterable[SymbolIterator]();
  4783. } else {
  4784. throw new ERR_INVALID_ARG_TYPE2("iterable", ["Iterable"], iterable);
  4785. }
  4786. const readable = new Readable2({
  4787. objectMode: true,
  4788. highWaterMark: 1,
  4789. // TODO(ronag): What options should be allowed?
  4790. ...opts
  4791. });
  4792. let reading = false;
  4793. readable._read = function() {
  4794. if (!reading) {
  4795. reading = true;
  4796. next();
  4797. }
  4798. };
  4799. readable._destroy = function(error, cb) {
  4800. PromisePrototypeThen(
  4801. close2(error),
  4802. () => process.nextTick(cb, error),
  4803. // nextTick is here in case cb throws
  4804. (e) => process.nextTick(cb, e || error)
  4805. );
  4806. };
  4807. async function close2(error) {
  4808. const hadError = error !== void 0 && error !== null;
  4809. const hasThrow = typeof iterator.throw === "function";
  4810. if (hadError && hasThrow) {
  4811. const { value, done } = await iterator.throw(error);
  4812. await value;
  4813. if (done) {
  4814. return;
  4815. }
  4816. }
  4817. if (typeof iterator.return === "function") {
  4818. const { value } = await iterator.return();
  4819. await value;
  4820. }
  4821. }
  4822. __name(close2, "close");
  4823. async function next() {
  4824. for (; ; ) {
  4825. try {
  4826. const { value, done } = isAsync ? await iterator.next() : iterator.next();
  4827. if (done) {
  4828. readable.push(null);
  4829. } else {
  4830. const res = value && typeof value.then === "function" ? await value : value;
  4831. if (res === null) {
  4832. reading = false;
  4833. throw new ERR_STREAM_NULL_VALUES();
  4834. } else if (readable.push(res)) {
  4835. continue;
  4836. } else {
  4837. reading = false;
  4838. }
  4839. }
  4840. } catch (err) {
  4841. readable.destroy(err);
  4842. }
  4843. break;
  4844. }
  4845. }
  4846. __name(next, "next");
  4847. return readable;
  4848. }
  4849. __name(from, "from");
  4850. module.exports = from;
  4851. }
  4852. });
  4853. // node_modules/readable-stream/lib/internal/streams/readable.js
  4854. var require_readable = __commonJS({
  4855. "node_modules/readable-stream/lib/internal/streams/readable.js"(exports, module) {
  4856. var process = require_browser2();
  4857. var {
  4858. ArrayPrototypeIndexOf,
  4859. NumberIsInteger,
  4860. NumberIsNaN,
  4861. NumberParseInt,
  4862. ObjectDefineProperties,
  4863. ObjectKeys,
  4864. ObjectSetPrototypeOf,
  4865. Promise: Promise2,
  4866. SafeSet,
  4867. SymbolAsyncDispose,
  4868. SymbolAsyncIterator,
  4869. Symbol: Symbol2
  4870. } = require_primordials();
  4871. module.exports = Readable2;
  4872. Readable2.ReadableState = ReadableState;
  4873. var { EventEmitter: EE } = require_events();
  4874. var { Stream, prependListener } = require_legacy();
  4875. var { Buffer: Buffer4 } = require_buffer();
  4876. var { addAbortSignal } = require_add_abort_signal();
  4877. var eos = require_end_of_stream();
  4878. var debug = require_util().debuglog("stream", (fn) => {
  4879. debug = fn;
  4880. });
  4881. var BufferList = require_buffer_list();
  4882. var destroyImpl = require_destroy();
  4883. var { getHighWaterMark, getDefaultHighWaterMark } = require_state();
  4884. var {
  4885. aggregateTwoErrors,
  4886. codes: {
  4887. ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2,
  4888. ERR_METHOD_NOT_IMPLEMENTED,
  4889. ERR_OUT_OF_RANGE,
  4890. ERR_STREAM_PUSH_AFTER_EOF,
  4891. ERR_STREAM_UNSHIFT_AFTER_END_EVENT
  4892. },
  4893. AbortError
  4894. } = require_errors();
  4895. var { validateObject } = require_validators();
  4896. var kPaused = Symbol2("kPaused");
  4897. var { StringDecoder } = require_string_decoder();
  4898. var from = require_from();
  4899. ObjectSetPrototypeOf(Readable2.prototype, Stream.prototype);
  4900. ObjectSetPrototypeOf(Readable2, Stream);
  4901. var nop2 = /* @__PURE__ */ __name(() => {
  4902. }, "nop");
  4903. var { errorOrDestroy } = destroyImpl;
  4904. var kObjectMode = 1 << 0;
  4905. var kEnded = 1 << 1;
  4906. var kEndEmitted = 1 << 2;
  4907. var kReading = 1 << 3;
  4908. var kConstructed = 1 << 4;
  4909. var kSync = 1 << 5;
  4910. var kNeedReadable = 1 << 6;
  4911. var kEmittedReadable = 1 << 7;
  4912. var kReadableListening = 1 << 8;
  4913. var kResumeScheduled = 1 << 9;
  4914. var kErrorEmitted = 1 << 10;
  4915. var kEmitClose = 1 << 11;
  4916. var kAutoDestroy = 1 << 12;
  4917. var kDestroyed = 1 << 13;
  4918. var kClosed = 1 << 14;
  4919. var kCloseEmitted = 1 << 15;
  4920. var kMultiAwaitDrain = 1 << 16;
  4921. var kReadingMore = 1 << 17;
  4922. var kDataEmitted = 1 << 18;
  4923. function makeBitMapDescriptor(bit) {
  4924. return {
  4925. enumerable: false,
  4926. get: /* @__PURE__ */ __name(function() {
  4927. return (this.state & bit) !== 0;
  4928. }, "get"),
  4929. set: /* @__PURE__ */ __name(function(value) {
  4930. if (value) this.state |= bit;
  4931. else this.state &= ~bit;
  4932. }, "set")
  4933. };
  4934. }
  4935. __name(makeBitMapDescriptor, "makeBitMapDescriptor");
  4936. ObjectDefineProperties(ReadableState.prototype, {
  4937. objectMode: makeBitMapDescriptor(kObjectMode),
  4938. ended: makeBitMapDescriptor(kEnded),
  4939. endEmitted: makeBitMapDescriptor(kEndEmitted),
  4940. reading: makeBitMapDescriptor(kReading),
  4941. // Stream is still being constructed and cannot be
  4942. // destroyed until construction finished or failed.
  4943. // Async construction is opt in, therefore we start as
  4944. // constructed.
  4945. constructed: makeBitMapDescriptor(kConstructed),
  4946. // A flag to be able to tell if the event 'readable'/'data' is emitted
  4947. // immediately, or on a later tick. We set this to true at first, because
  4948. // any actions that shouldn't happen until "later" should generally also
  4949. // not happen before the first read call.
  4950. sync: makeBitMapDescriptor(kSync),
  4951. // Whenever we return null, then we set a flag to say
  4952. // that we're awaiting a 'readable' event emission.
  4953. needReadable: makeBitMapDescriptor(kNeedReadable),
  4954. emittedReadable: makeBitMapDescriptor(kEmittedReadable),
  4955. readableListening: makeBitMapDescriptor(kReadableListening),
  4956. resumeScheduled: makeBitMapDescriptor(kResumeScheduled),
  4957. // True if the error was already emitted and should not be thrown again.
  4958. errorEmitted: makeBitMapDescriptor(kErrorEmitted),
  4959. emitClose: makeBitMapDescriptor(kEmitClose),
  4960. autoDestroy: makeBitMapDescriptor(kAutoDestroy),
  4961. // Has it been destroyed.
  4962. destroyed: makeBitMapDescriptor(kDestroyed),
  4963. // Indicates whether the stream has finished destroying.
  4964. closed: makeBitMapDescriptor(kClosed),
  4965. // True if close has been emitted or would have been emitted
  4966. // depending on emitClose.
  4967. closeEmitted: makeBitMapDescriptor(kCloseEmitted),
  4968. multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain),
  4969. // If true, a maybeReadMore has been scheduled.
  4970. readingMore: makeBitMapDescriptor(kReadingMore),
  4971. dataEmitted: makeBitMapDescriptor(kDataEmitted)
  4972. });
  4973. function ReadableState(options, stream, isDuplex) {
  4974. if (typeof isDuplex !== "boolean") isDuplex = stream instanceof require_duplex();
  4975. this.state = kEmitClose | kAutoDestroy | kConstructed | kSync;
  4976. if (options && options.objectMode) this.state |= kObjectMode;
  4977. if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode;
  4978. this.highWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false);
  4979. this.buffer = new BufferList();
  4980. this.length = 0;
  4981. this.pipes = [];
  4982. this.flowing = null;
  4983. this[kPaused] = null;
  4984. if (options && options.emitClose === false) this.state &= ~kEmitClose;
  4985. if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy;
  4986. this.errored = null;
  4987. this.defaultEncoding = options && options.defaultEncoding || "utf8";
  4988. this.awaitDrainWriters = null;
  4989. this.decoder = null;
  4990. this.encoding = null;
  4991. if (options && options.encoding) {
  4992. this.decoder = new StringDecoder(options.encoding);
  4993. this.encoding = options.encoding;
  4994. }
  4995. }
  4996. __name(ReadableState, "ReadableState");
  4997. function Readable2(options) {
  4998. if (!(this instanceof Readable2)) return new Readable2(options);
  4999. const isDuplex = this instanceof require_duplex();
  5000. this._readableState = new ReadableState(options, this, isDuplex);
  5001. if (options) {
  5002. if (typeof options.read === "function") this._read = options.read;
  5003. if (typeof options.destroy === "function") this._destroy = options.destroy;
  5004. if (typeof options.construct === "function") this._construct = options.construct;
  5005. if (options.signal && !isDuplex) addAbortSignal(options.signal, this);
  5006. }
  5007. Stream.call(this, options);
  5008. destroyImpl.construct(this, () => {
  5009. if (this._readableState.needReadable) {
  5010. maybeReadMore(this, this._readableState);
  5011. }
  5012. });
  5013. }
  5014. __name(Readable2, "Readable");
  5015. Readable2.prototype.destroy = destroyImpl.destroy;
  5016. Readable2.prototype._undestroy = destroyImpl.undestroy;
  5017. Readable2.prototype._destroy = function(err, cb) {
  5018. cb(err);
  5019. };
  5020. Readable2.prototype[EE.captureRejectionSymbol] = function(err) {
  5021. this.destroy(err);
  5022. };
  5023. Readable2.prototype[SymbolAsyncDispose] = function() {
  5024. let error;
  5025. if (!this.destroyed) {
  5026. error = this.readableEnded ? null : new AbortError();
  5027. this.destroy(error);
  5028. }
  5029. return new Promise2((resolve2, reject) => eos(this, (err) => err && err !== error ? reject(err) : resolve2(null)));
  5030. };
  5031. Readable2.prototype.push = function(chunk, encoding) {
  5032. return readableAddChunk(this, chunk, encoding, false);
  5033. };
  5034. Readable2.prototype.unshift = function(chunk, encoding) {
  5035. return readableAddChunk(this, chunk, encoding, true);
  5036. };
  5037. function readableAddChunk(stream, chunk, encoding, addToFront) {
  5038. debug("readableAddChunk", chunk);
  5039. const state = stream._readableState;
  5040. let err;
  5041. if ((state.state & kObjectMode) === 0) {
  5042. if (typeof chunk === "string") {
  5043. encoding = encoding || state.defaultEncoding;
  5044. if (state.encoding !== encoding) {
  5045. if (addToFront && state.encoding) {
  5046. chunk = Buffer4.from(chunk, encoding).toString(state.encoding);
  5047. } else {
  5048. chunk = Buffer4.from(chunk, encoding);
  5049. encoding = "";
  5050. }
  5051. }
  5052. } else if (chunk instanceof Buffer4) {
  5053. encoding = "";
  5054. } else if (Stream._isUint8Array(chunk)) {
  5055. chunk = Stream._uint8ArrayToBuffer(chunk);
  5056. encoding = "";
  5057. } else if (chunk != null) {
  5058. err = new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk);
  5059. }
  5060. }
  5061. if (err) {
  5062. errorOrDestroy(stream, err);
  5063. } else if (chunk === null) {
  5064. state.state &= ~kReading;
  5065. onEofChunk(stream, state);
  5066. } else if ((state.state & kObjectMode) !== 0 || chunk && chunk.length > 0) {
  5067. if (addToFront) {
  5068. if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());
  5069. else if (state.destroyed || state.errored) return false;
  5070. else addChunk(stream, state, chunk, true);
  5071. } else if (state.ended) {
  5072. errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
  5073. } else if (state.destroyed || state.errored) {
  5074. return false;
  5075. } else {
  5076. state.state &= ~kReading;
  5077. if (state.decoder && !encoding) {
  5078. chunk = state.decoder.write(chunk);
  5079. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);
  5080. else maybeReadMore(stream, state);
  5081. } else {
  5082. addChunk(stream, state, chunk, false);
  5083. }
  5084. }
  5085. } else if (!addToFront) {
  5086. state.state &= ~kReading;
  5087. maybeReadMore(stream, state);
  5088. }
  5089. return !state.ended && (state.length < state.highWaterMark || state.length === 0);
  5090. }
  5091. __name(readableAddChunk, "readableAddChunk");
  5092. function addChunk(stream, state, chunk, addToFront) {
  5093. if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount("data") > 0) {
  5094. if ((state.state & kMultiAwaitDrain) !== 0) {
  5095. state.awaitDrainWriters.clear();
  5096. } else {
  5097. state.awaitDrainWriters = null;
  5098. }
  5099. state.dataEmitted = true;
  5100. stream.emit("data", chunk);
  5101. } else {
  5102. state.length += state.objectMode ? 1 : chunk.length;
  5103. if (addToFront) state.buffer.unshift(chunk);
  5104. else state.buffer.push(chunk);
  5105. if ((state.state & kNeedReadable) !== 0) emitReadable(stream);
  5106. }
  5107. maybeReadMore(stream, state);
  5108. }
  5109. __name(addChunk, "addChunk");
  5110. Readable2.prototype.isPaused = function() {
  5111. const state = this._readableState;
  5112. return state[kPaused] === true || state.flowing === false;
  5113. };
  5114. Readable2.prototype.setEncoding = function(enc) {
  5115. const decoder = new StringDecoder(enc);
  5116. this._readableState.decoder = decoder;
  5117. this._readableState.encoding = this._readableState.decoder.encoding;
  5118. const buffer = this._readableState.buffer;
  5119. let content = "";
  5120. for (const data of buffer) {
  5121. content += decoder.write(data);
  5122. }
  5123. buffer.clear();
  5124. if (content !== "") buffer.push(content);
  5125. this._readableState.length = content.length;
  5126. return this;
  5127. };
  5128. var MAX_HWM = 1073741824;
  5129. function computeNewHighWaterMark(n) {
  5130. if (n > MAX_HWM) {
  5131. throw new ERR_OUT_OF_RANGE("size", "<= 1GiB", n);
  5132. } else {
  5133. n--;
  5134. n |= n >>> 1;
  5135. n |= n >>> 2;
  5136. n |= n >>> 4;
  5137. n |= n >>> 8;
  5138. n |= n >>> 16;
  5139. n++;
  5140. }
  5141. return n;
  5142. }
  5143. __name(computeNewHighWaterMark, "computeNewHighWaterMark");
  5144. function howMuchToRead(n, state) {
  5145. if (n <= 0 || state.length === 0 && state.ended) return 0;
  5146. if ((state.state & kObjectMode) !== 0) return 1;
  5147. if (NumberIsNaN(n)) {
  5148. if (state.flowing && state.length) return state.buffer.first().length;
  5149. return state.length;
  5150. }
  5151. if (n <= state.length) return n;
  5152. return state.ended ? state.length : 0;
  5153. }
  5154. __name(howMuchToRead, "howMuchToRead");
  5155. Readable2.prototype.read = function(n) {
  5156. debug("read", n);
  5157. if (n === void 0) {
  5158. n = NaN;
  5159. } else if (!NumberIsInteger(n)) {
  5160. n = NumberParseInt(n, 10);
  5161. }
  5162. const state = this._readableState;
  5163. const nOrig = n;
  5164. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  5165. if (n !== 0) state.state &= ~kEmittedReadable;
  5166. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
  5167. debug("read: emitReadable", state.length, state.ended);
  5168. if (state.length === 0 && state.ended) endReadable(this);
  5169. else emitReadable(this);
  5170. return null;
  5171. }
  5172. n = howMuchToRead(n, state);
  5173. if (n === 0 && state.ended) {
  5174. if (state.length === 0) endReadable(this);
  5175. return null;
  5176. }
  5177. let doRead = (state.state & kNeedReadable) !== 0;
  5178. debug("need readable", doRead);
  5179. if (state.length === 0 || state.length - n < state.highWaterMark) {
  5180. doRead = true;
  5181. debug("length less than watermark", doRead);
  5182. }
  5183. if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) {
  5184. doRead = false;
  5185. debug("reading, ended or constructing", doRead);
  5186. } else if (doRead) {
  5187. debug("do read");
  5188. state.state |= kReading | kSync;
  5189. if (state.length === 0) state.state |= kNeedReadable;
  5190. try {
  5191. this._read(state.highWaterMark);
  5192. } catch (err) {
  5193. errorOrDestroy(this, err);
  5194. }
  5195. state.state &= ~kSync;
  5196. if (!state.reading) n = howMuchToRead(nOrig, state);
  5197. }
  5198. let ret;
  5199. if (n > 0) ret = fromList(n, state);
  5200. else ret = null;
  5201. if (ret === null) {
  5202. state.needReadable = state.length <= state.highWaterMark;
  5203. n = 0;
  5204. } else {
  5205. state.length -= n;
  5206. if (state.multiAwaitDrain) {
  5207. state.awaitDrainWriters.clear();
  5208. } else {
  5209. state.awaitDrainWriters = null;
  5210. }
  5211. }
  5212. if (state.length === 0) {
  5213. if (!state.ended) state.needReadable = true;
  5214. if (nOrig !== n && state.ended) endReadable(this);
  5215. }
  5216. if (ret !== null && !state.errorEmitted && !state.closeEmitted) {
  5217. state.dataEmitted = true;
  5218. this.emit("data", ret);
  5219. }
  5220. return ret;
  5221. };
  5222. function onEofChunk(stream, state) {
  5223. debug("onEofChunk");
  5224. if (state.ended) return;
  5225. if (state.decoder) {
  5226. const chunk = state.decoder.end();
  5227. if (chunk && chunk.length) {
  5228. state.buffer.push(chunk);
  5229. state.length += state.objectMode ? 1 : chunk.length;
  5230. }
  5231. }
  5232. state.ended = true;
  5233. if (state.sync) {
  5234. emitReadable(stream);
  5235. } else {
  5236. state.needReadable = false;
  5237. state.emittedReadable = true;
  5238. emitReadable_(stream);
  5239. }
  5240. }
  5241. __name(onEofChunk, "onEofChunk");
  5242. function emitReadable(stream) {
  5243. const state = stream._readableState;
  5244. debug("emitReadable", state.needReadable, state.emittedReadable);
  5245. state.needReadable = false;
  5246. if (!state.emittedReadable) {
  5247. debug("emitReadable", state.flowing);
  5248. state.emittedReadable = true;
  5249. process.nextTick(emitReadable_, stream);
  5250. }
  5251. }
  5252. __name(emitReadable, "emitReadable");
  5253. function emitReadable_(stream) {
  5254. const state = stream._readableState;
  5255. debug("emitReadable_", state.destroyed, state.length, state.ended);
  5256. if (!state.destroyed && !state.errored && (state.length || state.ended)) {
  5257. stream.emit("readable");
  5258. state.emittedReadable = false;
  5259. }
  5260. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  5261. flow(stream);
  5262. }
  5263. __name(emitReadable_, "emitReadable_");
  5264. function maybeReadMore(stream, state) {
  5265. if (!state.readingMore && state.constructed) {
  5266. state.readingMore = true;
  5267. process.nextTick(maybeReadMore_, stream, state);
  5268. }
  5269. }
  5270. __name(maybeReadMore, "maybeReadMore");
  5271. function maybeReadMore_(stream, state) {
  5272. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
  5273. const len = state.length;
  5274. debug("maybeReadMore read 0");
  5275. stream.read(0);
  5276. if (len === state.length)
  5277. break;
  5278. }
  5279. state.readingMore = false;
  5280. }
  5281. __name(maybeReadMore_, "maybeReadMore_");
  5282. Readable2.prototype._read = function(n) {
  5283. throw new ERR_METHOD_NOT_IMPLEMENTED("_read()");
  5284. };
  5285. Readable2.prototype.pipe = function(dest, pipeOpts) {
  5286. const src = this;
  5287. const state = this._readableState;
  5288. if (state.pipes.length === 1) {
  5289. if (!state.multiAwaitDrain) {
  5290. state.multiAwaitDrain = true;
  5291. state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []);
  5292. }
  5293. }
  5294. state.pipes.push(dest);
  5295. debug("pipe count=%d opts=%j", state.pipes.length, pipeOpts);
  5296. const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  5297. const endFn = doEnd ? onend : unpipe;
  5298. if (state.endEmitted) process.nextTick(endFn);
  5299. else src.once("end", endFn);
  5300. dest.on("unpipe", onunpipe);
  5301. function onunpipe(readable, unpipeInfo) {
  5302. debug("onunpipe");
  5303. if (readable === src) {
  5304. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  5305. unpipeInfo.hasUnpiped = true;
  5306. cleanup();
  5307. }
  5308. }
  5309. }
  5310. __name(onunpipe, "onunpipe");
  5311. function onend() {
  5312. debug("onend");
  5313. dest.end();
  5314. }
  5315. __name(onend, "onend");
  5316. let ondrain;
  5317. let cleanedUp = false;
  5318. function cleanup() {
  5319. debug("cleanup");
  5320. dest.removeListener("close", onclose);
  5321. dest.removeListener("finish", onfinish);
  5322. if (ondrain) {
  5323. dest.removeListener("drain", ondrain);
  5324. }
  5325. dest.removeListener("error", onerror);
  5326. dest.removeListener("unpipe", onunpipe);
  5327. src.removeListener("end", onend);
  5328. src.removeListener("end", unpipe);
  5329. src.removeListener("data", ondata);
  5330. cleanedUp = true;
  5331. if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  5332. }
  5333. __name(cleanup, "cleanup");
  5334. function pause() {
  5335. if (!cleanedUp) {
  5336. if (state.pipes.length === 1 && state.pipes[0] === dest) {
  5337. debug("false write response, pause", 0);
  5338. state.awaitDrainWriters = dest;
  5339. state.multiAwaitDrain = false;
  5340. } else if (state.pipes.length > 1 && state.pipes.includes(dest)) {
  5341. debug("false write response, pause", state.awaitDrainWriters.size);
  5342. state.awaitDrainWriters.add(dest);
  5343. }
  5344. src.pause();
  5345. }
  5346. if (!ondrain) {
  5347. ondrain = pipeOnDrain(src, dest);
  5348. dest.on("drain", ondrain);
  5349. }
  5350. }
  5351. __name(pause, "pause");
  5352. src.on("data", ondata);
  5353. function ondata(chunk) {
  5354. debug("ondata");
  5355. const ret = dest.write(chunk);
  5356. debug("dest.write", ret);
  5357. if (ret === false) {
  5358. pause();
  5359. }
  5360. }
  5361. __name(ondata, "ondata");
  5362. function onerror(er) {
  5363. debug("onerror", er);
  5364. unpipe();
  5365. dest.removeListener("error", onerror);
  5366. if (dest.listenerCount("error") === 0) {
  5367. const s = dest._writableState || dest._readableState;
  5368. if (s && !s.errorEmitted) {
  5369. errorOrDestroy(dest, er);
  5370. } else {
  5371. dest.emit("error", er);
  5372. }
  5373. }
  5374. }
  5375. __name(onerror, "onerror");
  5376. prependListener(dest, "error", onerror);
  5377. function onclose() {
  5378. dest.removeListener("finish", onfinish);
  5379. unpipe();
  5380. }
  5381. __name(onclose, "onclose");
  5382. dest.once("close", onclose);
  5383. function onfinish() {
  5384. debug("onfinish");
  5385. dest.removeListener("close", onclose);
  5386. unpipe();
  5387. }
  5388. __name(onfinish, "onfinish");
  5389. dest.once("finish", onfinish);
  5390. function unpipe() {
  5391. debug("unpipe");
  5392. src.unpipe(dest);
  5393. }
  5394. __name(unpipe, "unpipe");
  5395. dest.emit("pipe", src);
  5396. if (dest.writableNeedDrain === true) {
  5397. pause();
  5398. } else if (!state.flowing) {
  5399. debug("pipe resume");
  5400. src.resume();
  5401. }
  5402. return dest;
  5403. };
  5404. function pipeOnDrain(src, dest) {
  5405. return /* @__PURE__ */ __name(function pipeOnDrainFunctionResult() {
  5406. const state = src._readableState;
  5407. if (state.awaitDrainWriters === dest) {
  5408. debug("pipeOnDrain", 1);
  5409. state.awaitDrainWriters = null;
  5410. } else if (state.multiAwaitDrain) {
  5411. debug("pipeOnDrain", state.awaitDrainWriters.size);
  5412. state.awaitDrainWriters.delete(dest);
  5413. }
  5414. if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount("data")) {
  5415. src.resume();
  5416. }
  5417. }, "pipeOnDrainFunctionResult");
  5418. }
  5419. __name(pipeOnDrain, "pipeOnDrain");
  5420. Readable2.prototype.unpipe = function(dest) {
  5421. const state = this._readableState;
  5422. const unpipeInfo = {
  5423. hasUnpiped: false
  5424. };
  5425. if (state.pipes.length === 0) return this;
  5426. if (!dest) {
  5427. const dests = state.pipes;
  5428. state.pipes = [];
  5429. this.pause();
  5430. for (let i = 0; i < dests.length; i++)
  5431. dests[i].emit("unpipe", this, {
  5432. hasUnpiped: false
  5433. });
  5434. return this;
  5435. }
  5436. const index = ArrayPrototypeIndexOf(state.pipes, dest);
  5437. if (index === -1) return this;
  5438. state.pipes.splice(index, 1);
  5439. if (state.pipes.length === 0) this.pause();
  5440. dest.emit("unpipe", this, unpipeInfo);
  5441. return this;
  5442. };
  5443. Readable2.prototype.on = function(ev, fn) {
  5444. const res = Stream.prototype.on.call(this, ev, fn);
  5445. const state = this._readableState;
  5446. if (ev === "data") {
  5447. state.readableListening = this.listenerCount("readable") > 0;
  5448. if (state.flowing !== false) this.resume();
  5449. } else if (ev === "readable") {
  5450. if (!state.endEmitted && !state.readableListening) {
  5451. state.readableListening = state.needReadable = true;
  5452. state.flowing = false;
  5453. state.emittedReadable = false;
  5454. debug("on readable", state.length, state.reading);
  5455. if (state.length) {
  5456. emitReadable(this);
  5457. } else if (!state.reading) {
  5458. process.nextTick(nReadingNextTick, this);
  5459. }
  5460. }
  5461. }
  5462. return res;
  5463. };
  5464. Readable2.prototype.addListener = Readable2.prototype.on;
  5465. Readable2.prototype.removeListener = function(ev, fn) {
  5466. const res = Stream.prototype.removeListener.call(this, ev, fn);
  5467. if (ev === "readable") {
  5468. process.nextTick(updateReadableListening, this);
  5469. }
  5470. return res;
  5471. };
  5472. Readable2.prototype.off = Readable2.prototype.removeListener;
  5473. Readable2.prototype.removeAllListeners = function(ev) {
  5474. const res = Stream.prototype.removeAllListeners.apply(this, arguments);
  5475. if (ev === "readable" || ev === void 0) {
  5476. process.nextTick(updateReadableListening, this);
  5477. }
  5478. return res;
  5479. };
  5480. function updateReadableListening(self2) {
  5481. const state = self2._readableState;
  5482. state.readableListening = self2.listenerCount("readable") > 0;
  5483. if (state.resumeScheduled && state[kPaused] === false) {
  5484. state.flowing = true;
  5485. } else if (self2.listenerCount("data") > 0) {
  5486. self2.resume();
  5487. } else if (!state.readableListening) {
  5488. state.flowing = null;
  5489. }
  5490. }
  5491. __name(updateReadableListening, "updateReadableListening");
  5492. function nReadingNextTick(self2) {
  5493. debug("readable nexttick read 0");
  5494. self2.read(0);
  5495. }
  5496. __name(nReadingNextTick, "nReadingNextTick");
  5497. Readable2.prototype.resume = function() {
  5498. const state = this._readableState;
  5499. if (!state.flowing) {
  5500. debug("resume");
  5501. state.flowing = !state.readableListening;
  5502. resume(this, state);
  5503. }
  5504. state[kPaused] = false;
  5505. return this;
  5506. };
  5507. function resume(stream, state) {
  5508. if (!state.resumeScheduled) {
  5509. state.resumeScheduled = true;
  5510. process.nextTick(resume_, stream, state);
  5511. }
  5512. }
  5513. __name(resume, "resume");
  5514. function resume_(stream, state) {
  5515. debug("resume", state.reading);
  5516. if (!state.reading) {
  5517. stream.read(0);
  5518. }
  5519. state.resumeScheduled = false;
  5520. stream.emit("resume");
  5521. flow(stream);
  5522. if (state.flowing && !state.reading) stream.read(0);
  5523. }
  5524. __name(resume_, "resume_");
  5525. Readable2.prototype.pause = function() {
  5526. debug("call pause flowing=%j", this._readableState.flowing);
  5527. if (this._readableState.flowing !== false) {
  5528. debug("pause");
  5529. this._readableState.flowing = false;
  5530. this.emit("pause");
  5531. }
  5532. this._readableState[kPaused] = true;
  5533. return this;
  5534. };
  5535. function flow(stream) {
  5536. const state = stream._readableState;
  5537. debug("flow", state.flowing);
  5538. while (state.flowing && stream.read() !== null) ;
  5539. }
  5540. __name(flow, "flow");
  5541. Readable2.prototype.wrap = function(stream) {
  5542. let paused = false;
  5543. stream.on("data", (chunk) => {
  5544. if (!this.push(chunk) && stream.pause) {
  5545. paused = true;
  5546. stream.pause();
  5547. }
  5548. });
  5549. stream.on("end", () => {
  5550. this.push(null);
  5551. });
  5552. stream.on("error", (err) => {
  5553. errorOrDestroy(this, err);
  5554. });
  5555. stream.on("close", () => {
  5556. this.destroy();
  5557. });
  5558. stream.on("destroy", () => {
  5559. this.destroy();
  5560. });
  5561. this._read = () => {
  5562. if (paused && stream.resume) {
  5563. paused = false;
  5564. stream.resume();
  5565. }
  5566. };
  5567. const streamKeys = ObjectKeys(stream);
  5568. for (let j = 1; j < streamKeys.length; j++) {
  5569. const i = streamKeys[j];
  5570. if (this[i] === void 0 && typeof stream[i] === "function") {
  5571. this[i] = stream[i].bind(stream);
  5572. }
  5573. }
  5574. return this;
  5575. };
  5576. Readable2.prototype[SymbolAsyncIterator] = function() {
  5577. return streamToAsyncIterator(this);
  5578. };
  5579. Readable2.prototype.iterator = function(options) {
  5580. if (options !== void 0) {
  5581. validateObject(options, "options");
  5582. }
  5583. return streamToAsyncIterator(this, options);
  5584. };
  5585. function streamToAsyncIterator(stream, options) {
  5586. if (typeof stream.read !== "function") {
  5587. stream = Readable2.wrap(stream, {
  5588. objectMode: true
  5589. });
  5590. }
  5591. const iter = createAsyncIterator(stream, options);
  5592. iter.stream = stream;
  5593. return iter;
  5594. }
  5595. __name(streamToAsyncIterator, "streamToAsyncIterator");
  5596. async function* createAsyncIterator(stream, options) {
  5597. let callback = nop2;
  5598. function next(resolve2) {
  5599. if (this === stream) {
  5600. callback();
  5601. callback = nop2;
  5602. } else {
  5603. callback = resolve2;
  5604. }
  5605. }
  5606. __name(next, "next");
  5607. stream.on("readable", next);
  5608. let error;
  5609. const cleanup = eos(
  5610. stream,
  5611. {
  5612. writable: false
  5613. },
  5614. (err) => {
  5615. error = err ? aggregateTwoErrors(error, err) : null;
  5616. callback();
  5617. callback = nop2;
  5618. }
  5619. );
  5620. try {
  5621. while (true) {
  5622. const chunk = stream.destroyed ? null : stream.read();
  5623. if (chunk !== null) {
  5624. yield chunk;
  5625. } else if (error) {
  5626. throw error;
  5627. } else if (error === null) {
  5628. return;
  5629. } else {
  5630. await new Promise2(next);
  5631. }
  5632. }
  5633. } catch (err) {
  5634. error = aggregateTwoErrors(error, err);
  5635. throw error;
  5636. } finally {
  5637. if ((error || (options === null || options === void 0 ? void 0 : options.destroyOnReturn) !== false) && (error === void 0 || stream._readableState.autoDestroy)) {
  5638. destroyImpl.destroyer(stream, null);
  5639. } else {
  5640. stream.off("readable", next);
  5641. cleanup();
  5642. }
  5643. }
  5644. }
  5645. __name(createAsyncIterator, "createAsyncIterator");
  5646. ObjectDefineProperties(Readable2.prototype, {
  5647. readable: {
  5648. __proto__: null,
  5649. get: /* @__PURE__ */ __name(function() {
  5650. const r = this._readableState;
  5651. return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted;
  5652. }, "get"),
  5653. set: /* @__PURE__ */ __name(function(val) {
  5654. if (this._readableState) {
  5655. this._readableState.readable = !!val;
  5656. }
  5657. }, "set")
  5658. },
  5659. readableDidRead: {
  5660. __proto__: null,
  5661. enumerable: false,
  5662. get: /* @__PURE__ */ __name(function() {
  5663. return this._readableState.dataEmitted;
  5664. }, "get")
  5665. },
  5666. readableAborted: {
  5667. __proto__: null,
  5668. enumerable: false,
  5669. get: /* @__PURE__ */ __name(function() {
  5670. return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted);
  5671. }, "get")
  5672. },
  5673. readableHighWaterMark: {
  5674. __proto__: null,
  5675. enumerable: false,
  5676. get: /* @__PURE__ */ __name(function() {
  5677. return this._readableState.highWaterMark;
  5678. }, "get")
  5679. },
  5680. readableBuffer: {
  5681. __proto__: null,
  5682. enumerable: false,
  5683. get: /* @__PURE__ */ __name(function() {
  5684. return this._readableState && this._readableState.buffer;
  5685. }, "get")
  5686. },
  5687. readableFlowing: {
  5688. __proto__: null,
  5689. enumerable: false,
  5690. get: /* @__PURE__ */ __name(function() {
  5691. return this._readableState.flowing;
  5692. }, "get"),
  5693. set: /* @__PURE__ */ __name(function(state) {
  5694. if (this._readableState) {
  5695. this._readableState.flowing = state;
  5696. }
  5697. }, "set")
  5698. },
  5699. readableLength: {
  5700. __proto__: null,
  5701. enumerable: false,
  5702. get: /* @__PURE__ */ __name(function() {
  5703. return this._readableState.length;
  5704. }, "get")
  5705. },
  5706. readableObjectMode: {
  5707. __proto__: null,
  5708. enumerable: false,
  5709. get: /* @__PURE__ */ __name(function() {
  5710. return this._readableState ? this._readableState.objectMode : false;
  5711. }, "get")
  5712. },
  5713. readableEncoding: {
  5714. __proto__: null,
  5715. enumerable: false,
  5716. get: /* @__PURE__ */ __name(function() {
  5717. return this._readableState ? this._readableState.encoding : null;
  5718. }, "get")
  5719. },
  5720. errored: {
  5721. __proto__: null,
  5722. enumerable: false,
  5723. get: /* @__PURE__ */ __name(function() {
  5724. return this._readableState ? this._readableState.errored : null;
  5725. }, "get")
  5726. },
  5727. closed: {
  5728. __proto__: null,
  5729. get: /* @__PURE__ */ __name(function() {
  5730. return this._readableState ? this._readableState.closed : false;
  5731. }, "get")
  5732. },
  5733. destroyed: {
  5734. __proto__: null,
  5735. enumerable: false,
  5736. get: /* @__PURE__ */ __name(function() {
  5737. return this._readableState ? this._readableState.destroyed : false;
  5738. }, "get"),
  5739. set: /* @__PURE__ */ __name(function(value) {
  5740. if (!this._readableState) {
  5741. return;
  5742. }
  5743. this._readableState.destroyed = value;
  5744. }, "set")
  5745. },
  5746. readableEnded: {
  5747. __proto__: null,
  5748. enumerable: false,
  5749. get: /* @__PURE__ */ __name(function() {
  5750. return this._readableState ? this._readableState.endEmitted : false;
  5751. }, "get")
  5752. }
  5753. });
  5754. ObjectDefineProperties(ReadableState.prototype, {
  5755. // Legacy getter for `pipesCount`.
  5756. pipesCount: {
  5757. __proto__: null,
  5758. get: /* @__PURE__ */ __name(function() {
  5759. return this.pipes.length;
  5760. }, "get")
  5761. },
  5762. // Legacy property for `paused`.
  5763. paused: {
  5764. __proto__: null,
  5765. get: /* @__PURE__ */ __name(function() {
  5766. return this[kPaused] !== false;
  5767. }, "get"),
  5768. set: /* @__PURE__ */ __name(function(value) {
  5769. this[kPaused] = !!value;
  5770. }, "set")
  5771. }
  5772. });
  5773. Readable2._fromList = fromList;
  5774. function fromList(n, state) {
  5775. if (state.length === 0) return null;
  5776. let ret;
  5777. if (state.objectMode) ret = state.buffer.shift();
  5778. else if (!n || n >= state.length) {
  5779. if (state.decoder) ret = state.buffer.join("");
  5780. else if (state.buffer.length === 1) ret = state.buffer.first();
  5781. else ret = state.buffer.concat(state.length);
  5782. state.buffer.clear();
  5783. } else {
  5784. ret = state.buffer.consume(n, state.decoder);
  5785. }
  5786. return ret;
  5787. }
  5788. __name(fromList, "fromList");
  5789. function endReadable(stream) {
  5790. const state = stream._readableState;
  5791. debug("endReadable", state.endEmitted);
  5792. if (!state.endEmitted) {
  5793. state.ended = true;
  5794. process.nextTick(endReadableNT, state, stream);
  5795. }
  5796. }
  5797. __name(endReadable, "endReadable");
  5798. function endReadableNT(state, stream) {
  5799. debug("endReadableNT", state.endEmitted, state.length);
  5800. if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) {
  5801. state.endEmitted = true;
  5802. stream.emit("end");
  5803. if (stream.writable && stream.allowHalfOpen === false) {
  5804. process.nextTick(endWritableNT, stream);
  5805. } else if (state.autoDestroy) {
  5806. const wState = stream._writableState;
  5807. const autoDestroy = !wState || wState.autoDestroy && // We don't expect the writable to ever 'finish'
  5808. // if writable is explicitly set to false.
  5809. (wState.finished || wState.writable === false);
  5810. if (autoDestroy) {
  5811. stream.destroy();
  5812. }
  5813. }
  5814. }
  5815. }
  5816. __name(endReadableNT, "endReadableNT");
  5817. function endWritableNT(stream) {
  5818. const writable = stream.writable && !stream.writableEnded && !stream.destroyed;
  5819. if (writable) {
  5820. stream.end();
  5821. }
  5822. }
  5823. __name(endWritableNT, "endWritableNT");
  5824. Readable2.from = function(iterable, opts) {
  5825. return from(Readable2, iterable, opts);
  5826. };
  5827. var webStreamsAdapters;
  5828. function lazyWebStreams() {
  5829. if (webStreamsAdapters === void 0) webStreamsAdapters = {};
  5830. return webStreamsAdapters;
  5831. }
  5832. __name(lazyWebStreams, "lazyWebStreams");
  5833. Readable2.fromWeb = function(readableStream, options) {
  5834. return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options);
  5835. };
  5836. Readable2.toWeb = function(streamReadable, options) {
  5837. return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options);
  5838. };
  5839. Readable2.wrap = function(src, options) {
  5840. var _ref, _src$readableObjectMo;
  5841. return new Readable2({
  5842. objectMode: (_ref = (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== void 0 ? _src$readableObjectMo : src.objectMode) !== null && _ref !== void 0 ? _ref : true,
  5843. ...options,
  5844. destroy: /* @__PURE__ */ __name(function(err, callback) {
  5845. destroyImpl.destroyer(src, err);
  5846. callback(err);
  5847. }, "destroy")
  5848. }).wrap(src);
  5849. };
  5850. }
  5851. });
  5852. // node_modules/readable-stream/lib/internal/streams/writable.js
  5853. var require_writable = __commonJS({
  5854. "node_modules/readable-stream/lib/internal/streams/writable.js"(exports, module) {
  5855. var process = require_browser2();
  5856. var {
  5857. ArrayPrototypeSlice,
  5858. Error: Error2,
  5859. FunctionPrototypeSymbolHasInstance,
  5860. ObjectDefineProperty,
  5861. ObjectDefineProperties,
  5862. ObjectSetPrototypeOf,
  5863. StringPrototypeToLowerCase,
  5864. Symbol: Symbol2,
  5865. SymbolHasInstance
  5866. } = require_primordials();
  5867. module.exports = Writable2;
  5868. Writable2.WritableState = WritableState;
  5869. var { EventEmitter: EE } = require_events();
  5870. var Stream = require_legacy().Stream;
  5871. var { Buffer: Buffer4 } = require_buffer();
  5872. var destroyImpl = require_destroy();
  5873. var { addAbortSignal } = require_add_abort_signal();
  5874. var { getHighWaterMark, getDefaultHighWaterMark } = require_state();
  5875. var {
  5876. ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2,
  5877. ERR_METHOD_NOT_IMPLEMENTED,
  5878. ERR_MULTIPLE_CALLBACK,
  5879. ERR_STREAM_CANNOT_PIPE,
  5880. ERR_STREAM_DESTROYED,
  5881. ERR_STREAM_ALREADY_FINISHED,
  5882. ERR_STREAM_NULL_VALUES,
  5883. ERR_STREAM_WRITE_AFTER_END,
  5884. ERR_UNKNOWN_ENCODING
  5885. } = require_errors().codes;
  5886. var { errorOrDestroy } = destroyImpl;
  5887. ObjectSetPrototypeOf(Writable2.prototype, Stream.prototype);
  5888. ObjectSetPrototypeOf(Writable2, Stream);
  5889. function nop2() {
  5890. }
  5891. __name(nop2, "nop");
  5892. var kOnFinished = Symbol2("kOnFinished");
  5893. function WritableState(options, stream, isDuplex) {
  5894. if (typeof isDuplex !== "boolean") isDuplex = stream instanceof require_duplex();
  5895. this.objectMode = !!(options && options.objectMode);
  5896. if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode);
  5897. this.highWaterMark = options ? getHighWaterMark(this, options, "writableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false);
  5898. this.finalCalled = false;
  5899. this.needDrain = false;
  5900. this.ending = false;
  5901. this.ended = false;
  5902. this.finished = false;
  5903. this.destroyed = false;
  5904. const noDecode = !!(options && options.decodeStrings === false);
  5905. this.decodeStrings = !noDecode;
  5906. this.defaultEncoding = options && options.defaultEncoding || "utf8";
  5907. this.length = 0;
  5908. this.writing = false;
  5909. this.corked = 0;
  5910. this.sync = true;
  5911. this.bufferProcessing = false;
  5912. this.onwrite = onwrite.bind(void 0, stream);
  5913. this.writecb = null;
  5914. this.writelen = 0;
  5915. this.afterWriteTickInfo = null;
  5916. resetBuffer(this);
  5917. this.pendingcb = 0;
  5918. this.constructed = true;
  5919. this.prefinished = false;
  5920. this.errorEmitted = false;
  5921. this.emitClose = !options || options.emitClose !== false;
  5922. this.autoDestroy = !options || options.autoDestroy !== false;
  5923. this.errored = null;
  5924. this.closed = false;
  5925. this.closeEmitted = false;
  5926. this[kOnFinished] = [];
  5927. }
  5928. __name(WritableState, "WritableState");
  5929. function resetBuffer(state) {
  5930. state.buffered = [];
  5931. state.bufferedIndex = 0;
  5932. state.allBuffers = true;
  5933. state.allNoop = true;
  5934. }
  5935. __name(resetBuffer, "resetBuffer");
  5936. WritableState.prototype.getBuffer = /* @__PURE__ */ __name(function getBuffer() {
  5937. return ArrayPrototypeSlice(this.buffered, this.bufferedIndex);
  5938. }, "getBuffer");
  5939. ObjectDefineProperty(WritableState.prototype, "bufferedRequestCount", {
  5940. __proto__: null,
  5941. get: /* @__PURE__ */ __name(function() {
  5942. return this.buffered.length - this.bufferedIndex;
  5943. }, "get")
  5944. });
  5945. function Writable2(options) {
  5946. const isDuplex = this instanceof require_duplex();
  5947. if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable2, this)) return new Writable2(options);
  5948. this._writableState = new WritableState(options, this, isDuplex);
  5949. if (options) {
  5950. if (typeof options.write === "function") this._write = options.write;
  5951. if (typeof options.writev === "function") this._writev = options.writev;
  5952. if (typeof options.destroy === "function") this._destroy = options.destroy;
  5953. if (typeof options.final === "function") this._final = options.final;
  5954. if (typeof options.construct === "function") this._construct = options.construct;
  5955. if (options.signal) addAbortSignal(options.signal, this);
  5956. }
  5957. Stream.call(this, options);
  5958. destroyImpl.construct(this, () => {
  5959. const state = this._writableState;
  5960. if (!state.writing) {
  5961. clearBuffer(this, state);
  5962. }
  5963. finishMaybe(this, state);
  5964. });
  5965. }
  5966. __name(Writable2, "Writable");
  5967. ObjectDefineProperty(Writable2, SymbolHasInstance, {
  5968. __proto__: null,
  5969. value: /* @__PURE__ */ __name(function(object) {
  5970. if (FunctionPrototypeSymbolHasInstance(this, object)) return true;
  5971. if (this !== Writable2) return false;
  5972. return object && object._writableState instanceof WritableState;
  5973. }, "value")
  5974. });
  5975. Writable2.prototype.pipe = function() {
  5976. errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
  5977. };
  5978. function _write(stream, chunk, encoding, cb) {
  5979. const state = stream._writableState;
  5980. if (typeof encoding === "function") {
  5981. cb = encoding;
  5982. encoding = state.defaultEncoding;
  5983. } else {
  5984. if (!encoding) encoding = state.defaultEncoding;
  5985. else if (encoding !== "buffer" && !Buffer4.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding);
  5986. if (typeof cb !== "function") cb = nop2;
  5987. }
  5988. if (chunk === null) {
  5989. throw new ERR_STREAM_NULL_VALUES();
  5990. } else if (!state.objectMode) {
  5991. if (typeof chunk === "string") {
  5992. if (state.decodeStrings !== false) {
  5993. chunk = Buffer4.from(chunk, encoding);
  5994. encoding = "buffer";
  5995. }
  5996. } else if (chunk instanceof Buffer4) {
  5997. encoding = "buffer";
  5998. } else if (Stream._isUint8Array(chunk)) {
  5999. chunk = Stream._uint8ArrayToBuffer(chunk);
  6000. encoding = "buffer";
  6001. } else {
  6002. throw new ERR_INVALID_ARG_TYPE2("chunk", ["string", "Buffer", "Uint8Array"], chunk);
  6003. }
  6004. }
  6005. let err;
  6006. if (state.ending) {
  6007. err = new ERR_STREAM_WRITE_AFTER_END();
  6008. } else if (state.destroyed) {
  6009. err = new ERR_STREAM_DESTROYED("write");
  6010. }
  6011. if (err) {
  6012. process.nextTick(cb, err);
  6013. errorOrDestroy(stream, err, true);
  6014. return err;
  6015. }
  6016. state.pendingcb++;
  6017. return writeOrBuffer(stream, state, chunk, encoding, cb);
  6018. }
  6019. __name(_write, "_write");
  6020. Writable2.prototype.write = function(chunk, encoding, cb) {
  6021. return _write(this, chunk, encoding, cb) === true;
  6022. };
  6023. Writable2.prototype.cork = function() {
  6024. this._writableState.corked++;
  6025. };
  6026. Writable2.prototype.uncork = function() {
  6027. const state = this._writableState;
  6028. if (state.corked) {
  6029. state.corked--;
  6030. if (!state.writing) clearBuffer(this, state);
  6031. }
  6032. };
  6033. Writable2.prototype.setDefaultEncoding = /* @__PURE__ */ __name(function setDefaultEncoding(encoding) {
  6034. if (typeof encoding === "string") encoding = StringPrototypeToLowerCase(encoding);
  6035. if (!Buffer4.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding);
  6036. this._writableState.defaultEncoding = encoding;
  6037. return this;
  6038. }, "setDefaultEncoding");
  6039. function writeOrBuffer(stream, state, chunk, encoding, callback) {
  6040. const len = state.objectMode ? 1 : chunk.length;
  6041. state.length += len;
  6042. const ret = state.length < state.highWaterMark;
  6043. if (!ret) state.needDrain = true;
  6044. if (state.writing || state.corked || state.errored || !state.constructed) {
  6045. state.buffered.push({
  6046. chunk,
  6047. encoding,
  6048. callback
  6049. });
  6050. if (state.allBuffers && encoding !== "buffer") {
  6051. state.allBuffers = false;
  6052. }
  6053. if (state.allNoop && callback !== nop2) {
  6054. state.allNoop = false;
  6055. }
  6056. } else {
  6057. state.writelen = len;
  6058. state.writecb = callback;
  6059. state.writing = true;
  6060. state.sync = true;
  6061. stream._write(chunk, encoding, state.onwrite);
  6062. state.sync = false;
  6063. }
  6064. return ret && !state.errored && !state.destroyed;
  6065. }
  6066. __name(writeOrBuffer, "writeOrBuffer");
  6067. function doWrite(stream, state, writev2, len, chunk, encoding, cb) {
  6068. state.writelen = len;
  6069. state.writecb = cb;
  6070. state.writing = true;
  6071. state.sync = true;
  6072. if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED("write"));
  6073. else if (writev2) stream._writev(chunk, state.onwrite);
  6074. else stream._write(chunk, encoding, state.onwrite);
  6075. state.sync = false;
  6076. }
  6077. __name(doWrite, "doWrite");
  6078. function onwriteError(stream, state, er, cb) {
  6079. --state.pendingcb;
  6080. cb(er);
  6081. errorBuffer(state);
  6082. errorOrDestroy(stream, er);
  6083. }
  6084. __name(onwriteError, "onwriteError");
  6085. function onwrite(stream, er) {
  6086. const state = stream._writableState;
  6087. const sync = state.sync;
  6088. const cb = state.writecb;
  6089. if (typeof cb !== "function") {
  6090. errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK());
  6091. return;
  6092. }
  6093. state.writing = false;
  6094. state.writecb = null;
  6095. state.length -= state.writelen;
  6096. state.writelen = 0;
  6097. if (er) {
  6098. er.stack;
  6099. if (!state.errored) {
  6100. state.errored = er;
  6101. }
  6102. if (stream._readableState && !stream._readableState.errored) {
  6103. stream._readableState.errored = er;
  6104. }
  6105. if (sync) {
  6106. process.nextTick(onwriteError, stream, state, er, cb);
  6107. } else {
  6108. onwriteError(stream, state, er, cb);
  6109. }
  6110. } else {
  6111. if (state.buffered.length > state.bufferedIndex) {
  6112. clearBuffer(stream, state);
  6113. }
  6114. if (sync) {
  6115. if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) {
  6116. state.afterWriteTickInfo.count++;
  6117. } else {
  6118. state.afterWriteTickInfo = {
  6119. count: 1,
  6120. cb,
  6121. stream,
  6122. state
  6123. };
  6124. process.nextTick(afterWriteTick, state.afterWriteTickInfo);
  6125. }
  6126. } else {
  6127. afterWrite(stream, state, 1, cb);
  6128. }
  6129. }
  6130. }
  6131. __name(onwrite, "onwrite");
  6132. function afterWriteTick({ stream, state, count, cb }) {
  6133. state.afterWriteTickInfo = null;
  6134. return afterWrite(stream, state, count, cb);
  6135. }
  6136. __name(afterWriteTick, "afterWriteTick");
  6137. function afterWrite(stream, state, count, cb) {
  6138. const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain;
  6139. if (needDrain) {
  6140. state.needDrain = false;
  6141. stream.emit("drain");
  6142. }
  6143. while (count-- > 0) {
  6144. state.pendingcb--;
  6145. cb();
  6146. }
  6147. if (state.destroyed) {
  6148. errorBuffer(state);
  6149. }
  6150. finishMaybe(stream, state);
  6151. }
  6152. __name(afterWrite, "afterWrite");
  6153. function errorBuffer(state) {
  6154. if (state.writing) {
  6155. return;
  6156. }
  6157. for (let n = state.bufferedIndex; n < state.buffered.length; ++n) {
  6158. var _state$errored;
  6159. const { chunk, callback } = state.buffered[n];
  6160. const len = state.objectMode ? 1 : chunk.length;
  6161. state.length -= len;
  6162. callback(
  6163. (_state$errored = state.errored) !== null && _state$errored !== void 0 ? _state$errored : new ERR_STREAM_DESTROYED("write")
  6164. );
  6165. }
  6166. const onfinishCallbacks = state[kOnFinished].splice(0);
  6167. for (let i = 0; i < onfinishCallbacks.length; i++) {
  6168. var _state$errored2;
  6169. onfinishCallbacks[i](
  6170. (_state$errored2 = state.errored) !== null && _state$errored2 !== void 0 ? _state$errored2 : new ERR_STREAM_DESTROYED("end")
  6171. );
  6172. }
  6173. resetBuffer(state);
  6174. }
  6175. __name(errorBuffer, "errorBuffer");
  6176. function clearBuffer(stream, state) {
  6177. if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) {
  6178. return;
  6179. }
  6180. const { buffered, bufferedIndex, objectMode } = state;
  6181. const bufferedLength = buffered.length - bufferedIndex;
  6182. if (!bufferedLength) {
  6183. return;
  6184. }
  6185. let i = bufferedIndex;
  6186. state.bufferProcessing = true;
  6187. if (bufferedLength > 1 && stream._writev) {
  6188. state.pendingcb -= bufferedLength - 1;
  6189. const callback = state.allNoop ? nop2 : (err) => {
  6190. for (let n = i; n < buffered.length; ++n) {
  6191. buffered[n].callback(err);
  6192. }
  6193. };
  6194. const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i);
  6195. chunks.allBuffers = state.allBuffers;
  6196. doWrite(stream, state, true, state.length, chunks, "", callback);
  6197. resetBuffer(state);
  6198. } else {
  6199. do {
  6200. const { chunk, encoding, callback } = buffered[i];
  6201. buffered[i++] = null;
  6202. const len = objectMode ? 1 : chunk.length;
  6203. doWrite(stream, state, false, len, chunk, encoding, callback);
  6204. } while (i < buffered.length && !state.writing);
  6205. if (i === buffered.length) {
  6206. resetBuffer(state);
  6207. } else if (i > 256) {
  6208. buffered.splice(0, i);
  6209. state.bufferedIndex = 0;
  6210. } else {
  6211. state.bufferedIndex = i;
  6212. }
  6213. }
  6214. state.bufferProcessing = false;
  6215. }
  6216. __name(clearBuffer, "clearBuffer");
  6217. Writable2.prototype._write = function(chunk, encoding, cb) {
  6218. if (this._writev) {
  6219. this._writev(
  6220. [
  6221. {
  6222. chunk,
  6223. encoding
  6224. }
  6225. ],
  6226. cb
  6227. );
  6228. } else {
  6229. throw new ERR_METHOD_NOT_IMPLEMENTED("_write()");
  6230. }
  6231. };
  6232. Writable2.prototype._writev = null;
  6233. Writable2.prototype.end = function(chunk, encoding, cb) {
  6234. const state = this._writableState;
  6235. if (typeof chunk === "function") {
  6236. cb = chunk;
  6237. chunk = null;
  6238. encoding = null;
  6239. } else if (typeof encoding === "function") {
  6240. cb = encoding;
  6241. encoding = null;
  6242. }
  6243. let err;
  6244. if (chunk !== null && chunk !== void 0) {
  6245. const ret = _write(this, chunk, encoding);
  6246. if (ret instanceof Error2) {
  6247. err = ret;
  6248. }
  6249. }
  6250. if (state.corked) {
  6251. state.corked = 1;
  6252. this.uncork();
  6253. }
  6254. if (err) {
  6255. } else if (!state.errored && !state.ending) {
  6256. state.ending = true;
  6257. finishMaybe(this, state, true);
  6258. state.ended = true;
  6259. } else if (state.finished) {
  6260. err = new ERR_STREAM_ALREADY_FINISHED("end");
  6261. } else if (state.destroyed) {
  6262. err = new ERR_STREAM_DESTROYED("end");
  6263. }
  6264. if (typeof cb === "function") {
  6265. if (err || state.finished) {
  6266. process.nextTick(cb, err);
  6267. } else {
  6268. state[kOnFinished].push(cb);
  6269. }
  6270. }
  6271. return this;
  6272. };
  6273. function needFinish(state) {
  6274. return state.ending && !state.destroyed && state.constructed && state.length === 0 && !state.errored && state.buffered.length === 0 && !state.finished && !state.writing && !state.errorEmitted && !state.closeEmitted;
  6275. }
  6276. __name(needFinish, "needFinish");
  6277. function callFinal(stream, state) {
  6278. let called = false;
  6279. function onFinish(err) {
  6280. if (called) {
  6281. errorOrDestroy(stream, err !== null && err !== void 0 ? err : ERR_MULTIPLE_CALLBACK());
  6282. return;
  6283. }
  6284. called = true;
  6285. state.pendingcb--;
  6286. if (err) {
  6287. const onfinishCallbacks = state[kOnFinished].splice(0);
  6288. for (let i = 0; i < onfinishCallbacks.length; i++) {
  6289. onfinishCallbacks[i](err);
  6290. }
  6291. errorOrDestroy(stream, err, state.sync);
  6292. } else if (needFinish(state)) {
  6293. state.prefinished = true;
  6294. stream.emit("prefinish");
  6295. state.pendingcb++;
  6296. process.nextTick(finish, stream, state);
  6297. }
  6298. }
  6299. __name(onFinish, "onFinish");
  6300. state.sync = true;
  6301. state.pendingcb++;
  6302. try {
  6303. stream._final(onFinish);
  6304. } catch (err) {
  6305. onFinish(err);
  6306. }
  6307. state.sync = false;
  6308. }
  6309. __name(callFinal, "callFinal");
  6310. function prefinish(stream, state) {
  6311. if (!state.prefinished && !state.finalCalled) {
  6312. if (typeof stream._final === "function" && !state.destroyed) {
  6313. state.finalCalled = true;
  6314. callFinal(stream, state);
  6315. } else {
  6316. state.prefinished = true;
  6317. stream.emit("prefinish");
  6318. }
  6319. }
  6320. }
  6321. __name(prefinish, "prefinish");
  6322. function finishMaybe(stream, state, sync) {
  6323. if (needFinish(state)) {
  6324. prefinish(stream, state);
  6325. if (state.pendingcb === 0) {
  6326. if (sync) {
  6327. state.pendingcb++;
  6328. process.nextTick(
  6329. (stream2, state2) => {
  6330. if (needFinish(state2)) {
  6331. finish(stream2, state2);
  6332. } else {
  6333. state2.pendingcb--;
  6334. }
  6335. },
  6336. stream,
  6337. state
  6338. );
  6339. } else if (needFinish(state)) {
  6340. state.pendingcb++;
  6341. finish(stream, state);
  6342. }
  6343. }
  6344. }
  6345. }
  6346. __name(finishMaybe, "finishMaybe");
  6347. function finish(stream, state) {
  6348. state.pendingcb--;
  6349. state.finished = true;
  6350. const onfinishCallbacks = state[kOnFinished].splice(0);
  6351. for (let i = 0; i < onfinishCallbacks.length; i++) {
  6352. onfinishCallbacks[i]();
  6353. }
  6354. stream.emit("finish");
  6355. if (state.autoDestroy) {
  6356. const rState = stream._readableState;
  6357. const autoDestroy = !rState || rState.autoDestroy && // We don't expect the readable to ever 'end'
  6358. // if readable is explicitly set to false.
  6359. (rState.endEmitted || rState.readable === false);
  6360. if (autoDestroy) {
  6361. stream.destroy();
  6362. }
  6363. }
  6364. }
  6365. __name(finish, "finish");
  6366. ObjectDefineProperties(Writable2.prototype, {
  6367. closed: {
  6368. __proto__: null,
  6369. get: /* @__PURE__ */ __name(function() {
  6370. return this._writableState ? this._writableState.closed : false;
  6371. }, "get")
  6372. },
  6373. destroyed: {
  6374. __proto__: null,
  6375. get: /* @__PURE__ */ __name(function() {
  6376. return this._writableState ? this._writableState.destroyed : false;
  6377. }, "get"),
  6378. set: /* @__PURE__ */ __name(function(value) {
  6379. if (this._writableState) {
  6380. this._writableState.destroyed = value;
  6381. }
  6382. }, "set")
  6383. },
  6384. writable: {
  6385. __proto__: null,
  6386. get: /* @__PURE__ */ __name(function() {
  6387. const w = this._writableState;
  6388. return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended;
  6389. }, "get"),
  6390. set: /* @__PURE__ */ __name(function(val) {
  6391. if (this._writableState) {
  6392. this._writableState.writable = !!val;
  6393. }
  6394. }, "set")
  6395. },
  6396. writableFinished: {
  6397. __proto__: null,
  6398. get: /* @__PURE__ */ __name(function() {
  6399. return this._writableState ? this._writableState.finished : false;
  6400. }, "get")
  6401. },
  6402. writableObjectMode: {
  6403. __proto__: null,
  6404. get: /* @__PURE__ */ __name(function() {
  6405. return this._writableState ? this._writableState.objectMode : false;
  6406. }, "get")
  6407. },
  6408. writableBuffer: {
  6409. __proto__: null,
  6410. get: /* @__PURE__ */ __name(function() {
  6411. return this._writableState && this._writableState.getBuffer();
  6412. }, "get")
  6413. },
  6414. writableEnded: {
  6415. __proto__: null,
  6416. get: /* @__PURE__ */ __name(function() {
  6417. return this._writableState ? this._writableState.ending : false;
  6418. }, "get")
  6419. },
  6420. writableNeedDrain: {
  6421. __proto__: null,
  6422. get: /* @__PURE__ */ __name(function() {
  6423. const wState = this._writableState;
  6424. if (!wState) return false;
  6425. return !wState.destroyed && !wState.ending && wState.needDrain;
  6426. }, "get")
  6427. },
  6428. writableHighWaterMark: {
  6429. __proto__: null,
  6430. get: /* @__PURE__ */ __name(function() {
  6431. return this._writableState && this._writableState.highWaterMark;
  6432. }, "get")
  6433. },
  6434. writableCorked: {
  6435. __proto__: null,
  6436. get: /* @__PURE__ */ __name(function() {
  6437. return this._writableState ? this._writableState.corked : 0;
  6438. }, "get")
  6439. },
  6440. writableLength: {
  6441. __proto__: null,
  6442. get: /* @__PURE__ */ __name(function() {
  6443. return this._writableState && this._writableState.length;
  6444. }, "get")
  6445. },
  6446. errored: {
  6447. __proto__: null,
  6448. enumerable: false,
  6449. get: /* @__PURE__ */ __name(function() {
  6450. return this._writableState ? this._writableState.errored : null;
  6451. }, "get")
  6452. },
  6453. writableAborted: {
  6454. __proto__: null,
  6455. enumerable: false,
  6456. get: /* @__PURE__ */ __name(function() {
  6457. return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished);
  6458. }, "get")
  6459. }
  6460. });
  6461. var destroy = destroyImpl.destroy;
  6462. Writable2.prototype.destroy = function(err, cb) {
  6463. const state = this._writableState;
  6464. if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) {
  6465. process.nextTick(errorBuffer, state);
  6466. }
  6467. destroy.call(this, err, cb);
  6468. return this;
  6469. };
  6470. Writable2.prototype._undestroy = destroyImpl.undestroy;
  6471. Writable2.prototype._destroy = function(err, cb) {
  6472. cb(err);
  6473. };
  6474. Writable2.prototype[EE.captureRejectionSymbol] = function(err) {
  6475. this.destroy(err);
  6476. };
  6477. var webStreamsAdapters;
  6478. function lazyWebStreams() {
  6479. if (webStreamsAdapters === void 0) webStreamsAdapters = {};
  6480. return webStreamsAdapters;
  6481. }
  6482. __name(lazyWebStreams, "lazyWebStreams");
  6483. Writable2.fromWeb = function(writableStream, options) {
  6484. return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options);
  6485. };
  6486. Writable2.toWeb = function(streamWritable) {
  6487. return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable);
  6488. };
  6489. }
  6490. });
  6491. // node_modules/readable-stream/lib/internal/streams/duplexify.js
  6492. var require_duplexify = __commonJS({
  6493. "node_modules/readable-stream/lib/internal/streams/duplexify.js"(exports, module) {
  6494. var process = require_browser2();
  6495. var bufferModule = require_buffer();
  6496. var {
  6497. isReadable: isReadable2,
  6498. isWritable,
  6499. isIterable,
  6500. isNodeStream,
  6501. isReadableNodeStream,
  6502. isWritableNodeStream,
  6503. isDuplexNodeStream,
  6504. isReadableStream,
  6505. isWritableStream
  6506. } = require_utils();
  6507. var eos = require_end_of_stream();
  6508. var {
  6509. AbortError,
  6510. codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_INVALID_RETURN_VALUE }
  6511. } = require_errors();
  6512. var { destroyer } = require_destroy();
  6513. var Duplex = require_duplex();
  6514. var Readable2 = require_readable();
  6515. var Writable2 = require_writable();
  6516. var { createDeferredPromise } = require_util();
  6517. var from = require_from();
  6518. var Blob2 = globalThis.Blob || bufferModule.Blob;
  6519. var isBlob = typeof Blob2 !== "undefined" ? /* @__PURE__ */ __name(function isBlob2(b) {
  6520. return b instanceof Blob2;
  6521. }, "isBlob") : /* @__PURE__ */ __name(function isBlob2(b) {
  6522. return false;
  6523. }, "isBlob");
  6524. var AbortController = globalThis.AbortController || require_browser().AbortController;
  6525. var { FunctionPrototypeCall } = require_primordials();
  6526. var Duplexify = class extends Duplex {
  6527. static {
  6528. __name(this, "Duplexify");
  6529. }
  6530. constructor(options) {
  6531. super(options);
  6532. if ((options === null || options === void 0 ? void 0 : options.readable) === false) {
  6533. this._readableState.readable = false;
  6534. this._readableState.ended = true;
  6535. this._readableState.endEmitted = true;
  6536. }
  6537. if ((options === null || options === void 0 ? void 0 : options.writable) === false) {
  6538. this._writableState.writable = false;
  6539. this._writableState.ending = true;
  6540. this._writableState.ended = true;
  6541. this._writableState.finished = true;
  6542. }
  6543. }
  6544. };
  6545. module.exports = /* @__PURE__ */ __name(function duplexify(body, name) {
  6546. if (isDuplexNodeStream(body)) {
  6547. return body;
  6548. }
  6549. if (isReadableNodeStream(body)) {
  6550. return _duplexify({
  6551. readable: body
  6552. });
  6553. }
  6554. if (isWritableNodeStream(body)) {
  6555. return _duplexify({
  6556. writable: body
  6557. });
  6558. }
  6559. if (isNodeStream(body)) {
  6560. return _duplexify({
  6561. writable: false,
  6562. readable: false
  6563. });
  6564. }
  6565. if (isReadableStream(body)) {
  6566. return _duplexify({
  6567. readable: Readable2.fromWeb(body)
  6568. });
  6569. }
  6570. if (isWritableStream(body)) {
  6571. return _duplexify({
  6572. writable: Writable2.fromWeb(body)
  6573. });
  6574. }
  6575. if (typeof body === "function") {
  6576. const { value, write: write2, final, destroy } = fromAsyncGen(body);
  6577. if (isIterable(value)) {
  6578. return from(Duplexify, value, {
  6579. // TODO (ronag): highWaterMark?
  6580. objectMode: true,
  6581. write: write2,
  6582. final,
  6583. destroy
  6584. });
  6585. }
  6586. const then2 = value === null || value === void 0 ? void 0 : value.then;
  6587. if (typeof then2 === "function") {
  6588. let d;
  6589. const promise = FunctionPrototypeCall(
  6590. then2,
  6591. value,
  6592. (val) => {
  6593. if (val != null) {
  6594. throw new ERR_INVALID_RETURN_VALUE("nully", "body", val);
  6595. }
  6596. },
  6597. (err) => {
  6598. destroyer(d, err);
  6599. }
  6600. );
  6601. return d = new Duplexify({
  6602. // TODO (ronag): highWaterMark?
  6603. objectMode: true,
  6604. readable: false,
  6605. write: write2,
  6606. final: /* @__PURE__ */ __name(function(cb) {
  6607. final(async () => {
  6608. try {
  6609. await promise;
  6610. process.nextTick(cb, null);
  6611. } catch (err) {
  6612. process.nextTick(cb, err);
  6613. }
  6614. });
  6615. }, "final"),
  6616. destroy
  6617. });
  6618. }
  6619. throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or AsyncFunction", name, value);
  6620. }
  6621. if (isBlob(body)) {
  6622. return duplexify(body.arrayBuffer());
  6623. }
  6624. if (isIterable(body)) {
  6625. return from(Duplexify, body, {
  6626. // TODO (ronag): highWaterMark?
  6627. objectMode: true,
  6628. writable: false
  6629. });
  6630. }
  6631. if (isReadableStream(body === null || body === void 0 ? void 0 : body.readable) && isWritableStream(body === null || body === void 0 ? void 0 : body.writable)) {
  6632. return Duplexify.fromWeb(body);
  6633. }
  6634. if (typeof (body === null || body === void 0 ? void 0 : body.writable) === "object" || typeof (body === null || body === void 0 ? void 0 : body.readable) === "object") {
  6635. const readable = body !== null && body !== void 0 && body.readable ? isReadableNodeStream(body === null || body === void 0 ? void 0 : body.readable) ? body === null || body === void 0 ? void 0 : body.readable : duplexify(body.readable) : void 0;
  6636. const writable = body !== null && body !== void 0 && body.writable ? isWritableNodeStream(body === null || body === void 0 ? void 0 : body.writable) ? body === null || body === void 0 ? void 0 : body.writable : duplexify(body.writable) : void 0;
  6637. return _duplexify({
  6638. readable,
  6639. writable
  6640. });
  6641. }
  6642. const then = body === null || body === void 0 ? void 0 : body.then;
  6643. if (typeof then === "function") {
  6644. let d;
  6645. FunctionPrototypeCall(
  6646. then,
  6647. body,
  6648. (val) => {
  6649. if (val != null) {
  6650. d.push(val);
  6651. }
  6652. d.push(null);
  6653. },
  6654. (err) => {
  6655. destroyer(d, err);
  6656. }
  6657. );
  6658. return d = new Duplexify({
  6659. objectMode: true,
  6660. writable: false,
  6661. read: /* @__PURE__ */ __name(function() {
  6662. }, "read")
  6663. });
  6664. }
  6665. throw new ERR_INVALID_ARG_TYPE2(
  6666. name,
  6667. [
  6668. "Blob",
  6669. "ReadableStream",
  6670. "WritableStream",
  6671. "Stream",
  6672. "Iterable",
  6673. "AsyncIterable",
  6674. "Function",
  6675. "{ readable, writable } pair",
  6676. "Promise"
  6677. ],
  6678. body
  6679. );
  6680. }, "duplexify");
  6681. function fromAsyncGen(fn) {
  6682. let { promise, resolve: resolve2 } = createDeferredPromise();
  6683. const ac = new AbortController();
  6684. const signal = ac.signal;
  6685. const value = fn(
  6686. async function* () {
  6687. while (true) {
  6688. const _promise = promise;
  6689. promise = null;
  6690. const { chunk, done, cb } = await _promise;
  6691. process.nextTick(cb);
  6692. if (done) return;
  6693. if (signal.aborted)
  6694. throw new AbortError(void 0, {
  6695. cause: signal.reason
  6696. });
  6697. ({ promise, resolve: resolve2 } = createDeferredPromise());
  6698. yield chunk;
  6699. }
  6700. }(),
  6701. {
  6702. signal
  6703. }
  6704. );
  6705. return {
  6706. value,
  6707. write: /* @__PURE__ */ __name(function(chunk, encoding, cb) {
  6708. const _resolve = resolve2;
  6709. resolve2 = null;
  6710. _resolve({
  6711. chunk,
  6712. done: false,
  6713. cb
  6714. });
  6715. }, "write"),
  6716. final: /* @__PURE__ */ __name(function(cb) {
  6717. const _resolve = resolve2;
  6718. resolve2 = null;
  6719. _resolve({
  6720. done: true,
  6721. cb
  6722. });
  6723. }, "final"),
  6724. destroy: /* @__PURE__ */ __name(function(err, cb) {
  6725. ac.abort();
  6726. cb(err);
  6727. }, "destroy")
  6728. };
  6729. }
  6730. __name(fromAsyncGen, "fromAsyncGen");
  6731. function _duplexify(pair) {
  6732. const r = pair.readable && typeof pair.readable.read !== "function" ? Readable2.wrap(pair.readable) : pair.readable;
  6733. const w = pair.writable;
  6734. let readable = !!isReadable2(r);
  6735. let writable = !!isWritable(w);
  6736. let ondrain;
  6737. let onfinish;
  6738. let onreadable;
  6739. let onclose;
  6740. let d;
  6741. function onfinished(err) {
  6742. const cb = onclose;
  6743. onclose = null;
  6744. if (cb) {
  6745. cb(err);
  6746. } else if (err) {
  6747. d.destroy(err);
  6748. }
  6749. }
  6750. __name(onfinished, "onfinished");
  6751. d = new Duplexify({
  6752. // TODO (ronag): highWaterMark?
  6753. readableObjectMode: !!(r !== null && r !== void 0 && r.readableObjectMode),
  6754. writableObjectMode: !!(w !== null && w !== void 0 && w.writableObjectMode),
  6755. readable,
  6756. writable
  6757. });
  6758. if (writable) {
  6759. eos(w, (err) => {
  6760. writable = false;
  6761. if (err) {
  6762. destroyer(r, err);
  6763. }
  6764. onfinished(err);
  6765. });
  6766. d._write = function(chunk, encoding, callback) {
  6767. if (w.write(chunk, encoding)) {
  6768. callback();
  6769. } else {
  6770. ondrain = callback;
  6771. }
  6772. };
  6773. d._final = function(callback) {
  6774. w.end();
  6775. onfinish = callback;
  6776. };
  6777. w.on("drain", function() {
  6778. if (ondrain) {
  6779. const cb = ondrain;
  6780. ondrain = null;
  6781. cb();
  6782. }
  6783. });
  6784. w.on("finish", function() {
  6785. if (onfinish) {
  6786. const cb = onfinish;
  6787. onfinish = null;
  6788. cb();
  6789. }
  6790. });
  6791. }
  6792. if (readable) {
  6793. eos(r, (err) => {
  6794. readable = false;
  6795. if (err) {
  6796. destroyer(r, err);
  6797. }
  6798. onfinished(err);
  6799. });
  6800. r.on("readable", function() {
  6801. if (onreadable) {
  6802. const cb = onreadable;
  6803. onreadable = null;
  6804. cb();
  6805. }
  6806. });
  6807. r.on("end", function() {
  6808. d.push(null);
  6809. });
  6810. d._read = function() {
  6811. while (true) {
  6812. const buf = r.read();
  6813. if (buf === null) {
  6814. onreadable = d._read;
  6815. return;
  6816. }
  6817. if (!d.push(buf)) {
  6818. return;
  6819. }
  6820. }
  6821. };
  6822. }
  6823. d._destroy = function(err, callback) {
  6824. if (!err && onclose !== null) {
  6825. err = new AbortError();
  6826. }
  6827. onreadable = null;
  6828. ondrain = null;
  6829. onfinish = null;
  6830. if (onclose === null) {
  6831. callback(err);
  6832. } else {
  6833. onclose = callback;
  6834. destroyer(w, err);
  6835. destroyer(r, err);
  6836. }
  6837. };
  6838. return d;
  6839. }
  6840. __name(_duplexify, "_duplexify");
  6841. }
  6842. });
  6843. // node_modules/readable-stream/lib/internal/streams/duplex.js
  6844. var require_duplex = __commonJS({
  6845. "node_modules/readable-stream/lib/internal/streams/duplex.js"(exports, module) {
  6846. "use strict";
  6847. var {
  6848. ObjectDefineProperties,
  6849. ObjectGetOwnPropertyDescriptor,
  6850. ObjectKeys,
  6851. ObjectSetPrototypeOf
  6852. } = require_primordials();
  6853. module.exports = Duplex;
  6854. var Readable2 = require_readable();
  6855. var Writable2 = require_writable();
  6856. ObjectSetPrototypeOf(Duplex.prototype, Readable2.prototype);
  6857. ObjectSetPrototypeOf(Duplex, Readable2);
  6858. {
  6859. const keys = ObjectKeys(Writable2.prototype);
  6860. for (let i = 0; i < keys.length; i++) {
  6861. const method = keys[i];
  6862. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable2.prototype[method];
  6863. }
  6864. }
  6865. function Duplex(options) {
  6866. if (!(this instanceof Duplex)) return new Duplex(options);
  6867. Readable2.call(this, options);
  6868. Writable2.call(this, options);
  6869. if (options) {
  6870. this.allowHalfOpen = options.allowHalfOpen !== false;
  6871. if (options.readable === false) {
  6872. this._readableState.readable = false;
  6873. this._readableState.ended = true;
  6874. this._readableState.endEmitted = true;
  6875. }
  6876. if (options.writable === false) {
  6877. this._writableState.writable = false;
  6878. this._writableState.ending = true;
  6879. this._writableState.ended = true;
  6880. this._writableState.finished = true;
  6881. }
  6882. } else {
  6883. this.allowHalfOpen = true;
  6884. }
  6885. }
  6886. __name(Duplex, "Duplex");
  6887. ObjectDefineProperties(Duplex.prototype, {
  6888. writable: {
  6889. __proto__: null,
  6890. ...ObjectGetOwnPropertyDescriptor(Writable2.prototype, "writable")
  6891. },
  6892. writableHighWaterMark: {
  6893. __proto__: null,
  6894. ...ObjectGetOwnPropertyDescriptor(Writable2.prototype, "writableHighWaterMark")
  6895. },
  6896. writableObjectMode: {
  6897. __proto__: null,
  6898. ...ObjectGetOwnPropertyDescriptor(Writable2.prototype, "writableObjectMode")
  6899. },
  6900. writableBuffer: {
  6901. __proto__: null,
  6902. ...ObjectGetOwnPropertyDescriptor(Writable2.prototype, "writableBuffer")
  6903. },
  6904. writableLength: {
  6905. __proto__: null,
  6906. ...ObjectGetOwnPropertyDescriptor(Writable2.prototype, "writableLength")
  6907. },
  6908. writableFinished: {
  6909. __proto__: null,
  6910. ...ObjectGetOwnPropertyDescriptor(Writable2.prototype, "writableFinished")
  6911. },
  6912. writableCorked: {
  6913. __proto__: null,
  6914. ...ObjectGetOwnPropertyDescriptor(Writable2.prototype, "writableCorked")
  6915. },
  6916. writableEnded: {
  6917. __proto__: null,
  6918. ...ObjectGetOwnPropertyDescriptor(Writable2.prototype, "writableEnded")
  6919. },
  6920. writableNeedDrain: {
  6921. __proto__: null,
  6922. ...ObjectGetOwnPropertyDescriptor(Writable2.prototype, "writableNeedDrain")
  6923. },
  6924. destroyed: {
  6925. __proto__: null,
  6926. get: /* @__PURE__ */ __name(function() {
  6927. if (this._readableState === void 0 || this._writableState === void 0) {
  6928. return false;
  6929. }
  6930. return this._readableState.destroyed && this._writableState.destroyed;
  6931. }, "get"),
  6932. set: /* @__PURE__ */ __name(function(value) {
  6933. if (this._readableState && this._writableState) {
  6934. this._readableState.destroyed = value;
  6935. this._writableState.destroyed = value;
  6936. }
  6937. }, "set")
  6938. }
  6939. });
  6940. var webStreamsAdapters;
  6941. function lazyWebStreams() {
  6942. if (webStreamsAdapters === void 0) webStreamsAdapters = {};
  6943. return webStreamsAdapters;
  6944. }
  6945. __name(lazyWebStreams, "lazyWebStreams");
  6946. Duplex.fromWeb = function(pair, options) {
  6947. return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options);
  6948. };
  6949. Duplex.toWeb = function(duplex) {
  6950. return lazyWebStreams().newReadableWritablePairFromDuplex(duplex);
  6951. };
  6952. var duplexify;
  6953. Duplex.from = function(body) {
  6954. if (!duplexify) {
  6955. duplexify = require_duplexify();
  6956. }
  6957. return duplexify(body, "body");
  6958. };
  6959. }
  6960. });
  6961. // node_modules/readable-stream/lib/internal/streams/transform.js
  6962. var require_transform = __commonJS({
  6963. "node_modules/readable-stream/lib/internal/streams/transform.js"(exports, module) {
  6964. "use strict";
  6965. var { ObjectSetPrototypeOf, Symbol: Symbol2 } = require_primordials();
  6966. module.exports = Transform;
  6967. var { ERR_METHOD_NOT_IMPLEMENTED } = require_errors().codes;
  6968. var Duplex = require_duplex();
  6969. var { getHighWaterMark } = require_state();
  6970. ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype);
  6971. ObjectSetPrototypeOf(Transform, Duplex);
  6972. var kCallback = Symbol2("kCallback");
  6973. function Transform(options) {
  6974. if (!(this instanceof Transform)) return new Transform(options);
  6975. const readableHighWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", true) : null;
  6976. if (readableHighWaterMark === 0) {
  6977. options = {
  6978. ...options,
  6979. highWaterMark: null,
  6980. readableHighWaterMark,
  6981. // TODO (ronag): 0 is not optimal since we have
  6982. // a "bug" where we check needDrain before calling _write and not after.
  6983. // Refs: https://github.com/nodejs/node/pull/32887
  6984. // Refs: https://github.com/nodejs/node/pull/35941
  6985. writableHighWaterMark: options.writableHighWaterMark || 0
  6986. };
  6987. }
  6988. Duplex.call(this, options);
  6989. this._readableState.sync = false;
  6990. this[kCallback] = null;
  6991. if (options) {
  6992. if (typeof options.transform === "function") this._transform = options.transform;
  6993. if (typeof options.flush === "function") this._flush = options.flush;
  6994. }
  6995. this.on("prefinish", prefinish);
  6996. }
  6997. __name(Transform, "Transform");
  6998. function final(cb) {
  6999. if (typeof this._flush === "function" && !this.destroyed) {
  7000. this._flush((er, data) => {
  7001. if (er) {
  7002. if (cb) {
  7003. cb(er);
  7004. } else {
  7005. this.destroy(er);
  7006. }
  7007. return;
  7008. }
  7009. if (data != null) {
  7010. this.push(data);
  7011. }
  7012. this.push(null);
  7013. if (cb) {
  7014. cb();
  7015. }
  7016. });
  7017. } else {
  7018. this.push(null);
  7019. if (cb) {
  7020. cb();
  7021. }
  7022. }
  7023. }
  7024. __name(final, "final");
  7025. function prefinish() {
  7026. if (this._final !== final) {
  7027. final.call(this);
  7028. }
  7029. }
  7030. __name(prefinish, "prefinish");
  7031. Transform.prototype._final = final;
  7032. Transform.prototype._transform = function(chunk, encoding, callback) {
  7033. throw new ERR_METHOD_NOT_IMPLEMENTED("_transform()");
  7034. };
  7035. Transform.prototype._write = function(chunk, encoding, callback) {
  7036. const rState = this._readableState;
  7037. const wState = this._writableState;
  7038. const length = rState.length;
  7039. this._transform(chunk, encoding, (err, val) => {
  7040. if (err) {
  7041. callback(err);
  7042. return;
  7043. }
  7044. if (val != null) {
  7045. this.push(val);
  7046. }
  7047. if (wState.ended || // Backwards compat.
  7048. length === rState.length || // Backwards compat.
  7049. rState.length < rState.highWaterMark) {
  7050. callback();
  7051. } else {
  7052. this[kCallback] = callback;
  7053. }
  7054. });
  7055. };
  7056. Transform.prototype._read = function() {
  7057. if (this[kCallback]) {
  7058. const callback = this[kCallback];
  7059. this[kCallback] = null;
  7060. callback();
  7061. }
  7062. };
  7063. }
  7064. });
  7065. // node_modules/readable-stream/lib/internal/streams/passthrough.js
  7066. var require_passthrough = __commonJS({
  7067. "node_modules/readable-stream/lib/internal/streams/passthrough.js"(exports, module) {
  7068. "use strict";
  7069. var { ObjectSetPrototypeOf } = require_primordials();
  7070. module.exports = PassThrough;
  7071. var Transform = require_transform();
  7072. ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype);
  7073. ObjectSetPrototypeOf(PassThrough, Transform);
  7074. function PassThrough(options) {
  7075. if (!(this instanceof PassThrough)) return new PassThrough(options);
  7076. Transform.call(this, options);
  7077. }
  7078. __name(PassThrough, "PassThrough");
  7079. PassThrough.prototype._transform = function(chunk, encoding, cb) {
  7080. cb(null, chunk);
  7081. };
  7082. }
  7083. });
  7084. // node_modules/readable-stream/lib/internal/streams/pipeline.js
  7085. var require_pipeline = __commonJS({
  7086. "node_modules/readable-stream/lib/internal/streams/pipeline.js"(exports, module) {
  7087. var process = require_browser2();
  7088. var { ArrayIsArray, Promise: Promise2, SymbolAsyncIterator, SymbolDispose } = require_primordials();
  7089. var eos = require_end_of_stream();
  7090. var { once } = require_util();
  7091. var destroyImpl = require_destroy();
  7092. var Duplex = require_duplex();
  7093. var {
  7094. aggregateTwoErrors,
  7095. codes: {
  7096. ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2,
  7097. ERR_INVALID_RETURN_VALUE,
  7098. ERR_MISSING_ARGS,
  7099. ERR_STREAM_DESTROYED,
  7100. ERR_STREAM_PREMATURE_CLOSE
  7101. },
  7102. AbortError
  7103. } = require_errors();
  7104. var { validateFunction, validateAbortSignal } = require_validators();
  7105. var {
  7106. isIterable,
  7107. isReadable: isReadable2,
  7108. isReadableNodeStream,
  7109. isNodeStream,
  7110. isTransformStream,
  7111. isWebStream,
  7112. isReadableStream,
  7113. isReadableFinished
  7114. } = require_utils();
  7115. var AbortController = globalThis.AbortController || require_browser().AbortController;
  7116. var PassThrough;
  7117. var Readable2;
  7118. var addAbortListener;
  7119. function destroyer(stream, reading, writing) {
  7120. let finished = false;
  7121. stream.on("close", () => {
  7122. finished = true;
  7123. });
  7124. const cleanup = eos(
  7125. stream,
  7126. {
  7127. readable: reading,
  7128. writable: writing
  7129. },
  7130. (err) => {
  7131. finished = !err;
  7132. }
  7133. );
  7134. return {
  7135. destroy: /* @__PURE__ */ __name((err) => {
  7136. if (finished) return;
  7137. finished = true;
  7138. destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED("pipe"));
  7139. }, "destroy"),
  7140. cleanup
  7141. };
  7142. }
  7143. __name(destroyer, "destroyer");
  7144. function popCallback(streams) {
  7145. validateFunction(streams[streams.length - 1], "streams[stream.length - 1]");
  7146. return streams.pop();
  7147. }
  7148. __name(popCallback, "popCallback");
  7149. function makeAsyncIterable(val) {
  7150. if (isIterable(val)) {
  7151. return val;
  7152. } else if (isReadableNodeStream(val)) {
  7153. return fromReadable(val);
  7154. }
  7155. throw new ERR_INVALID_ARG_TYPE2("val", ["Readable", "Iterable", "AsyncIterable"], val);
  7156. }
  7157. __name(makeAsyncIterable, "makeAsyncIterable");
  7158. async function* fromReadable(val) {
  7159. if (!Readable2) {
  7160. Readable2 = require_readable();
  7161. }
  7162. yield* Readable2.prototype[SymbolAsyncIterator].call(val);
  7163. }
  7164. __name(fromReadable, "fromReadable");
  7165. async function pumpToNode(iterable, writable, finish, { end }) {
  7166. let error;
  7167. let onresolve = null;
  7168. const resume = /* @__PURE__ */ __name((err) => {
  7169. if (err) {
  7170. error = err;
  7171. }
  7172. if (onresolve) {
  7173. const callback = onresolve;
  7174. onresolve = null;
  7175. callback();
  7176. }
  7177. }, "resume");
  7178. const wait = /* @__PURE__ */ __name(() => new Promise2((resolve2, reject) => {
  7179. if (error) {
  7180. reject(error);
  7181. } else {
  7182. onresolve = /* @__PURE__ */ __name(() => {
  7183. if (error) {
  7184. reject(error);
  7185. } else {
  7186. resolve2();
  7187. }
  7188. }, "onresolve");
  7189. }
  7190. }), "wait");
  7191. writable.on("drain", resume);
  7192. const cleanup = eos(
  7193. writable,
  7194. {
  7195. readable: false
  7196. },
  7197. resume
  7198. );
  7199. try {
  7200. if (writable.writableNeedDrain) {
  7201. await wait();
  7202. }
  7203. for await (const chunk of iterable) {
  7204. if (!writable.write(chunk)) {
  7205. await wait();
  7206. }
  7207. }
  7208. if (end) {
  7209. writable.end();
  7210. await wait();
  7211. }
  7212. finish();
  7213. } catch (err) {
  7214. finish(error !== err ? aggregateTwoErrors(error, err) : err);
  7215. } finally {
  7216. cleanup();
  7217. writable.off("drain", resume);
  7218. }
  7219. }
  7220. __name(pumpToNode, "pumpToNode");
  7221. async function pumpToWeb(readable, writable, finish, { end }) {
  7222. if (isTransformStream(writable)) {
  7223. writable = writable.writable;
  7224. }
  7225. const writer = writable.getWriter();
  7226. try {
  7227. for await (const chunk of readable) {
  7228. await writer.ready;
  7229. writer.write(chunk).catch(() => {
  7230. });
  7231. }
  7232. await writer.ready;
  7233. if (end) {
  7234. await writer.close();
  7235. }
  7236. finish();
  7237. } catch (err) {
  7238. try {
  7239. await writer.abort(err);
  7240. finish(err);
  7241. } catch (err2) {
  7242. finish(err2);
  7243. }
  7244. }
  7245. }
  7246. __name(pumpToWeb, "pumpToWeb");
  7247. function pipeline(...streams) {
  7248. return pipelineImpl(streams, once(popCallback(streams)));
  7249. }
  7250. __name(pipeline, "pipeline");
  7251. function pipelineImpl(streams, callback, opts) {
  7252. if (streams.length === 1 && ArrayIsArray(streams[0])) {
  7253. streams = streams[0];
  7254. }
  7255. if (streams.length < 2) {
  7256. throw new ERR_MISSING_ARGS("streams");
  7257. }
  7258. const ac = new AbortController();
  7259. const signal = ac.signal;
  7260. const outerSignal = opts === null || opts === void 0 ? void 0 : opts.signal;
  7261. const lastStreamCleanup = [];
  7262. validateAbortSignal(outerSignal, "options.signal");
  7263. function abort() {
  7264. finishImpl(new AbortError());
  7265. }
  7266. __name(abort, "abort");
  7267. addAbortListener = addAbortListener || require_util().addAbortListener;
  7268. let disposable;
  7269. if (outerSignal) {
  7270. disposable = addAbortListener(outerSignal, abort);
  7271. }
  7272. let error;
  7273. let value;
  7274. const destroys = [];
  7275. let finishCount = 0;
  7276. function finish(err) {
  7277. finishImpl(err, --finishCount === 0);
  7278. }
  7279. __name(finish, "finish");
  7280. function finishImpl(err, final) {
  7281. var _disposable;
  7282. if (err && (!error || error.code === "ERR_STREAM_PREMATURE_CLOSE")) {
  7283. error = err;
  7284. }
  7285. if (!error && !final) {
  7286. return;
  7287. }
  7288. while (destroys.length) {
  7289. destroys.shift()(error);
  7290. }
  7291. ;
  7292. (_disposable = disposable) === null || _disposable === void 0 ? void 0 : _disposable[SymbolDispose]();
  7293. ac.abort();
  7294. if (final) {
  7295. if (!error) {
  7296. lastStreamCleanup.forEach((fn) => fn());
  7297. }
  7298. process.nextTick(callback, error, value);
  7299. }
  7300. }
  7301. __name(finishImpl, "finishImpl");
  7302. let ret;
  7303. for (let i = 0; i < streams.length; i++) {
  7304. const stream = streams[i];
  7305. const reading = i < streams.length - 1;
  7306. const writing = i > 0;
  7307. const end = reading || (opts === null || opts === void 0 ? void 0 : opts.end) !== false;
  7308. const isLastStream = i === streams.length - 1;
  7309. if (isNodeStream(stream)) {
  7310. let onError2 = function(err) {
  7311. if (err && err.name !== "AbortError" && err.code !== "ERR_STREAM_PREMATURE_CLOSE") {
  7312. finish(err);
  7313. }
  7314. };
  7315. var onError = onError2;
  7316. __name(onError2, "onError");
  7317. if (end) {
  7318. const { destroy, cleanup } = destroyer(stream, reading, writing);
  7319. destroys.push(destroy);
  7320. if (isReadable2(stream) && isLastStream) {
  7321. lastStreamCleanup.push(cleanup);
  7322. }
  7323. }
  7324. stream.on("error", onError2);
  7325. if (isReadable2(stream) && isLastStream) {
  7326. lastStreamCleanup.push(() => {
  7327. stream.removeListener("error", onError2);
  7328. });
  7329. }
  7330. }
  7331. if (i === 0) {
  7332. if (typeof stream === "function") {
  7333. ret = stream({
  7334. signal
  7335. });
  7336. if (!isIterable(ret)) {
  7337. throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or Stream", "source", ret);
  7338. }
  7339. } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) {
  7340. ret = stream;
  7341. } else {
  7342. ret = Duplex.from(stream);
  7343. }
  7344. } else if (typeof stream === "function") {
  7345. if (isTransformStream(ret)) {
  7346. var _ret;
  7347. ret = makeAsyncIterable((_ret = ret) === null || _ret === void 0 ? void 0 : _ret.readable);
  7348. } else {
  7349. ret = makeAsyncIterable(ret);
  7350. }
  7351. ret = stream(ret, {
  7352. signal
  7353. });
  7354. if (reading) {
  7355. if (!isIterable(ret, true)) {
  7356. throw new ERR_INVALID_RETURN_VALUE("AsyncIterable", `transform[${i - 1}]`, ret);
  7357. }
  7358. } else {
  7359. var _ret2;
  7360. if (!PassThrough) {
  7361. PassThrough = require_passthrough();
  7362. }
  7363. const pt = new PassThrough({
  7364. objectMode: true
  7365. });
  7366. const then = (_ret2 = ret) === null || _ret2 === void 0 ? void 0 : _ret2.then;
  7367. if (typeof then === "function") {
  7368. finishCount++;
  7369. then.call(
  7370. ret,
  7371. (val) => {
  7372. value = val;
  7373. if (val != null) {
  7374. pt.write(val);
  7375. }
  7376. if (end) {
  7377. pt.end();
  7378. }
  7379. process.nextTick(finish);
  7380. },
  7381. (err) => {
  7382. pt.destroy(err);
  7383. process.nextTick(finish, err);
  7384. }
  7385. );
  7386. } else if (isIterable(ret, true)) {
  7387. finishCount++;
  7388. pumpToNode(ret, pt, finish, {
  7389. end
  7390. });
  7391. } else if (isReadableStream(ret) || isTransformStream(ret)) {
  7392. const toRead = ret.readable || ret;
  7393. finishCount++;
  7394. pumpToNode(toRead, pt, finish, {
  7395. end
  7396. });
  7397. } else {
  7398. throw new ERR_INVALID_RETURN_VALUE("AsyncIterable or Promise", "destination", ret);
  7399. }
  7400. ret = pt;
  7401. const { destroy, cleanup } = destroyer(ret, false, true);
  7402. destroys.push(destroy);
  7403. if (isLastStream) {
  7404. lastStreamCleanup.push(cleanup);
  7405. }
  7406. }
  7407. } else if (isNodeStream(stream)) {
  7408. if (isReadableNodeStream(ret)) {
  7409. finishCount += 2;
  7410. const cleanup = pipe(ret, stream, finish, {
  7411. end
  7412. });
  7413. if (isReadable2(stream) && isLastStream) {
  7414. lastStreamCleanup.push(cleanup);
  7415. }
  7416. } else if (isTransformStream(ret) || isReadableStream(ret)) {
  7417. const toRead = ret.readable || ret;
  7418. finishCount++;
  7419. pumpToNode(toRead, stream, finish, {
  7420. end
  7421. });
  7422. } else if (isIterable(ret)) {
  7423. finishCount++;
  7424. pumpToNode(ret, stream, finish, {
  7425. end
  7426. });
  7427. } else {
  7428. throw new ERR_INVALID_ARG_TYPE2(
  7429. "val",
  7430. ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"],
  7431. ret
  7432. );
  7433. }
  7434. ret = stream;
  7435. } else if (isWebStream(stream)) {
  7436. if (isReadableNodeStream(ret)) {
  7437. finishCount++;
  7438. pumpToWeb(makeAsyncIterable(ret), stream, finish, {
  7439. end
  7440. });
  7441. } else if (isReadableStream(ret) || isIterable(ret)) {
  7442. finishCount++;
  7443. pumpToWeb(ret, stream, finish, {
  7444. end
  7445. });
  7446. } else if (isTransformStream(ret)) {
  7447. finishCount++;
  7448. pumpToWeb(ret.readable, stream, finish, {
  7449. end
  7450. });
  7451. } else {
  7452. throw new ERR_INVALID_ARG_TYPE2(
  7453. "val",
  7454. ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"],
  7455. ret
  7456. );
  7457. }
  7458. ret = stream;
  7459. } else {
  7460. ret = Duplex.from(stream);
  7461. }
  7462. }
  7463. if (signal !== null && signal !== void 0 && signal.aborted || outerSignal !== null && outerSignal !== void 0 && outerSignal.aborted) {
  7464. process.nextTick(abort);
  7465. }
  7466. return ret;
  7467. }
  7468. __name(pipelineImpl, "pipelineImpl");
  7469. function pipe(src, dst, finish, { end }) {
  7470. let ended = false;
  7471. dst.on("close", () => {
  7472. if (!ended) {
  7473. finish(new ERR_STREAM_PREMATURE_CLOSE());
  7474. }
  7475. });
  7476. src.pipe(dst, {
  7477. end: false
  7478. });
  7479. if (end) {
  7480. let endFn2 = function() {
  7481. ended = true;
  7482. dst.end();
  7483. };
  7484. var endFn = endFn2;
  7485. __name(endFn2, "endFn");
  7486. if (isReadableFinished(src)) {
  7487. process.nextTick(endFn2);
  7488. } else {
  7489. src.once("end", endFn2);
  7490. }
  7491. } else {
  7492. finish();
  7493. }
  7494. eos(
  7495. src,
  7496. {
  7497. readable: true,
  7498. writable: false
  7499. },
  7500. (err) => {
  7501. const rState = src._readableState;
  7502. if (err && err.code === "ERR_STREAM_PREMATURE_CLOSE" && rState && rState.ended && !rState.errored && !rState.errorEmitted) {
  7503. src.once("end", finish).once("error", finish);
  7504. } else {
  7505. finish(err);
  7506. }
  7507. }
  7508. );
  7509. return eos(
  7510. dst,
  7511. {
  7512. readable: false,
  7513. writable: true
  7514. },
  7515. finish
  7516. );
  7517. }
  7518. __name(pipe, "pipe");
  7519. module.exports = {
  7520. pipelineImpl,
  7521. pipeline
  7522. };
  7523. }
  7524. });
  7525. // node_modules/readable-stream/lib/internal/streams/compose.js
  7526. var require_compose = __commonJS({
  7527. "node_modules/readable-stream/lib/internal/streams/compose.js"(exports, module) {
  7528. "use strict";
  7529. var { pipeline } = require_pipeline();
  7530. var Duplex = require_duplex();
  7531. var { destroyer } = require_destroy();
  7532. var {
  7533. isNodeStream,
  7534. isReadable: isReadable2,
  7535. isWritable,
  7536. isWebStream,
  7537. isTransformStream,
  7538. isWritableStream,
  7539. isReadableStream
  7540. } = require_utils();
  7541. var {
  7542. AbortError,
  7543. codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS }
  7544. } = require_errors();
  7545. var eos = require_end_of_stream();
  7546. module.exports = /* @__PURE__ */ __name(function compose(...streams) {
  7547. if (streams.length === 0) {
  7548. throw new ERR_MISSING_ARGS("streams");
  7549. }
  7550. if (streams.length === 1) {
  7551. return Duplex.from(streams[0]);
  7552. }
  7553. const orgStreams = [...streams];
  7554. if (typeof streams[0] === "function") {
  7555. streams[0] = Duplex.from(streams[0]);
  7556. }
  7557. if (typeof streams[streams.length - 1] === "function") {
  7558. const idx = streams.length - 1;
  7559. streams[idx] = Duplex.from(streams[idx]);
  7560. }
  7561. for (let n = 0; n < streams.length; ++n) {
  7562. if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) {
  7563. continue;
  7564. }
  7565. if (n < streams.length - 1 && !(isReadable2(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n]))) {
  7566. throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], "must be readable");
  7567. }
  7568. if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) {
  7569. throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], "must be writable");
  7570. }
  7571. }
  7572. let ondrain;
  7573. let onfinish;
  7574. let onreadable;
  7575. let onclose;
  7576. let d;
  7577. function onfinished(err) {
  7578. const cb = onclose;
  7579. onclose = null;
  7580. if (cb) {
  7581. cb(err);
  7582. } else if (err) {
  7583. d.destroy(err);
  7584. } else if (!readable && !writable) {
  7585. d.destroy();
  7586. }
  7587. }
  7588. __name(onfinished, "onfinished");
  7589. const head = streams[0];
  7590. const tail = pipeline(streams, onfinished);
  7591. const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head));
  7592. const readable = !!(isReadable2(tail) || isReadableStream(tail) || isTransformStream(tail));
  7593. d = new Duplex({
  7594. // TODO (ronag): highWaterMark?
  7595. writableObjectMode: !!(head !== null && head !== void 0 && head.writableObjectMode),
  7596. readableObjectMode: !!(tail !== null && tail !== void 0 && tail.readableObjectMode),
  7597. writable,
  7598. readable
  7599. });
  7600. if (writable) {
  7601. if (isNodeStream(head)) {
  7602. d._write = function(chunk, encoding, callback) {
  7603. if (head.write(chunk, encoding)) {
  7604. callback();
  7605. } else {
  7606. ondrain = callback;
  7607. }
  7608. };
  7609. d._final = function(callback) {
  7610. head.end();
  7611. onfinish = callback;
  7612. };
  7613. head.on("drain", function() {
  7614. if (ondrain) {
  7615. const cb = ondrain;
  7616. ondrain = null;
  7617. cb();
  7618. }
  7619. });
  7620. } else if (isWebStream(head)) {
  7621. const writable2 = isTransformStream(head) ? head.writable : head;
  7622. const writer = writable2.getWriter();
  7623. d._write = async function(chunk, encoding, callback) {
  7624. try {
  7625. await writer.ready;
  7626. writer.write(chunk).catch(() => {
  7627. });
  7628. callback();
  7629. } catch (err) {
  7630. callback(err);
  7631. }
  7632. };
  7633. d._final = async function(callback) {
  7634. try {
  7635. await writer.ready;
  7636. writer.close().catch(() => {
  7637. });
  7638. onfinish = callback;
  7639. } catch (err) {
  7640. callback(err);
  7641. }
  7642. };
  7643. }
  7644. const toRead = isTransformStream(tail) ? tail.readable : tail;
  7645. eos(toRead, () => {
  7646. if (onfinish) {
  7647. const cb = onfinish;
  7648. onfinish = null;
  7649. cb();
  7650. }
  7651. });
  7652. }
  7653. if (readable) {
  7654. if (isNodeStream(tail)) {
  7655. tail.on("readable", function() {
  7656. if (onreadable) {
  7657. const cb = onreadable;
  7658. onreadable = null;
  7659. cb();
  7660. }
  7661. });
  7662. tail.on("end", function() {
  7663. d.push(null);
  7664. });
  7665. d._read = function() {
  7666. while (true) {
  7667. const buf = tail.read();
  7668. if (buf === null) {
  7669. onreadable = d._read;
  7670. return;
  7671. }
  7672. if (!d.push(buf)) {
  7673. return;
  7674. }
  7675. }
  7676. };
  7677. } else if (isWebStream(tail)) {
  7678. const readable2 = isTransformStream(tail) ? tail.readable : tail;
  7679. const reader = readable2.getReader();
  7680. d._read = async function() {
  7681. while (true) {
  7682. try {
  7683. const { value, done } = await reader.read();
  7684. if (!d.push(value)) {
  7685. return;
  7686. }
  7687. if (done) {
  7688. d.push(null);
  7689. return;
  7690. }
  7691. } catch {
  7692. return;
  7693. }
  7694. }
  7695. };
  7696. }
  7697. }
  7698. d._destroy = function(err, callback) {
  7699. if (!err && onclose !== null) {
  7700. err = new AbortError();
  7701. }
  7702. onreadable = null;
  7703. ondrain = null;
  7704. onfinish = null;
  7705. if (onclose === null) {
  7706. callback(err);
  7707. } else {
  7708. onclose = callback;
  7709. if (isNodeStream(tail)) {
  7710. destroyer(tail, err);
  7711. }
  7712. }
  7713. };
  7714. return d;
  7715. }, "compose");
  7716. }
  7717. });
  7718. // node_modules/readable-stream/lib/internal/streams/operators.js
  7719. var require_operators = __commonJS({
  7720. "node_modules/readable-stream/lib/internal/streams/operators.js"(exports, module) {
  7721. "use strict";
  7722. var AbortController = globalThis.AbortController || require_browser().AbortController;
  7723. var {
  7724. codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE2, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE },
  7725. AbortError
  7726. } = require_errors();
  7727. var { validateAbortSignal, validateInteger, validateObject } = require_validators();
  7728. var kWeakHandler = require_primordials().Symbol("kWeak");
  7729. var kResistStopPropagation = require_primordials().Symbol("kResistStopPropagation");
  7730. var { finished } = require_end_of_stream();
  7731. var staticCompose = require_compose();
  7732. var { addAbortSignalNoValidate } = require_add_abort_signal();
  7733. var { isWritable, isNodeStream } = require_utils();
  7734. var { deprecate } = require_util();
  7735. var {
  7736. ArrayPrototypePush,
  7737. Boolean: Boolean2,
  7738. MathFloor,
  7739. Number: Number2,
  7740. NumberIsNaN,
  7741. Promise: Promise2,
  7742. PromiseReject,
  7743. PromiseResolve,
  7744. PromisePrototypeThen,
  7745. Symbol: Symbol2
  7746. } = require_primordials();
  7747. var kEmpty = Symbol2("kEmpty");
  7748. var kEof = Symbol2("kEof");
  7749. function compose(stream, options) {
  7750. if (options != null) {
  7751. validateObject(options, "options");
  7752. }
  7753. if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
  7754. validateAbortSignal(options.signal, "options.signal");
  7755. }
  7756. if (isNodeStream(stream) && !isWritable(stream)) {
  7757. throw new ERR_INVALID_ARG_VALUE("stream", stream, "must be writable");
  7758. }
  7759. const composedStream = staticCompose(this, stream);
  7760. if (options !== null && options !== void 0 && options.signal) {
  7761. addAbortSignalNoValidate(options.signal, composedStream);
  7762. }
  7763. return composedStream;
  7764. }
  7765. __name(compose, "compose");
  7766. function map(fn, options) {
  7767. if (typeof fn !== "function") {
  7768. throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn);
  7769. }
  7770. if (options != null) {
  7771. validateObject(options, "options");
  7772. }
  7773. if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
  7774. validateAbortSignal(options.signal, "options.signal");
  7775. }
  7776. let concurrency = 1;
  7777. if ((options === null || options === void 0 ? void 0 : options.concurrency) != null) {
  7778. concurrency = MathFloor(options.concurrency);
  7779. }
  7780. let highWaterMark = concurrency - 1;
  7781. if ((options === null || options === void 0 ? void 0 : options.highWaterMark) != null) {
  7782. highWaterMark = MathFloor(options.highWaterMark);
  7783. }
  7784. validateInteger(concurrency, "options.concurrency", 1);
  7785. validateInteger(highWaterMark, "options.highWaterMark", 0);
  7786. highWaterMark += concurrency;
  7787. return (/* @__PURE__ */ __name(async function* map2() {
  7788. const signal = require_util().AbortSignalAny(
  7789. [options === null || options === void 0 ? void 0 : options.signal].filter(Boolean2)
  7790. );
  7791. const stream = this;
  7792. const queue = [];
  7793. const signalOpt = {
  7794. signal
  7795. };
  7796. let next;
  7797. let resume;
  7798. let done = false;
  7799. let cnt = 0;
  7800. function onCatch() {
  7801. done = true;
  7802. afterItemProcessed();
  7803. }
  7804. __name(onCatch, "onCatch");
  7805. function afterItemProcessed() {
  7806. cnt -= 1;
  7807. maybeResume();
  7808. }
  7809. __name(afterItemProcessed, "afterItemProcessed");
  7810. function maybeResume() {
  7811. if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {
  7812. resume();
  7813. resume = null;
  7814. }
  7815. }
  7816. __name(maybeResume, "maybeResume");
  7817. async function pump() {
  7818. try {
  7819. for await (let val of stream) {
  7820. if (done) {
  7821. return;
  7822. }
  7823. if (signal.aborted) {
  7824. throw new AbortError();
  7825. }
  7826. try {
  7827. val = fn(val, signalOpt);
  7828. if (val === kEmpty) {
  7829. continue;
  7830. }
  7831. val = PromiseResolve(val);
  7832. } catch (err) {
  7833. val = PromiseReject(err);
  7834. }
  7835. cnt += 1;
  7836. PromisePrototypeThen(val, afterItemProcessed, onCatch);
  7837. queue.push(val);
  7838. if (next) {
  7839. next();
  7840. next = null;
  7841. }
  7842. if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {
  7843. await new Promise2((resolve2) => {
  7844. resume = resolve2;
  7845. });
  7846. }
  7847. }
  7848. queue.push(kEof);
  7849. } catch (err) {
  7850. const val = PromiseReject(err);
  7851. PromisePrototypeThen(val, afterItemProcessed, onCatch);
  7852. queue.push(val);
  7853. } finally {
  7854. done = true;
  7855. if (next) {
  7856. next();
  7857. next = null;
  7858. }
  7859. }
  7860. }
  7861. __name(pump, "pump");
  7862. pump();
  7863. try {
  7864. while (true) {
  7865. while (queue.length > 0) {
  7866. const val = await queue[0];
  7867. if (val === kEof) {
  7868. return;
  7869. }
  7870. if (signal.aborted) {
  7871. throw new AbortError();
  7872. }
  7873. if (val !== kEmpty) {
  7874. yield val;
  7875. }
  7876. queue.shift();
  7877. maybeResume();
  7878. }
  7879. await new Promise2((resolve2) => {
  7880. next = resolve2;
  7881. });
  7882. }
  7883. } finally {
  7884. done = true;
  7885. if (resume) {
  7886. resume();
  7887. resume = null;
  7888. }
  7889. }
  7890. }, "map")).call(this);
  7891. }
  7892. __name(map, "map");
  7893. function asIndexedPairs(options = void 0) {
  7894. if (options != null) {
  7895. validateObject(options, "options");
  7896. }
  7897. if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
  7898. validateAbortSignal(options.signal, "options.signal");
  7899. }
  7900. return (/* @__PURE__ */ __name(async function* asIndexedPairs2() {
  7901. let index = 0;
  7902. for await (const val of this) {
  7903. var _options$signal;
  7904. if (options !== null && options !== void 0 && (_options$signal = options.signal) !== null && _options$signal !== void 0 && _options$signal.aborted) {
  7905. throw new AbortError({
  7906. cause: options.signal.reason
  7907. });
  7908. }
  7909. yield [index++, val];
  7910. }
  7911. }, "asIndexedPairs")).call(this);
  7912. }
  7913. __name(asIndexedPairs, "asIndexedPairs");
  7914. async function some(fn, options = void 0) {
  7915. for await (const unused of filter.call(this, fn, options)) {
  7916. return true;
  7917. }
  7918. return false;
  7919. }
  7920. __name(some, "some");
  7921. async function every(fn, options = void 0) {
  7922. if (typeof fn !== "function") {
  7923. throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn);
  7924. }
  7925. return !await some.call(
  7926. this,
  7927. async (...args) => {
  7928. return !await fn(...args);
  7929. },
  7930. options
  7931. );
  7932. }
  7933. __name(every, "every");
  7934. async function find(fn, options) {
  7935. for await (const result of filter.call(this, fn, options)) {
  7936. return result;
  7937. }
  7938. return void 0;
  7939. }
  7940. __name(find, "find");
  7941. async function forEach(fn, options) {
  7942. if (typeof fn !== "function") {
  7943. throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn);
  7944. }
  7945. async function forEachFn(value, options2) {
  7946. await fn(value, options2);
  7947. return kEmpty;
  7948. }
  7949. __name(forEachFn, "forEachFn");
  7950. for await (const unused of map.call(this, forEachFn, options)) ;
  7951. }
  7952. __name(forEach, "forEach");
  7953. function filter(fn, options) {
  7954. if (typeof fn !== "function") {
  7955. throw new ERR_INVALID_ARG_TYPE2("fn", ["Function", "AsyncFunction"], fn);
  7956. }
  7957. async function filterFn(value, options2) {
  7958. if (await fn(value, options2)) {
  7959. return value;
  7960. }
  7961. return kEmpty;
  7962. }
  7963. __name(filterFn, "filterFn");
  7964. return map.call(this, filterFn, options);
  7965. }
  7966. __name(filter, "filter");
  7967. var ReduceAwareErrMissingArgs = class extends ERR_MISSING_ARGS {
  7968. static {
  7969. __name(this, "ReduceAwareErrMissingArgs");
  7970. }
  7971. constructor() {
  7972. super("reduce");
  7973. this.message = "Reduce of an empty stream requires an initial value";
  7974. }
  7975. };
  7976. async function reduce(reducer, initialValue, options) {
  7977. var _options$signal2;
  7978. if (typeof reducer !== "function") {
  7979. throw new ERR_INVALID_ARG_TYPE2("reducer", ["Function", "AsyncFunction"], reducer);
  7980. }
  7981. if (options != null) {
  7982. validateObject(options, "options");
  7983. }
  7984. if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
  7985. validateAbortSignal(options.signal, "options.signal");
  7986. }
  7987. let hasInitialValue = arguments.length > 1;
  7988. if (options !== null && options !== void 0 && (_options$signal2 = options.signal) !== null && _options$signal2 !== void 0 && _options$signal2.aborted) {
  7989. const err = new AbortError(void 0, {
  7990. cause: options.signal.reason
  7991. });
  7992. this.once("error", () => {
  7993. });
  7994. await finished(this.destroy(err));
  7995. throw err;
  7996. }
  7997. const ac = new AbortController();
  7998. const signal = ac.signal;
  7999. if (options !== null && options !== void 0 && options.signal) {
  8000. const opts = {
  8001. once: true,
  8002. [kWeakHandler]: this,
  8003. [kResistStopPropagation]: true
  8004. };
  8005. options.signal.addEventListener("abort", () => ac.abort(), opts);
  8006. }
  8007. let gotAnyItemFromStream = false;
  8008. try {
  8009. for await (const value of this) {
  8010. var _options$signal3;
  8011. gotAnyItemFromStream = true;
  8012. if (options !== null && options !== void 0 && (_options$signal3 = options.signal) !== null && _options$signal3 !== void 0 && _options$signal3.aborted) {
  8013. throw new AbortError();
  8014. }
  8015. if (!hasInitialValue) {
  8016. initialValue = value;
  8017. hasInitialValue = true;
  8018. } else {
  8019. initialValue = await reducer(initialValue, value, {
  8020. signal
  8021. });
  8022. }
  8023. }
  8024. if (!gotAnyItemFromStream && !hasInitialValue) {
  8025. throw new ReduceAwareErrMissingArgs();
  8026. }
  8027. } finally {
  8028. ac.abort();
  8029. }
  8030. return initialValue;
  8031. }
  8032. __name(reduce, "reduce");
  8033. async function toArray(options) {
  8034. if (options != null) {
  8035. validateObject(options, "options");
  8036. }
  8037. if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
  8038. validateAbortSignal(options.signal, "options.signal");
  8039. }
  8040. const result = [];
  8041. for await (const val of this) {
  8042. var _options$signal4;
  8043. if (options !== null && options !== void 0 && (_options$signal4 = options.signal) !== null && _options$signal4 !== void 0 && _options$signal4.aborted) {
  8044. throw new AbortError(void 0, {
  8045. cause: options.signal.reason
  8046. });
  8047. }
  8048. ArrayPrototypePush(result, val);
  8049. }
  8050. return result;
  8051. }
  8052. __name(toArray, "toArray");
  8053. function flatMap(fn, options) {
  8054. const values = map.call(this, fn, options);
  8055. return (/* @__PURE__ */ __name(async function* flatMap2() {
  8056. for await (const val of values) {
  8057. yield* val;
  8058. }
  8059. }, "flatMap")).call(this);
  8060. }
  8061. __name(flatMap, "flatMap");
  8062. function toIntegerOrInfinity(number) {
  8063. number = Number2(number);
  8064. if (NumberIsNaN(number)) {
  8065. return 0;
  8066. }
  8067. if (number < 0) {
  8068. throw new ERR_OUT_OF_RANGE("number", ">= 0", number);
  8069. }
  8070. return number;
  8071. }
  8072. __name(toIntegerOrInfinity, "toIntegerOrInfinity");
  8073. function drop(number, options = void 0) {
  8074. if (options != null) {
  8075. validateObject(options, "options");
  8076. }
  8077. if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
  8078. validateAbortSignal(options.signal, "options.signal");
  8079. }
  8080. number = toIntegerOrInfinity(number);
  8081. return (/* @__PURE__ */ __name(async function* drop2() {
  8082. var _options$signal5;
  8083. if (options !== null && options !== void 0 && (_options$signal5 = options.signal) !== null && _options$signal5 !== void 0 && _options$signal5.aborted) {
  8084. throw new AbortError();
  8085. }
  8086. for await (const val of this) {
  8087. var _options$signal6;
  8088. if (options !== null && options !== void 0 && (_options$signal6 = options.signal) !== null && _options$signal6 !== void 0 && _options$signal6.aborted) {
  8089. throw new AbortError();
  8090. }
  8091. if (number-- <= 0) {
  8092. yield val;
  8093. }
  8094. }
  8095. }, "drop")).call(this);
  8096. }
  8097. __name(drop, "drop");
  8098. function take(number, options = void 0) {
  8099. if (options != null) {
  8100. validateObject(options, "options");
  8101. }
  8102. if ((options === null || options === void 0 ? void 0 : options.signal) != null) {
  8103. validateAbortSignal(options.signal, "options.signal");
  8104. }
  8105. number = toIntegerOrInfinity(number);
  8106. return (/* @__PURE__ */ __name(async function* take2() {
  8107. var _options$signal7;
  8108. if (options !== null && options !== void 0 && (_options$signal7 = options.signal) !== null && _options$signal7 !== void 0 && _options$signal7.aborted) {
  8109. throw new AbortError();
  8110. }
  8111. for await (const val of this) {
  8112. var _options$signal8;
  8113. if (options !== null && options !== void 0 && (_options$signal8 = options.signal) !== null && _options$signal8 !== void 0 && _options$signal8.aborted) {
  8114. throw new AbortError();
  8115. }
  8116. if (number-- > 0) {
  8117. yield val;
  8118. }
  8119. if (number <= 0) {
  8120. return;
  8121. }
  8122. }
  8123. }, "take")).call(this);
  8124. }
  8125. __name(take, "take");
  8126. module.exports.streamReturningOperators = {
  8127. asIndexedPairs: deprecate(asIndexedPairs, "readable.asIndexedPairs will be removed in a future version."),
  8128. drop,
  8129. filter,
  8130. flatMap,
  8131. map,
  8132. take,
  8133. compose
  8134. };
  8135. module.exports.promiseReturningOperators = {
  8136. every,
  8137. forEach,
  8138. reduce,
  8139. toArray,
  8140. some,
  8141. find
  8142. };
  8143. }
  8144. });
  8145. // node_modules/readable-stream/lib/stream/promises.js
  8146. var require_promises = __commonJS({
  8147. "node_modules/readable-stream/lib/stream/promises.js"(exports, module) {
  8148. "use strict";
  8149. var { ArrayPrototypePop, Promise: Promise2 } = require_primordials();
  8150. var { isIterable, isNodeStream, isWebStream } = require_utils();
  8151. var { pipelineImpl: pl } = require_pipeline();
  8152. var { finished } = require_end_of_stream();
  8153. require_stream();
  8154. function pipeline(...streams) {
  8155. return new Promise2((resolve2, reject) => {
  8156. let signal;
  8157. let end;
  8158. const lastArg = streams[streams.length - 1];
  8159. if (lastArg && typeof lastArg === "object" && !isNodeStream(lastArg) && !isIterable(lastArg) && !isWebStream(lastArg)) {
  8160. const options = ArrayPrototypePop(streams);
  8161. signal = options.signal;
  8162. end = options.end;
  8163. }
  8164. pl(
  8165. streams,
  8166. (err, value) => {
  8167. if (err) {
  8168. reject(err);
  8169. } else {
  8170. resolve2(value);
  8171. }
  8172. },
  8173. {
  8174. signal,
  8175. end
  8176. }
  8177. );
  8178. });
  8179. }
  8180. __name(pipeline, "pipeline");
  8181. module.exports = {
  8182. finished,
  8183. pipeline
  8184. };
  8185. }
  8186. });
  8187. // node_modules/readable-stream/lib/stream.js
  8188. var require_stream = __commonJS({
  8189. "node_modules/readable-stream/lib/stream.js"(exports, module) {
  8190. var { Buffer: Buffer4 } = require_buffer();
  8191. var { ObjectDefineProperty, ObjectKeys, ReflectApply } = require_primordials();
  8192. var {
  8193. promisify: { custom: customPromisify }
  8194. } = require_util();
  8195. var { streamReturningOperators, promiseReturningOperators } = require_operators();
  8196. var {
  8197. codes: { ERR_ILLEGAL_CONSTRUCTOR }
  8198. } = require_errors();
  8199. var compose = require_compose();
  8200. var { setDefaultHighWaterMark, getDefaultHighWaterMark } = require_state();
  8201. var { pipeline } = require_pipeline();
  8202. var { destroyer } = require_destroy();
  8203. var eos = require_end_of_stream();
  8204. var promises = require_promises();
  8205. var utils = require_utils();
  8206. var Stream = module.exports = require_legacy().Stream;
  8207. Stream.isDestroyed = utils.isDestroyed;
  8208. Stream.isDisturbed = utils.isDisturbed;
  8209. Stream.isErrored = utils.isErrored;
  8210. Stream.isReadable = utils.isReadable;
  8211. Stream.isWritable = utils.isWritable;
  8212. Stream.Readable = require_readable();
  8213. for (const key of ObjectKeys(streamReturningOperators)) {
  8214. let fn2 = function(...args) {
  8215. if (new.target) {
  8216. throw ERR_ILLEGAL_CONSTRUCTOR();
  8217. }
  8218. return Stream.Readable.from(ReflectApply(op, this, args));
  8219. };
  8220. fn = fn2;
  8221. __name(fn2, "fn");
  8222. const op = streamReturningOperators[key];
  8223. ObjectDefineProperty(fn2, "name", {
  8224. __proto__: null,
  8225. value: op.name
  8226. });
  8227. ObjectDefineProperty(fn2, "length", {
  8228. __proto__: null,
  8229. value: op.length
  8230. });
  8231. ObjectDefineProperty(Stream.Readable.prototype, key, {
  8232. __proto__: null,
  8233. value: fn2,
  8234. enumerable: false,
  8235. configurable: true,
  8236. writable: true
  8237. });
  8238. }
  8239. var fn;
  8240. for (const key of ObjectKeys(promiseReturningOperators)) {
  8241. let fn2 = function(...args) {
  8242. if (new.target) {
  8243. throw ERR_ILLEGAL_CONSTRUCTOR();
  8244. }
  8245. return ReflectApply(op, this, args);
  8246. };
  8247. fn = fn2;
  8248. __name(fn2, "fn");
  8249. const op = promiseReturningOperators[key];
  8250. ObjectDefineProperty(fn2, "name", {
  8251. __proto__: null,
  8252. value: op.name
  8253. });
  8254. ObjectDefineProperty(fn2, "length", {
  8255. __proto__: null,
  8256. value: op.length
  8257. });
  8258. ObjectDefineProperty(Stream.Readable.prototype, key, {
  8259. __proto__: null,
  8260. value: fn2,
  8261. enumerable: false,
  8262. configurable: true,
  8263. writable: true
  8264. });
  8265. }
  8266. var fn;
  8267. Stream.Writable = require_writable();
  8268. Stream.Duplex = require_duplex();
  8269. Stream.Transform = require_transform();
  8270. Stream.PassThrough = require_passthrough();
  8271. Stream.pipeline = pipeline;
  8272. var { addAbortSignal } = require_add_abort_signal();
  8273. Stream.addAbortSignal = addAbortSignal;
  8274. Stream.finished = eos;
  8275. Stream.destroy = destroyer;
  8276. Stream.compose = compose;
  8277. Stream.setDefaultHighWaterMark = setDefaultHighWaterMark;
  8278. Stream.getDefaultHighWaterMark = getDefaultHighWaterMark;
  8279. ObjectDefineProperty(Stream, "promises", {
  8280. __proto__: null,
  8281. configurable: true,
  8282. enumerable: true,
  8283. get: /* @__PURE__ */ __name(function() {
  8284. return promises;
  8285. }, "get")
  8286. });
  8287. ObjectDefineProperty(pipeline, customPromisify, {
  8288. __proto__: null,
  8289. enumerable: true,
  8290. get: /* @__PURE__ */ __name(function() {
  8291. return promises.pipeline;
  8292. }, "get")
  8293. });
  8294. ObjectDefineProperty(eos, customPromisify, {
  8295. __proto__: null,
  8296. enumerable: true,
  8297. get: /* @__PURE__ */ __name(function() {
  8298. return promises.finished;
  8299. }, "get")
  8300. });
  8301. Stream.Stream = Stream;
  8302. Stream._isUint8Array = /* @__PURE__ */ __name(function isUint8Array(value) {
  8303. return value instanceof Uint8Array;
  8304. }, "isUint8Array");
  8305. Stream._uint8ArrayToBuffer = /* @__PURE__ */ __name(function _uint8ArrayToBuffer(chunk) {
  8306. return Buffer4.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
  8307. }, "_uint8ArrayToBuffer");
  8308. }
  8309. });
  8310. // node_modules/readable-stream/lib/ours/browser.js
  8311. var require_browser3 = __commonJS({
  8312. "node_modules/readable-stream/lib/ours/browser.js"(exports, module) {
  8313. "use strict";
  8314. var CustomStream = require_stream();
  8315. var promises = require_promises();
  8316. var originalDestroy = CustomStream.Readable.destroy;
  8317. module.exports = CustomStream.Readable;
  8318. module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer;
  8319. module.exports._isUint8Array = CustomStream._isUint8Array;
  8320. module.exports.isDisturbed = CustomStream.isDisturbed;
  8321. module.exports.isErrored = CustomStream.isErrored;
  8322. module.exports.isReadable = CustomStream.isReadable;
  8323. module.exports.Readable = CustomStream.Readable;
  8324. module.exports.Writable = CustomStream.Writable;
  8325. module.exports.Duplex = CustomStream.Duplex;
  8326. module.exports.Transform = CustomStream.Transform;
  8327. module.exports.PassThrough = CustomStream.PassThrough;
  8328. module.exports.addAbortSignal = CustomStream.addAbortSignal;
  8329. module.exports.finished = CustomStream.finished;
  8330. module.exports.destroy = CustomStream.destroy;
  8331. module.exports.destroy = originalDestroy;
  8332. module.exports.pipeline = CustomStream.pipeline;
  8333. module.exports.compose = CustomStream.compose;
  8334. Object.defineProperty(CustomStream, "promises", {
  8335. configurable: true,
  8336. enumerable: true,
  8337. get: /* @__PURE__ */ __name(function() {
  8338. return promises;
  8339. }, "get")
  8340. });
  8341. module.exports.Stream = CustomStream.Stream;
  8342. module.exports.default = module.exports;
  8343. }
  8344. });
  8345. // src/index.ts
  8346. var src_exports = {};
  8347. __export(src_exports, {
  8348. ActionType: () => ActionType,
  8349. Async: () => Async,
  8350. AsyncIndexFS: () => AsyncIndexFS,
  8351. AsyncTransaction: () => AsyncTransaction,
  8352. BigIntStats: () => BigIntStats,
  8353. BigIntStatsFs: () => BigIntStatsFs,
  8354. Dir: () => Dir,
  8355. Dirent: () => Dirent,
  8356. Errno: () => Errno,
  8357. ErrnoError: () => ErrnoError,
  8358. Fetch: () => Fetch,
  8359. FetchFS: () => FetchFS,
  8360. File: () => File,
  8361. FileIndex: () => FileIndex,
  8362. FileSystem: () => FileSystem,
  8363. FileType: () => FileType,
  8364. InMemory: () => InMemory,
  8365. InMemoryStore: () => InMemoryStore,
  8366. IndexDirInode: () => IndexDirInode,
  8367. IndexFS: () => IndexFS,
  8368. IndexFileInode: () => IndexFileInode,
  8369. IndexInode: () => IndexInode,
  8370. Inode: () => Inode,
  8371. LockedFS: () => LockedFS,
  8372. Mutex: () => Mutex,
  8373. NoSyncFile: () => NoSyncFile,
  8374. Overlay: () => Overlay,
  8375. OverlayFS: () => OverlayFS,
  8376. Port: () => Port,
  8377. PortFS: () => PortFS,
  8378. PortFile: () => PortFile,
  8379. PreloadFile: () => PreloadFile,
  8380. ReadStream: () => ReadStream,
  8381. Readonly: () => Readonly,
  8382. SimpleAsyncStore: () => SimpleAsyncStore,
  8383. SimpleTransaction: () => SimpleTransaction,
  8384. Stats: () => Stats,
  8385. StatsCommon: () => StatsCommon,
  8386. StatsFs: () => StatsFs,
  8387. StoreFS: () => StoreFS,
  8388. Sync: () => Sync,
  8389. SyncIndexFS: () => SyncIndexFS,
  8390. SyncTransaction: () => SyncTransaction,
  8391. Transaction: () => Transaction,
  8392. UnlockedOverlayFS: () => UnlockedOverlayFS,
  8393. WriteStream: () => WriteStream,
  8394. _toUnixTimestamp: () => _toUnixTimestamp,
  8395. access: () => access2,
  8396. accessSync: () => accessSync,
  8397. appendFile: () => appendFile2,
  8398. appendFileSync: () => appendFileSync,
  8399. attachFS: () => attachFS,
  8400. checkOptions: () => checkOptions,
  8401. chmod: () => chmod2,
  8402. chmodSync: () => chmodSync,
  8403. chown: () => chown2,
  8404. chownSync: () => chownSync,
  8405. close: () => close,
  8406. closeSync: () => closeSync,
  8407. configure: () => configure,
  8408. constants: () => constants_exports,
  8409. copyFile: () => copyFile2,
  8410. copyFileSync: () => copyFileSync,
  8411. cp: () => cp2,
  8412. cpSync: () => cpSync,
  8413. createReadStream: () => createReadStream,
  8414. createWriteStream: () => createWriteStream,
  8415. decode: () => decode,
  8416. decodeDirListing: () => decodeDirListing,
  8417. default: () => src_default,
  8418. detachFS: () => detachFS,
  8419. encode: () => encode,
  8420. encodeDirListing: () => encodeDirListing,
  8421. errorMessages: () => errorMessages,
  8422. exists: () => exists2,
  8423. existsSync: () => existsSync,
  8424. fchmod: () => fchmod,
  8425. fchmodSync: () => fchmodSync,
  8426. fchown: () => fchown,
  8427. fchownSync: () => fchownSync,
  8428. fdatasync: () => fdatasync,
  8429. fdatasyncSync: () => fdatasyncSync,
  8430. flagToMode: () => flagToMode,
  8431. flagToNumber: () => flagToNumber,
  8432. flagToString: () => flagToString,
  8433. fs: () => emulation_exports,
  8434. fstat: () => fstat,
  8435. fstatSync: () => fstatSync,
  8436. fsync: () => fsync,
  8437. fsyncSync: () => fsyncSync,
  8438. ftruncate: () => ftruncate,
  8439. ftruncateSync: () => ftruncateSync,
  8440. futimes: () => futimes,
  8441. futimesSync: () => futimesSync,
  8442. isAppendable: () => isAppendable,
  8443. isBackend: () => isBackend,
  8444. isBackendConfig: () => isBackendConfig,
  8445. isExclusive: () => isExclusive,
  8446. isReadable: () => isReadable,
  8447. isSynchronous: () => isSynchronous,
  8448. isTruncating: () => isTruncating,
  8449. isWriteable: () => isWriteable,
  8450. lchmod: () => lchmod2,
  8451. lchmodSync: () => lchmodSync,
  8452. lchown: () => lchown2,
  8453. lchownSync: () => lchownSync,
  8454. levenshtein: () => levenshtein,
  8455. link: () => link2,
  8456. linkSync: () => linkSync,
  8457. lopenSync: () => lopenSync,
  8458. lstat: () => lstat2,
  8459. lstatSync: () => lstatSync,
  8460. lutimes: () => lutimes2,
  8461. lutimesSync: () => lutimesSync,
  8462. mkdir: () => mkdir2,
  8463. mkdirSync: () => mkdirSync,
  8464. mkdirpSync: () => mkdirpSync,
  8465. mkdtemp: () => mkdtemp2,
  8466. mkdtempSync: () => mkdtempSync,
  8467. mount: () => mount,
  8468. mountObject: () => mountObject,
  8469. mounts: () => mounts,
  8470. nop: () => nop,
  8471. normalizeMode: () => normalizeMode,
  8472. normalizeOptions: () => normalizeOptions,
  8473. normalizePath: () => normalizePath,
  8474. normalizeTime: () => normalizeTime,
  8475. open: () => open2,
  8476. openAsBlob: () => openAsBlob,
  8477. openSync: () => openSync,
  8478. opendir: () => opendir2,
  8479. opendirSync: () => opendirSync,
  8480. parseFlag: () => parseFlag,
  8481. pathExistsAction: () => pathExistsAction,
  8482. pathNotExistsAction: () => pathNotExistsAction,
  8483. promises: () => promises_exports,
  8484. randomIno: () => randomIno,
  8485. read: () => read,
  8486. readFile: () => readFile2,
  8487. readFileSync: () => readFileSync,
  8488. readSync: () => readSync,
  8489. readdir: () => readdir2,
  8490. readdirSync: () => readdirSync,
  8491. readlink: () => readlink2,
  8492. readlinkSync: () => readlinkSync,
  8493. readv: () => readv,
  8494. readvSync: () => readvSync,
  8495. realpath: () => realpath2,
  8496. realpathSync: () => realpathSync,
  8497. rename: () => rename2,
  8498. renameSync: () => renameSync,
  8499. resolveMountConfig: () => resolveMountConfig,
  8500. rm: () => rm2,
  8501. rmSync: () => rmSync,
  8502. rmdir: () => rmdir2,
  8503. rmdirSync: () => rmdirSync,
  8504. rootCred: () => rootCred,
  8505. rootIno: () => rootIno,
  8506. setImmediate: () => setImmediate,
  8507. size_max: () => size_max,
  8508. stat: () => stat2,
  8509. statSync: () => statSync,
  8510. statfs: () => statfs2,
  8511. statfsSync: () => statfsSync,
  8512. symlink: () => symlink2,
  8513. symlinkSync: () => symlinkSync,
  8514. truncate: () => truncate2,
  8515. truncateSync: () => truncateSync,
  8516. umount: () => umount,
  8517. unlink: () => unlink2,
  8518. unlinkSync: () => unlinkSync,
  8519. unwatchFile: () => unwatchFile,
  8520. utimes: () => utimes2,
  8521. utimesSync: () => utimesSync,
  8522. watch: () => watch2,
  8523. watchFile: () => watchFile,
  8524. write: () => write,
  8525. writeFile: () => writeFile2,
  8526. writeFileSync: () => writeFileSync,
  8527. writeSync: () => writeSync,
  8528. writev: () => writev,
  8529. writevSync: () => writevSync
  8530. });
  8531. // src/error.ts
  8532. var Errno = /* @__PURE__ */ ((Errno2) => {
  8533. Errno2[Errno2["EPERM"] = 1] = "EPERM";
  8534. Errno2[Errno2["ENOENT"] = 2] = "ENOENT";
  8535. Errno2[Errno2["EINTR"] = 4] = "EINTR";
  8536. Errno2[Errno2["EIO"] = 5] = "EIO";
  8537. Errno2[Errno2["ENXIO"] = 6] = "ENXIO";
  8538. Errno2[Errno2["EBADF"] = 9] = "EBADF";
  8539. Errno2[Errno2["EAGAIN"] = 11] = "EAGAIN";
  8540. Errno2[Errno2["ENOMEM"] = 12] = "ENOMEM";
  8541. Errno2[Errno2["EACCES"] = 13] = "EACCES";
  8542. Errno2[Errno2["EFAULT"] = 14] = "EFAULT";
  8543. Errno2[Errno2["ENOTBLK"] = 15] = "ENOTBLK";
  8544. Errno2[Errno2["EBUSY"] = 16] = "EBUSY";
  8545. Errno2[Errno2["EEXIST"] = 17] = "EEXIST";
  8546. Errno2[Errno2["EXDEV"] = 18] = "EXDEV";
  8547. Errno2[Errno2["ENODEV"] = 19] = "ENODEV";
  8548. Errno2[Errno2["ENOTDIR"] = 20] = "ENOTDIR";
  8549. Errno2[Errno2["EISDIR"] = 21] = "EISDIR";
  8550. Errno2[Errno2["EINVAL"] = 22] = "EINVAL";
  8551. Errno2[Errno2["ENFILE"] = 23] = "ENFILE";
  8552. Errno2[Errno2["EMFILE"] = 24] = "EMFILE";
  8553. Errno2[Errno2["ETXTBSY"] = 26] = "ETXTBSY";
  8554. Errno2[Errno2["EFBIG"] = 27] = "EFBIG";
  8555. Errno2[Errno2["ENOSPC"] = 28] = "ENOSPC";
  8556. Errno2[Errno2["ESPIPE"] = 29] = "ESPIPE";
  8557. Errno2[Errno2["EROFS"] = 30] = "EROFS";
  8558. Errno2[Errno2["EMLINK"] = 31] = "EMLINK";
  8559. Errno2[Errno2["EPIPE"] = 32] = "EPIPE";
  8560. Errno2[Errno2["EDOM"] = 33] = "EDOM";
  8561. Errno2[Errno2["ERANGE"] = 34] = "ERANGE";
  8562. Errno2[Errno2["EDEADLK"] = 35] = "EDEADLK";
  8563. Errno2[Errno2["ENAMETOOLONG"] = 36] = "ENAMETOOLONG";
  8564. Errno2[Errno2["ENOLCK"] = 37] = "ENOLCK";
  8565. Errno2[Errno2["ENOSYS"] = 38] = "ENOSYS";
  8566. Errno2[Errno2["ENOTEMPTY"] = 39] = "ENOTEMPTY";
  8567. Errno2[Errno2["ELOOP"] = 40] = "ELOOP";
  8568. Errno2[Errno2["ENOMSG"] = 42] = "ENOMSG";
  8569. Errno2[Errno2["EBADE"] = 52] = "EBADE";
  8570. Errno2[Errno2["EBADR"] = 53] = "EBADR";
  8571. Errno2[Errno2["EXFULL"] = 54] = "EXFULL";
  8572. Errno2[Errno2["ENOANO"] = 55] = "ENOANO";
  8573. Errno2[Errno2["EBADRQC"] = 56] = "EBADRQC";
  8574. Errno2[Errno2["ENOSTR"] = 60] = "ENOSTR";
  8575. Errno2[Errno2["ENODATA"] = 61] = "ENODATA";
  8576. Errno2[Errno2["ETIME"] = 62] = "ETIME";
  8577. Errno2[Errno2["ENOSR"] = 63] = "ENOSR";
  8578. Errno2[Errno2["ENONET"] = 64] = "ENONET";
  8579. Errno2[Errno2["EREMOTE"] = 66] = "EREMOTE";
  8580. Errno2[Errno2["ENOLINK"] = 67] = "ENOLINK";
  8581. Errno2[Errno2["ECOMM"] = 70] = "ECOMM";
  8582. Errno2[Errno2["EPROTO"] = 71] = "EPROTO";
  8583. Errno2[Errno2["EBADMSG"] = 74] = "EBADMSG";
  8584. Errno2[Errno2["EOVERFLOW"] = 75] = "EOVERFLOW";
  8585. Errno2[Errno2["EBADFD"] = 77] = "EBADFD";
  8586. Errno2[Errno2["ESTRPIPE"] = 86] = "ESTRPIPE";
  8587. Errno2[Errno2["ENOTSOCK"] = 88] = "ENOTSOCK";
  8588. Errno2[Errno2["EDESTADDRREQ"] = 89] = "EDESTADDRREQ";
  8589. Errno2[Errno2["EMSGSIZE"] = 90] = "EMSGSIZE";
  8590. Errno2[Errno2["EPROTOTYPE"] = 91] = "EPROTOTYPE";
  8591. Errno2[Errno2["ENOPROTOOPT"] = 92] = "ENOPROTOOPT";
  8592. Errno2[Errno2["EPROTONOSUPPORT"] = 93] = "EPROTONOSUPPORT";
  8593. Errno2[Errno2["ESOCKTNOSUPPORT"] = 94] = "ESOCKTNOSUPPORT";
  8594. Errno2[Errno2["ENOTSUP"] = 95] = "ENOTSUP";
  8595. Errno2[Errno2["ENETDOWN"] = 100] = "ENETDOWN";
  8596. Errno2[Errno2["ENETUNREACH"] = 101] = "ENETUNREACH";
  8597. Errno2[Errno2["ENETRESET"] = 102] = "ENETRESET";
  8598. Errno2[Errno2["ETIMEDOUT"] = 110] = "ETIMEDOUT";
  8599. Errno2[Errno2["ECONNREFUSED"] = 111] = "ECONNREFUSED";
  8600. Errno2[Errno2["EHOSTDOWN"] = 112] = "EHOSTDOWN";
  8601. Errno2[Errno2["EHOSTUNREACH"] = 113] = "EHOSTUNREACH";
  8602. Errno2[Errno2["EALREADY"] = 114] = "EALREADY";
  8603. Errno2[Errno2["EINPROGRESS"] = 115] = "EINPROGRESS";
  8604. Errno2[Errno2["ESTALE"] = 116] = "ESTALE";
  8605. Errno2[Errno2["EREMOTEIO"] = 121] = "EREMOTEIO";
  8606. Errno2[Errno2["EDQUOT"] = 122] = "EDQUOT";
  8607. return Errno2;
  8608. })(Errno || {});
  8609. var errorMessages = {
  8610. [1 /* EPERM */]: "Operation not permitted",
  8611. [2 /* ENOENT */]: "No such file or directory",
  8612. [4 /* EINTR */]: "Interrupted system call",
  8613. [5 /* EIO */]: "Input/output error",
  8614. [6 /* ENXIO */]: "No such device or address",
  8615. [9 /* EBADF */]: "Bad file descriptor",
  8616. [11 /* EAGAIN */]: "Resource temporarily unavailable",
  8617. [12 /* ENOMEM */]: "Cannot allocate memory",
  8618. [13 /* EACCES */]: "Permission denied",
  8619. [14 /* EFAULT */]: "Bad address",
  8620. [15 /* ENOTBLK */]: "Block device required",
  8621. [16 /* EBUSY */]: "Resource busy or locked",
  8622. [17 /* EEXIST */]: "File exists",
  8623. [18 /* EXDEV */]: "Invalid cross-device link",
  8624. [19 /* ENODEV */]: "No such device",
  8625. [20 /* ENOTDIR */]: "File is not a directory",
  8626. [21 /* EISDIR */]: "File is a directory",
  8627. [22 /* EINVAL */]: "Invalid argument",
  8628. [23 /* ENFILE */]: "Too many open files in system",
  8629. [24 /* EMFILE */]: "Too many open files",
  8630. [26 /* ETXTBSY */]: "Text file busy",
  8631. [27 /* EFBIG */]: "File is too big",
  8632. [28 /* ENOSPC */]: "No space left on disk",
  8633. [29 /* ESPIPE */]: "Illegal seek",
  8634. [30 /* EROFS */]: "Cannot modify a read-only file system",
  8635. [31 /* EMLINK */]: "Too many links",
  8636. [32 /* EPIPE */]: "Broken pipe",
  8637. [33 /* EDOM */]: "Numerical argument out of domain",
  8638. [34 /* ERANGE */]: "Numerical result out of range",
  8639. [35 /* EDEADLK */]: "Resource deadlock would occur",
  8640. [36 /* ENAMETOOLONG */]: "File name too long",
  8641. [37 /* ENOLCK */]: "No locks available",
  8642. [38 /* ENOSYS */]: "Function not implemented",
  8643. [39 /* ENOTEMPTY */]: "Directory is not empty",
  8644. [40 /* ELOOP */]: "Too many levels of symbolic links",
  8645. [42 /* ENOMSG */]: "No message of desired type",
  8646. [52 /* EBADE */]: "Invalid exchange",
  8647. [53 /* EBADR */]: "Invalid request descriptor",
  8648. [54 /* EXFULL */]: "Exchange full",
  8649. [55 /* ENOANO */]: "No anode",
  8650. [56 /* EBADRQC */]: "Invalid request code",
  8651. [60 /* ENOSTR */]: "Device not a stream",
  8652. [61 /* ENODATA */]: "No data available",
  8653. [62 /* ETIME */]: "Timer expired",
  8654. [63 /* ENOSR */]: "Out of streams resources",
  8655. [64 /* ENONET */]: "Machine is not on the network",
  8656. [66 /* EREMOTE */]: "Object is remote",
  8657. [67 /* ENOLINK */]: "Link has been severed",
  8658. [70 /* ECOMM */]: "Communication error on send",
  8659. [71 /* EPROTO */]: "Protocol error",
  8660. [74 /* EBADMSG */]: "Bad message",
  8661. [75 /* EOVERFLOW */]: "Value too large for defined data type",
  8662. [77 /* EBADFD */]: "File descriptor in bad state",
  8663. [86 /* ESTRPIPE */]: "Streams pipe error",
  8664. [88 /* ENOTSOCK */]: "Socket operation on non-socket",
  8665. [89 /* EDESTADDRREQ */]: "Destination address required",
  8666. [90 /* EMSGSIZE */]: "Message too long",
  8667. [91 /* EPROTOTYPE */]: "Protocol wrong type for socket",
  8668. [92 /* ENOPROTOOPT */]: "Protocol not available",
  8669. [93 /* EPROTONOSUPPORT */]: "Protocol not supported",
  8670. [94 /* ESOCKTNOSUPPORT */]: "Socket type not supported",
  8671. [95 /* ENOTSUP */]: "Operation is not supported",
  8672. [100 /* ENETDOWN */]: "Network is down",
  8673. [101 /* ENETUNREACH */]: "Network is unreachable",
  8674. [102 /* ENETRESET */]: "Network dropped connection on reset",
  8675. [110 /* ETIMEDOUT */]: "Connection timed out",
  8676. [111 /* ECONNREFUSED */]: "Connection refused",
  8677. [112 /* EHOSTDOWN */]: "Host is down",
  8678. [113 /* EHOSTUNREACH */]: "No route to host",
  8679. [114 /* EALREADY */]: "Operation already in progress",
  8680. [115 /* EINPROGRESS */]: "Operation now in progress",
  8681. [116 /* ESTALE */]: "Stale file handle",
  8682. [121 /* EREMOTEIO */]: "Remote I/O error",
  8683. [122 /* EDQUOT */]: "Disk quota exceeded"
  8684. };
  8685. var ErrnoError = class _ErrnoError extends Error {
  8686. /**
  8687. * Represents a ZenFS error. Passed back to applications after a failed
  8688. * call to the ZenFS API.
  8689. *
  8690. * Error codes mirror those returned by regular Unix file operations, which is
  8691. * what Node returns.
  8692. * @param type The type of the error.
  8693. * @param message A descriptive error message.
  8694. */
  8695. constructor(errno, message = errorMessages[errno], path, syscall = "") {
  8696. super(message);
  8697. this.errno = errno;
  8698. this.path = path;
  8699. this.syscall = syscall;
  8700. this.code = Errno[errno];
  8701. this.message = `${this.code}: ${message}${this.path ? `, '${this.path}'` : ""}`;
  8702. }
  8703. static {
  8704. __name(this, "ErrnoError");
  8705. }
  8706. static fromJSON(json) {
  8707. const err = new _ErrnoError(json.errno, json.message, json.path, json.syscall);
  8708. err.code = json.code;
  8709. err.stack = json.stack;
  8710. return err;
  8711. }
  8712. static With(code, path, syscall) {
  8713. return new _ErrnoError(Errno[code], errorMessages[Errno[code]], path, syscall);
  8714. }
  8715. /**
  8716. * @return A friendly error message.
  8717. */
  8718. toString() {
  8719. return this.message;
  8720. }
  8721. toJSON() {
  8722. return {
  8723. errno: this.errno,
  8724. code: this.code,
  8725. path: this.path,
  8726. stack: this.stack,
  8727. message: this.message,
  8728. syscall: this.syscall
  8729. };
  8730. }
  8731. /**
  8732. * The size of the API error in buffer-form in bytes.
  8733. */
  8734. bufferSize() {
  8735. return 4 + JSON.stringify(this.toJSON()).length;
  8736. }
  8737. };
  8738. // src/emulation/constants.ts
  8739. var constants_exports = {};
  8740. __export(constants_exports, {
  8741. COPYFILE_EXCL: () => COPYFILE_EXCL,
  8742. COPYFILE_FICLONE: () => COPYFILE_FICLONE,
  8743. COPYFILE_FICLONE_FORCE: () => COPYFILE_FICLONE_FORCE,
  8744. F_OK: () => F_OK,
  8745. O_APPEND: () => O_APPEND,
  8746. O_CREAT: () => O_CREAT,
  8747. O_DIRECT: () => O_DIRECT,
  8748. O_DIRECTORY: () => O_DIRECTORY,
  8749. O_DSYNC: () => O_DSYNC,
  8750. O_EXCL: () => O_EXCL,
  8751. O_NOATIME: () => O_NOATIME,
  8752. O_NOCTTY: () => O_NOCTTY,
  8753. O_NOFOLLOW: () => O_NOFOLLOW,
  8754. O_NONBLOCK: () => O_NONBLOCK,
  8755. O_RDONLY: () => O_RDONLY,
  8756. O_RDWR: () => O_RDWR,
  8757. O_SYMLINK: () => O_SYMLINK,
  8758. O_SYNC: () => O_SYNC,
  8759. O_TRUNC: () => O_TRUNC,
  8760. O_WRONLY: () => O_WRONLY,
  8761. R_OK: () => R_OK,
  8762. S_IFBLK: () => S_IFBLK,
  8763. S_IFCHR: () => S_IFCHR,
  8764. S_IFDIR: () => S_IFDIR,
  8765. S_IFIFO: () => S_IFIFO,
  8766. S_IFLNK: () => S_IFLNK,
  8767. S_IFMT: () => S_IFMT,
  8768. S_IFREG: () => S_IFREG,
  8769. S_IFSOCK: () => S_IFSOCK,
  8770. S_IRGRP: () => S_IRGRP,
  8771. S_IROTH: () => S_IROTH,
  8772. S_IRUSR: () => S_IRUSR,
  8773. S_IRWXG: () => S_IRWXG,
  8774. S_IRWXO: () => S_IRWXO,
  8775. S_IRWXU: () => S_IRWXU,
  8776. S_ISGID: () => S_ISGID,
  8777. S_ISUID: () => S_ISUID,
  8778. S_ISVTX: () => S_ISVTX,
  8779. S_IWGRP: () => S_IWGRP,
  8780. S_IWOTH: () => S_IWOTH,
  8781. S_IWUSR: () => S_IWUSR,
  8782. S_IXGRP: () => S_IXGRP,
  8783. S_IXOTH: () => S_IXOTH,
  8784. S_IXUSR: () => S_IXUSR,
  8785. UV_FS_O_FILEMAP: () => UV_FS_O_FILEMAP,
  8786. W_OK: () => W_OK,
  8787. X_OK: () => X_OK
  8788. });
  8789. var F_OK = 0;
  8790. var R_OK = 4;
  8791. var W_OK = 2;
  8792. var X_OK = 1;
  8793. var COPYFILE_EXCL = 1;
  8794. var COPYFILE_FICLONE = 2;
  8795. var COPYFILE_FICLONE_FORCE = 4;
  8796. var O_RDONLY = 0;
  8797. var O_WRONLY = 1;
  8798. var O_RDWR = 2;
  8799. var O_CREAT = 64;
  8800. var O_EXCL = 128;
  8801. var O_NOCTTY = 256;
  8802. var O_TRUNC = 512;
  8803. var O_APPEND = 1024;
  8804. var O_DIRECTORY = 65536;
  8805. var O_NOATIME = 262144;
  8806. var O_NOFOLLOW = 131072;
  8807. var O_SYNC = 1052672;
  8808. var O_DSYNC = 4096;
  8809. var O_SYMLINK = 32768;
  8810. var O_DIRECT = 16384;
  8811. var O_NONBLOCK = 2048;
  8812. var S_IFMT = 61440;
  8813. var S_IFSOCK = 49152;
  8814. var S_IFLNK = 40960;
  8815. var S_IFREG = 32768;
  8816. var S_IFBLK = 24576;
  8817. var S_IFDIR = 16384;
  8818. var S_IFCHR = 8192;
  8819. var S_IFIFO = 4096;
  8820. var S_ISUID = 2048;
  8821. var S_ISGID = 1024;
  8822. var S_ISVTX = 512;
  8823. var S_IRWXU = 448;
  8824. var S_IRUSR = 256;
  8825. var S_IWUSR = 128;
  8826. var S_IXUSR = 64;
  8827. var S_IRWXG = 56;
  8828. var S_IRGRP = 32;
  8829. var S_IWGRP = 16;
  8830. var S_IXGRP = 8;
  8831. var S_IRWXO = 7;
  8832. var S_IROTH = 4;
  8833. var S_IWOTH = 2;
  8834. var S_IXOTH = 1;
  8835. var UV_FS_O_FILEMAP = 0;
  8836. // src/stats.ts
  8837. var FileType = /* @__PURE__ */ ((FileType2) => {
  8838. FileType2[FileType2["FILE"] = S_IFREG] = "FILE";
  8839. FileType2[FileType2["DIRECTORY"] = S_IFDIR] = "DIRECTORY";
  8840. FileType2[FileType2["SYMLINK"] = S_IFLNK] = "SYMLINK";
  8841. return FileType2;
  8842. })(FileType || {});
  8843. var StatsCommon = class {
  8844. /**
  8845. * Creates a new stats instance from a stats-like object. Can be used to copy stats (note)
  8846. */
  8847. constructor({ atimeMs, mtimeMs, ctimeMs, birthtimeMs, uid, gid, size, mode, ino } = {}) {
  8848. /**
  8849. * ID of device containing file
  8850. */
  8851. this.dev = this._convert(0);
  8852. /**
  8853. * inode number
  8854. */
  8855. this.ino = this._convert(0);
  8856. /**
  8857. * device ID (if special file)
  8858. */
  8859. this.rdev = this._convert(0);
  8860. /**
  8861. * number of hard links
  8862. */
  8863. this.nlink = this._convert(1);
  8864. /**
  8865. * blocksize for file system I/O
  8866. */
  8867. this.blksize = this._convert(4096);
  8868. /**
  8869. * user ID of owner
  8870. */
  8871. this.uid = this._convert(0);
  8872. /**
  8873. * group ID of owner
  8874. */
  8875. this.gid = this._convert(0);
  8876. const currentTime = Date.now();
  8877. const resolveT = /* @__PURE__ */ __name((val, _default) => typeof val == this._typename ? val : this._convert(typeof val == this._typename_inverse ? val : _default), "resolveT");
  8878. this.atimeMs = resolveT(atimeMs, currentTime);
  8879. this.mtimeMs = resolveT(mtimeMs, currentTime);
  8880. this.ctimeMs = resolveT(ctimeMs, currentTime);
  8881. this.birthtimeMs = resolveT(birthtimeMs, currentTime);
  8882. this.uid = resolveT(uid, 0);
  8883. this.gid = resolveT(gid, 0);
  8884. this.size = resolveT(size, 0);
  8885. this.ino = resolveT(ino, 0);
  8886. const itemType = Number(mode) & S_IFMT || FileType.FILE;
  8887. if (mode) {
  8888. this.mode = this._convert(mode);
  8889. } else {
  8890. switch (itemType) {
  8891. case FileType.FILE:
  8892. this.mode = this._convert(420);
  8893. break;
  8894. case FileType.DIRECTORY:
  8895. default:
  8896. this.mode = this._convert(511);
  8897. }
  8898. }
  8899. this.blocks = this._convert(Math.ceil(Number(size) / 512));
  8900. if ((this.mode & S_IFMT) == 0) {
  8901. this.mode = this.mode | this._convert(itemType);
  8902. }
  8903. }
  8904. static {
  8905. __name(this, "StatsCommon");
  8906. }
  8907. get _typename() {
  8908. return this._isBigint ? "bigint" : "number";
  8909. }
  8910. get _typename_inverse() {
  8911. return this._isBigint ? "number" : "bigint";
  8912. }
  8913. _convert(arg) {
  8914. return this._isBigint ? BigInt(arg) : Number(arg);
  8915. }
  8916. get atime() {
  8917. return new Date(Number(this.atimeMs));
  8918. }
  8919. set atime(value) {
  8920. this.atimeMs = this._convert(value.getTime());
  8921. }
  8922. get mtime() {
  8923. return new Date(Number(this.mtimeMs));
  8924. }
  8925. set mtime(value) {
  8926. this.mtimeMs = this._convert(value.getTime());
  8927. }
  8928. get ctime() {
  8929. return new Date(Number(this.ctimeMs));
  8930. }
  8931. set ctime(value) {
  8932. this.ctimeMs = this._convert(value.getTime());
  8933. }
  8934. get birthtime() {
  8935. return new Date(Number(this.birthtimeMs));
  8936. }
  8937. set birthtime(value) {
  8938. this.birthtimeMs = this._convert(value.getTime());
  8939. }
  8940. /**
  8941. * @returns true if this item is a file.
  8942. */
  8943. isFile() {
  8944. return (this.mode & S_IFMT) === S_IFREG;
  8945. }
  8946. /**
  8947. * @returns True if this item is a directory.
  8948. */
  8949. isDirectory() {
  8950. return (this.mode & S_IFMT) === S_IFDIR;
  8951. }
  8952. /**
  8953. * @returns true if this item is a symbolic link
  8954. */
  8955. isSymbolicLink() {
  8956. return (this.mode & S_IFMT) === S_IFLNK;
  8957. }
  8958. // Currently unsupported
  8959. isSocket() {
  8960. return false;
  8961. }
  8962. isBlockDevice() {
  8963. return false;
  8964. }
  8965. isCharacterDevice() {
  8966. return false;
  8967. }
  8968. isFIFO() {
  8969. return false;
  8970. }
  8971. /**
  8972. * Checks if a given user/group has access to this item
  8973. * @param mode The requested access, combination of W_OK, R_OK, and X_OK
  8974. * @param cred The requesting credentials
  8975. * @returns True if the request has access, false if the request does not
  8976. * @internal
  8977. */
  8978. hasAccess(mode, cred2) {
  8979. if (cred2.euid === 0 || cred2.egid === 0) {
  8980. return true;
  8981. }
  8982. const adjusted = (cred2.uid == this.uid ? S_IRWXU : 0) | (cred2.gid == this.gid ? S_IRWXG : 0) | S_IRWXO;
  8983. return (mode & this.mode & adjusted) == mode;
  8984. }
  8985. /**
  8986. * Convert the current stats object into a credentials object
  8987. * @internal
  8988. */
  8989. cred(uid = Number(this.uid), gid = Number(this.gid)) {
  8990. return {
  8991. uid,
  8992. gid,
  8993. suid: Number(this.uid),
  8994. sgid: Number(this.gid),
  8995. euid: uid,
  8996. egid: gid
  8997. };
  8998. }
  8999. /**
  9000. * Change the mode of the file. We use this helper function to prevent messing
  9001. * up the type of the file, which is encoded in mode.
  9002. * @internal
  9003. */
  9004. chmod(mode) {
  9005. this.mode = this._convert(this.mode & S_IFMT | mode);
  9006. }
  9007. /**
  9008. * Change the owner user/group of the file.
  9009. * This function makes sure it is a valid UID/GID (that is, a 32 unsigned int)
  9010. * @internal
  9011. */
  9012. chown(uid, gid) {
  9013. uid = Number(uid);
  9014. gid = Number(gid);
  9015. if (!isNaN(uid) && 0 <= uid && uid < 2 ** 32) {
  9016. this.uid = this._convert(uid);
  9017. }
  9018. if (!isNaN(gid) && 0 <= gid && gid < 2 ** 32) {
  9019. this.gid = this._convert(gid);
  9020. }
  9021. }
  9022. get atimeNs() {
  9023. return BigInt(this.atimeMs);
  9024. }
  9025. get mtimeNs() {
  9026. return BigInt(this.mtimeMs);
  9027. }
  9028. get ctimeNs() {
  9029. return BigInt(this.ctimeMs);
  9030. }
  9031. get birthtimeNs() {
  9032. return BigInt(this.birthtimeMs);
  9033. }
  9034. };
  9035. var Stats = class _Stats extends StatsCommon {
  9036. constructor() {
  9037. super(...arguments);
  9038. this._isBigint = false;
  9039. }
  9040. static {
  9041. __name(this, "Stats");
  9042. }
  9043. /**
  9044. * Clones the stats object.
  9045. * @deprecated use `new Stats(stats)`
  9046. */
  9047. static clone(stats) {
  9048. return new _Stats(stats);
  9049. }
  9050. };
  9051. var BigIntStats = class _BigIntStats extends StatsCommon {
  9052. constructor() {
  9053. super(...arguments);
  9054. this._isBigint = true;
  9055. }
  9056. static {
  9057. __name(this, "BigIntStats");
  9058. }
  9059. /**
  9060. * Clone a stats object.
  9061. * @deprecated use `new BigIntStats(stats)`
  9062. */
  9063. static clone(stats) {
  9064. return new _BigIntStats(stats);
  9065. }
  9066. };
  9067. var StatsFs = class {
  9068. constructor() {
  9069. /** Type of file system. */
  9070. this.type = 0;
  9071. /** Optimal transfer block size. */
  9072. this.bsize = 0;
  9073. /** Total data blocks in file system. */
  9074. this.blocks = 0;
  9075. /** Free blocks in file system. */
  9076. this.bfree = 0;
  9077. /** Available blocks for unprivileged users */
  9078. this.bavail = 0;
  9079. /** Total file nodes in file system. */
  9080. this.files = 0;
  9081. /** Free file nodes in file system. */
  9082. this.ffree = 0;
  9083. }
  9084. static {
  9085. __name(this, "StatsFs");
  9086. }
  9087. };
  9088. var BigIntStatsFs = class {
  9089. constructor() {
  9090. /** Type of file system. */
  9091. this.type = 0n;
  9092. /** Optimal transfer block size. */
  9093. this.bsize = 0n;
  9094. /** Total data blocks in file system. */
  9095. this.blocks = 0n;
  9096. /** Free blocks in file system. */
  9097. this.bfree = 0n;
  9098. /** Available blocks for unprivileged users */
  9099. this.bavail = 0n;
  9100. /** Total file nodes in file system. */
  9101. this.files = 0n;
  9102. /** Free file nodes in file system. */
  9103. this.ffree = 0n;
  9104. }
  9105. static {
  9106. __name(this, "BigIntStatsFs");
  9107. }
  9108. };
  9109. // src/inode.ts
  9110. var size_max = 2 ** 32 - 1;
  9111. var rootIno = 0n;
  9112. function _random() {
  9113. return Math.round(Math.random() * 2 ** 32).toString(16);
  9114. }
  9115. __name(_random, "_random");
  9116. function randomIno() {
  9117. return BigInt("0x" + _random() + _random());
  9118. }
  9119. __name(randomIno, "randomIno");
  9120. var Inode = class {
  9121. static {
  9122. __name(this, "Inode");
  9123. }
  9124. get data() {
  9125. return new Uint8Array(this.buffer);
  9126. }
  9127. constructor(buffer) {
  9128. const setDefaults = !buffer;
  9129. buffer ??= new ArrayBuffer(58 /* end */);
  9130. if (buffer?.byteLength < 58 /* end */) {
  9131. throw new RangeError(`Can not create an inode from a buffer less than ${58 /* end */} bytes`);
  9132. }
  9133. this.view = new DataView(buffer);
  9134. this.buffer = buffer;
  9135. if (!setDefaults) {
  9136. return;
  9137. }
  9138. this.ino = randomIno();
  9139. this.nlink = 1;
  9140. this.size = 4096;
  9141. const now = Date.now();
  9142. this.atimeMs = now;
  9143. this.mtimeMs = now;
  9144. this.ctimeMs = now;
  9145. this.birthtimeMs = now;
  9146. }
  9147. get ino() {
  9148. return this.view.getBigUint64(0 /* ino */, true);
  9149. }
  9150. set ino(value) {
  9151. this.view.setBigUint64(0 /* ino */, value, true);
  9152. }
  9153. get size() {
  9154. return this.view.getUint32(8 /* size */, true);
  9155. }
  9156. set size(value) {
  9157. this.view.setUint32(8 /* size */, value, true);
  9158. }
  9159. get mode() {
  9160. return this.view.getUint16(12 /* mode */, true);
  9161. }
  9162. set mode(value) {
  9163. this.view.setUint16(12 /* mode */, value, true);
  9164. }
  9165. get nlink() {
  9166. return this.view.getUint32(14 /* nlink */, true);
  9167. }
  9168. set nlink(value) {
  9169. this.view.setUint32(14 /* nlink */, value, true);
  9170. }
  9171. get uid() {
  9172. return this.view.getUint32(18 /* uid */, true);
  9173. }
  9174. set uid(value) {
  9175. this.view.setUint32(18 /* uid */, value, true);
  9176. }
  9177. get gid() {
  9178. return this.view.getUint32(22 /* gid */, true);
  9179. }
  9180. set gid(value) {
  9181. this.view.setUint32(22 /* gid */, value, true);
  9182. }
  9183. get atimeMs() {
  9184. return this.view.getFloat64(26 /* atime */, true);
  9185. }
  9186. set atimeMs(value) {
  9187. this.view.setFloat64(26 /* atime */, value, true);
  9188. }
  9189. get birthtimeMs() {
  9190. return this.view.getFloat64(34 /* birthtime */, true);
  9191. }
  9192. set birthtimeMs(value) {
  9193. this.view.setFloat64(34 /* birthtime */, value, true);
  9194. }
  9195. get mtimeMs() {
  9196. return this.view.getFloat64(42 /* mtime */, true);
  9197. }
  9198. set mtimeMs(value) {
  9199. this.view.setFloat64(42 /* mtime */, value, true);
  9200. }
  9201. get ctimeMs() {
  9202. return this.view.getFloat64(50 /* ctime */, true);
  9203. }
  9204. set ctimeMs(value) {
  9205. this.view.setFloat64(50 /* ctime */, value, true);
  9206. }
  9207. /**
  9208. * Handy function that converts the Inode to a Node Stats object.
  9209. */
  9210. toStats() {
  9211. return new Stats(this);
  9212. }
  9213. /**
  9214. * Updates the Inode using information from the stats object. Used by file
  9215. * systems at sync time, e.g.:
  9216. * - Program opens file and gets a File object.
  9217. * - Program mutates file. File object is responsible for maintaining
  9218. * metadata changes locally -- typically in a Stats object.
  9219. * - Program closes file. File object's metadata changes are synced with the
  9220. * file system.
  9221. * @return True if any changes have occurred.
  9222. */
  9223. update(stats) {
  9224. let hasChanged = false;
  9225. if (this.size !== stats.size) {
  9226. this.size = stats.size;
  9227. hasChanged = true;
  9228. }
  9229. if (this.mode !== stats.mode) {
  9230. this.mode = stats.mode;
  9231. hasChanged = true;
  9232. }
  9233. if (this.nlink !== stats.nlink) {
  9234. this.nlink = stats.nlink;
  9235. hasChanged = true;
  9236. }
  9237. if (this.uid !== stats.uid) {
  9238. this.uid = stats.uid;
  9239. hasChanged = true;
  9240. }
  9241. if (this.uid !== stats.uid) {
  9242. this.uid = stats.uid;
  9243. hasChanged = true;
  9244. }
  9245. if (this.atimeMs !== stats.atimeMs) {
  9246. this.atimeMs = stats.atimeMs;
  9247. hasChanged = true;
  9248. }
  9249. if (this.mtimeMs !== stats.mtimeMs) {
  9250. this.mtimeMs = stats.mtimeMs;
  9251. hasChanged = true;
  9252. }
  9253. if (this.ctimeMs !== stats.ctimeMs) {
  9254. this.ctimeMs = stats.ctimeMs;
  9255. hasChanged = true;
  9256. }
  9257. return hasChanged;
  9258. }
  9259. };
  9260. // src/file.ts
  9261. var ActionType = /* @__PURE__ */ ((ActionType2) => {
  9262. ActionType2[ActionType2["NOP"] = 0] = "NOP";
  9263. ActionType2[ActionType2["THROW"] = 1] = "THROW";
  9264. ActionType2[ActionType2["TRUNCATE"] = 2] = "TRUNCATE";
  9265. ActionType2[ActionType2["CREATE"] = 3] = "CREATE";
  9266. return ActionType2;
  9267. })(ActionType || {});
  9268. var validFlags = ["r", "r+", "rs", "rs+", "w", "wx", "w+", "wx+", "a", "ax", "a+", "ax+"];
  9269. function parseFlag(flag) {
  9270. if (typeof flag === "number") {
  9271. return flagToString(flag);
  9272. }
  9273. if (!validFlags.includes(flag)) {
  9274. throw new Error("Invalid flag string: " + flag);
  9275. }
  9276. return flag;
  9277. }
  9278. __name(parseFlag, "parseFlag");
  9279. function flagToString(flag) {
  9280. switch (flag) {
  9281. case O_RDONLY:
  9282. return "r";
  9283. case O_RDONLY | O_SYNC:
  9284. return "rs";
  9285. case O_RDWR:
  9286. return "r+";
  9287. case O_RDWR | O_SYNC:
  9288. return "rs+";
  9289. case O_TRUNC | O_CREAT | O_WRONLY:
  9290. return "w";
  9291. case O_TRUNC | O_CREAT | O_WRONLY | O_EXCL:
  9292. return "wx";
  9293. case O_TRUNC | O_CREAT | O_RDWR:
  9294. return "w+";
  9295. case O_TRUNC | O_CREAT | O_RDWR | O_EXCL:
  9296. return "wx+";
  9297. case O_APPEND | O_CREAT | O_WRONLY:
  9298. return "a";
  9299. case O_APPEND | O_CREAT | O_WRONLY | O_EXCL:
  9300. return "ax";
  9301. case O_APPEND | O_CREAT | O_RDWR:
  9302. return "a+";
  9303. case O_APPEND | O_CREAT | O_RDWR | O_EXCL:
  9304. return "ax+";
  9305. default:
  9306. throw new Error("Invalid flag number: " + flag);
  9307. }
  9308. }
  9309. __name(flagToString, "flagToString");
  9310. function flagToNumber(flag) {
  9311. switch (flag) {
  9312. case "r":
  9313. return O_RDONLY;
  9314. case "rs":
  9315. return O_RDONLY | O_SYNC;
  9316. case "r+":
  9317. return O_RDWR;
  9318. case "rs+":
  9319. return O_RDWR | O_SYNC;
  9320. case "w":
  9321. return O_TRUNC | O_CREAT | O_WRONLY;
  9322. case "wx":
  9323. return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL;
  9324. case "w+":
  9325. return O_TRUNC | O_CREAT | O_RDWR;
  9326. case "wx+":
  9327. return O_TRUNC | O_CREAT | O_RDWR | O_EXCL;
  9328. case "a":
  9329. return O_APPEND | O_CREAT | O_WRONLY;
  9330. case "ax":
  9331. return O_APPEND | O_CREAT | O_WRONLY | O_EXCL;
  9332. case "a+":
  9333. return O_APPEND | O_CREAT | O_RDWR;
  9334. case "ax+":
  9335. return O_APPEND | O_CREAT | O_RDWR | O_EXCL;
  9336. default:
  9337. throw new Error("Invalid flag string: " + flag);
  9338. }
  9339. }
  9340. __name(flagToNumber, "flagToNumber");
  9341. function flagToMode(flag) {
  9342. let mode = 0;
  9343. mode <<= 1;
  9344. mode += +isReadable(flag);
  9345. mode <<= 1;
  9346. mode += +isWriteable(flag);
  9347. mode <<= 1;
  9348. return mode;
  9349. }
  9350. __name(flagToMode, "flagToMode");
  9351. function isReadable(flag) {
  9352. return flag.indexOf("r") !== -1 || flag.indexOf("+") !== -1;
  9353. }
  9354. __name(isReadable, "isReadable");
  9355. function isWriteable(flag) {
  9356. return flag.indexOf("w") !== -1 || flag.indexOf("a") !== -1 || flag.indexOf("+") !== -1;
  9357. }
  9358. __name(isWriteable, "isWriteable");
  9359. function isTruncating(flag) {
  9360. return flag.indexOf("w") !== -1;
  9361. }
  9362. __name(isTruncating, "isTruncating");
  9363. function isAppendable(flag) {
  9364. return flag.indexOf("a") !== -1;
  9365. }
  9366. __name(isAppendable, "isAppendable");
  9367. function isSynchronous(flag) {
  9368. return flag.indexOf("s") !== -1;
  9369. }
  9370. __name(isSynchronous, "isSynchronous");
  9371. function isExclusive(flag) {
  9372. return flag.indexOf("x") !== -1;
  9373. }
  9374. __name(isExclusive, "isExclusive");
  9375. function pathExistsAction(flag) {
  9376. if (isExclusive(flag)) {
  9377. return 1 /* THROW */;
  9378. }
  9379. if (isTruncating(flag)) {
  9380. return 2 /* TRUNCATE */;
  9381. }
  9382. return 0 /* NOP */;
  9383. }
  9384. __name(pathExistsAction, "pathExistsAction");
  9385. function pathNotExistsAction(flag) {
  9386. if ((isWriteable(flag) || isAppendable(flag)) && flag !== "r+") {
  9387. return 3 /* CREATE */;
  9388. }
  9389. return 1 /* THROW */;
  9390. }
  9391. __name(pathNotExistsAction, "pathNotExistsAction");
  9392. var File = class {
  9393. static {
  9394. __name(this, "File");
  9395. }
  9396. [Symbol.asyncDispose]() {
  9397. return this.close();
  9398. }
  9399. [Symbol.dispose]() {
  9400. return this.closeSync();
  9401. }
  9402. /**
  9403. * Asynchronous `datasync`.
  9404. *
  9405. * Default implementation maps to `sync`.
  9406. */
  9407. datasync() {
  9408. return this.sync();
  9409. }
  9410. /**
  9411. * Synchronous `datasync`.
  9412. *
  9413. * Default implementation maps to `syncSync`.
  9414. */
  9415. datasyncSync() {
  9416. return this.syncSync();
  9417. }
  9418. };
  9419. var PreloadFile = class extends File {
  9420. /**
  9421. * Creates a file with the given path and, optionally, the given contents. Note
  9422. * that, if contents is specified, it will be mutated by the file!
  9423. * @param _mode The mode that the file was opened using.
  9424. * Dictates permissions and where the file pointer starts.
  9425. * @param stats The stats object for the given file.
  9426. * PreloadFile will mutate this object. Note that this object must contain
  9427. * the appropriate mode that the file was opened as.
  9428. * @param buffer A buffer containing the entire
  9429. * contents of the file. PreloadFile will mutate this buffer. If not
  9430. * specified, we assume it is a new file.
  9431. */
  9432. constructor(fs, path, flag, stats, _buffer = new Uint8Array(new ArrayBuffer(0, { maxByteLength: size_max }))) {
  9433. super();
  9434. this.fs = fs;
  9435. this.path = path;
  9436. this.flag = flag;
  9437. this.stats = stats;
  9438. this._buffer = _buffer;
  9439. this._position = 0;
  9440. this._dirty = false;
  9441. if (this.stats.size == _buffer.byteLength) {
  9442. return;
  9443. }
  9444. if (isReadable(this.flag)) {
  9445. throw new Error(`Size mismatch: buffer length ${_buffer.byteLength}, stats size ${this.stats.size}`);
  9446. }
  9447. this._dirty = true;
  9448. }
  9449. static {
  9450. __name(this, "PreloadFile");
  9451. }
  9452. /**
  9453. * Get the underlying buffer for this file. Mutating not recommended and will mess up dirty tracking.
  9454. */
  9455. get buffer() {
  9456. return this._buffer;
  9457. }
  9458. /**
  9459. * Get the current file position.
  9460. *
  9461. * We emulate the following bug mentioned in the Node documentation:
  9462. * > On Linux, positional writes don't work when the file is opened in append
  9463. * mode. The kernel ignores the position argument and always appends the data
  9464. * to the end of the file.
  9465. * @return The current file position.
  9466. */
  9467. get position() {
  9468. if (isAppendable(this.flag)) {
  9469. return this.stats.size;
  9470. }
  9471. return this._position;
  9472. }
  9473. /**
  9474. * Set the file position.
  9475. * @param newPos new position
  9476. */
  9477. set position(newPos) {
  9478. this._position = newPos;
  9479. }
  9480. async sync() {
  9481. if (!this.isDirty()) {
  9482. return;
  9483. }
  9484. await this.fs.sync(this.path, this._buffer, this.stats);
  9485. this._dirty = false;
  9486. }
  9487. syncSync() {
  9488. if (!this.isDirty()) {
  9489. return;
  9490. }
  9491. this.fs.syncSync(this.path, this._buffer, this.stats);
  9492. this._dirty = false;
  9493. }
  9494. async close() {
  9495. await this.sync();
  9496. }
  9497. closeSync() {
  9498. this.syncSync();
  9499. }
  9500. /**
  9501. * Asynchronous `stat`.
  9502. */
  9503. async stat() {
  9504. return new Stats(this.stats);
  9505. }
  9506. /**
  9507. * Synchronous `stat`.
  9508. */
  9509. statSync() {
  9510. return new Stats(this.stats);
  9511. }
  9512. /**
  9513. * Asynchronous truncate.
  9514. * @param len
  9515. */
  9516. async truncate(len) {
  9517. this.truncateSync(len);
  9518. if (isSynchronous(this.flag)) {
  9519. return this.sync();
  9520. }
  9521. }
  9522. /**
  9523. * Synchronous truncate.
  9524. * @param len
  9525. */
  9526. truncateSync(len) {
  9527. this._dirty = true;
  9528. if (!isWriteable(this.flag)) {
  9529. throw new ErrnoError(1 /* EPERM */, "File not opened with a writeable mode.");
  9530. }
  9531. this.stats.mtimeMs = Date.now();
  9532. if (len > this._buffer.length) {
  9533. const buf = new Uint8Array(len - this._buffer.length);
  9534. this.writeSync(buf, 0, buf.length, this._buffer.length);
  9535. if (isSynchronous(this.flag)) {
  9536. this.syncSync();
  9537. }
  9538. return;
  9539. }
  9540. this.stats.size = len;
  9541. this._buffer = this._buffer.subarray(0, len);
  9542. if (isSynchronous(this.flag)) {
  9543. this.syncSync();
  9544. }
  9545. }
  9546. /**
  9547. * Write buffer to the file.
  9548. * Note that it is unsafe to use fs.write multiple times on the same file
  9549. * without waiting for the callback.
  9550. * @param buffer Uint8Array containing the data to write to
  9551. * the file.
  9552. * @param offset Offset in the buffer to start reading data from.
  9553. * @param length The amount of bytes to write to the file.
  9554. * @param position Offset from the beginning of the file where this
  9555. * data should be written. If position is null, the data will be written at
  9556. * the current position.
  9557. */
  9558. async write(buffer, offset = 0, length = this.stats.size, position = 0) {
  9559. const bytesWritten = this.writeSync(buffer, offset, length, position);
  9560. await this.sync();
  9561. return bytesWritten;
  9562. }
  9563. /**
  9564. * Write buffer to the file.
  9565. * Note that it is unsafe to use fs.writeSync multiple times on the same file
  9566. * without waiting for the callback.
  9567. * @param buffer Uint8Array containing the data to write to
  9568. * the file.
  9569. * @param offset Offset in the buffer to start reading data from.
  9570. * @param length The amount of bytes to write to the file.
  9571. * @param position Offset from the beginning of the file where this
  9572. * data should be written. If position is null, the data will be written at
  9573. * the current position.
  9574. * @returns bytes written
  9575. */
  9576. writeSync(buffer, offset = 0, length = this.stats.size, position = 0) {
  9577. this._dirty = true;
  9578. position ??= this.position;
  9579. if (!isWriteable(this.flag)) {
  9580. throw new ErrnoError(1 /* EPERM */, "File not opened with a writeable mode.");
  9581. }
  9582. const endFp = position + length;
  9583. if (endFp > this.stats.size) {
  9584. this.stats.size = endFp;
  9585. if (endFp > this._buffer.byteLength) {
  9586. if (this._buffer.buffer.resizable && this._buffer.buffer.maxByteLength <= endFp) {
  9587. this._buffer.buffer.resize(endFp);
  9588. } else {
  9589. const newBuffer = new Uint8Array(new ArrayBuffer(endFp, { maxByteLength: size_max }));
  9590. newBuffer.set(this._buffer);
  9591. this._buffer = newBuffer;
  9592. }
  9593. }
  9594. }
  9595. const slice = buffer.slice(offset, offset + length);
  9596. this._buffer.set(slice, position);
  9597. const bytesWritten = slice.byteLength;
  9598. this.stats.mtimeMs = Date.now();
  9599. if (isSynchronous(this.flag)) {
  9600. this.syncSync();
  9601. return bytesWritten;
  9602. }
  9603. this.position = position + bytesWritten;
  9604. return bytesWritten;
  9605. }
  9606. /**
  9607. * Read data from the file.
  9608. * @param buffer The buffer that the data will be
  9609. * written to.
  9610. * @param offset The offset within the buffer where writing will
  9611. * start.
  9612. * @param length An integer specifying the number of bytes to read.
  9613. * @param position An integer specifying where to begin reading from
  9614. * in the file. If position is null, data will be read from the current file
  9615. * position.
  9616. */
  9617. async read(buffer, offset = 0, length = this.stats.size, position = 0) {
  9618. return { bytesRead: this.readSync(buffer, offset, length, position), buffer };
  9619. }
  9620. /**
  9621. * Read data from the file.
  9622. * @param buffer The buffer that the data will be
  9623. * written to.
  9624. * @param offset The offset within the buffer where writing will start.
  9625. * @param length An integer specifying the number of bytes to read.
  9626. * @param position An integer specifying where to begin reading from
  9627. * in the file. If position is null, data will be read from the current file
  9628. * position.
  9629. * @returns number of bytes written
  9630. */
  9631. readSync(buffer, offset = 0, length = this.stats.size, position) {
  9632. if (!isReadable(this.flag)) {
  9633. throw new ErrnoError(1 /* EPERM */, "File not opened with a readable mode.");
  9634. }
  9635. position ??= this.position;
  9636. let end = position + length;
  9637. if (end > this.stats.size) {
  9638. end = position + Math.max(this.stats.size - position, 0);
  9639. }
  9640. this.stats.atimeMs = Date.now();
  9641. this._position = end;
  9642. const bytesRead = end - position;
  9643. if (bytesRead == 0) {
  9644. return bytesRead;
  9645. }
  9646. new Uint8Array(buffer.buffer, offset, length).set(this._buffer.slice(position, end));
  9647. return bytesRead;
  9648. }
  9649. /**
  9650. * Asynchronous `fchmod`.
  9651. * @param mode the mode
  9652. */
  9653. async chmod(mode) {
  9654. this.chmodSync(mode);
  9655. }
  9656. /**
  9657. * Synchronous `fchmod`.
  9658. * @param mode
  9659. */
  9660. chmodSync(mode) {
  9661. this._dirty = true;
  9662. this.stats.chmod(mode);
  9663. this.syncSync();
  9664. }
  9665. /**
  9666. * Asynchronous `fchown`.
  9667. * @param uid
  9668. * @param gid
  9669. */
  9670. async chown(uid, gid) {
  9671. this.chownSync(uid, gid);
  9672. }
  9673. /**
  9674. * Synchronous `fchown`.
  9675. * @param uid
  9676. * @param gid
  9677. */
  9678. chownSync(uid, gid) {
  9679. this._dirty = true;
  9680. this.stats.chown(uid, gid);
  9681. this.syncSync();
  9682. }
  9683. async utimes(atime, mtime) {
  9684. this.utimesSync(atime, mtime);
  9685. }
  9686. utimesSync(atime, mtime) {
  9687. this._dirty = true;
  9688. this.stats.atime = atime;
  9689. this.stats.mtime = mtime;
  9690. this.syncSync();
  9691. }
  9692. isDirty() {
  9693. return this._dirty;
  9694. }
  9695. /**
  9696. * Resets the dirty bit. Should only be called after a sync has completed successfully.
  9697. */
  9698. resetDirty() {
  9699. this._dirty = false;
  9700. }
  9701. _setType(type) {
  9702. this._dirty = true;
  9703. this.stats.mode = this.stats.mode & ~S_IFMT | type;
  9704. return this.sync();
  9705. }
  9706. _setTypeSync(type) {
  9707. this._dirty = true;
  9708. this.stats.mode = this.stats.mode & ~S_IFMT | type;
  9709. this.syncSync();
  9710. }
  9711. };
  9712. var NoSyncFile = class extends PreloadFile {
  9713. static {
  9714. __name(this, "NoSyncFile");
  9715. }
  9716. constructor(_fs, _path, _flag, _stat, contents) {
  9717. super(_fs, _path, _flag, _stat, contents);
  9718. }
  9719. /**
  9720. * Asynchronous sync. Doesn't do anything, simply calls the cb.
  9721. */
  9722. async sync() {
  9723. return;
  9724. }
  9725. /**
  9726. * Synchronous sync. Doesn't do anything.
  9727. */
  9728. syncSync() {
  9729. }
  9730. /**
  9731. * Asynchronous close. Doesn't do anything, simply calls the cb.
  9732. */
  9733. async close() {
  9734. return;
  9735. }
  9736. /**
  9737. * Synchronous close. Doesn't do anything.
  9738. */
  9739. closeSync() {
  9740. }
  9741. };
  9742. // src/cred.ts
  9743. var rootCred = {
  9744. uid: 0,
  9745. gid: 0,
  9746. suid: 0,
  9747. sgid: 0,
  9748. euid: 0,
  9749. egid: 0
  9750. };
  9751. // src/emulation/path.ts
  9752. var cwd = "/";
  9753. function normalizeString(path, allowAboveRoot) {
  9754. let res = "";
  9755. let lastSegmentLength = 0;
  9756. let lastSlash = -1;
  9757. let dots = 0;
  9758. let char = "\0";
  9759. for (let i = 0; i <= path.length; ++i) {
  9760. if (i < path.length) {
  9761. char = path[i];
  9762. } else if (char == "/") {
  9763. break;
  9764. } else {
  9765. char = "/";
  9766. }
  9767. if (char == "/") {
  9768. if (lastSlash === i - 1 || dots === 1) {
  9769. } else if (dots === 2) {
  9770. if (res.length < 2 || lastSegmentLength !== 2 || res.at(-1) !== "." || res.at(-2) !== ".") {
  9771. if (res.length > 2) {
  9772. const lastSlashIndex = res.lastIndexOf("/");
  9773. if (lastSlashIndex === -1) {
  9774. res = "";
  9775. lastSegmentLength = 0;
  9776. } else {
  9777. res = res.slice(0, lastSlashIndex);
  9778. lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
  9779. }
  9780. lastSlash = i;
  9781. dots = 0;
  9782. continue;
  9783. } else if (res.length !== 0) {
  9784. res = "";
  9785. lastSegmentLength = 0;
  9786. lastSlash = i;
  9787. dots = 0;
  9788. continue;
  9789. }
  9790. }
  9791. if (allowAboveRoot) {
  9792. res += res.length > 0 ? "/.." : "..";
  9793. lastSegmentLength = 2;
  9794. }
  9795. } else {
  9796. if (res.length > 0) res += "/" + path.slice(lastSlash + 1, i);
  9797. else res = path.slice(lastSlash + 1, i);
  9798. lastSegmentLength = i - lastSlash - 1;
  9799. }
  9800. lastSlash = i;
  9801. dots = 0;
  9802. } else if (char === "." && dots !== -1) {
  9803. ++dots;
  9804. } else {
  9805. dots = -1;
  9806. }
  9807. }
  9808. return res;
  9809. }
  9810. __name(normalizeString, "normalizeString");
  9811. function resolve(...parts) {
  9812. let resolved = "";
  9813. for (const part of [...parts.reverse(), cwd]) {
  9814. if (!part.length) {
  9815. continue;
  9816. }
  9817. resolved = `${part}/${resolved}`;
  9818. if (part.startsWith("/")) {
  9819. break;
  9820. }
  9821. }
  9822. const absolute = resolved.startsWith("/");
  9823. resolved = normalizeString(resolved, !absolute);
  9824. if (absolute) {
  9825. return `/${resolved}`;
  9826. }
  9827. return resolved.length ? resolved : "/";
  9828. }
  9829. __name(resolve, "resolve");
  9830. function normalize(path) {
  9831. if (!path.length) return ".";
  9832. const isAbsolute = path.startsWith("/");
  9833. const trailingSeparator = path.endsWith("/");
  9834. path = normalizeString(path, !isAbsolute);
  9835. if (!path.length) {
  9836. if (isAbsolute) return "/";
  9837. return trailingSeparator ? "./" : ".";
  9838. }
  9839. if (trailingSeparator) path += "/";
  9840. return isAbsolute ? `/${path}` : path;
  9841. }
  9842. __name(normalize, "normalize");
  9843. function join(...parts) {
  9844. if (!parts.length) return ".";
  9845. const joined = parts.join("/");
  9846. if (!joined?.length) return ".";
  9847. return normalize(joined);
  9848. }
  9849. __name(join, "join");
  9850. function dirname(path) {
  9851. if (path.length === 0) return ".";
  9852. const hasRoot = path[0] === "/";
  9853. let end = -1;
  9854. let matchedSlash = true;
  9855. for (let i = path.length - 1; i >= 1; --i) {
  9856. if (path[i] === "/") {
  9857. if (!matchedSlash) {
  9858. end = i;
  9859. break;
  9860. }
  9861. } else {
  9862. matchedSlash = false;
  9863. }
  9864. }
  9865. if (end === -1) return hasRoot ? "/" : ".";
  9866. if (hasRoot && end === 1) return "//";
  9867. return path.slice(0, end);
  9868. }
  9869. __name(dirname, "dirname");
  9870. function basename(path, suffix) {
  9871. let start = 0;
  9872. let end = -1;
  9873. let matchedSlash = true;
  9874. if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) {
  9875. if (suffix === path) return "";
  9876. let extIdx = suffix.length - 1;
  9877. let firstNonSlashEnd = -1;
  9878. for (let i = path.length - 1; i >= 0; --i) {
  9879. if (path[i] === "/") {
  9880. if (!matchedSlash) {
  9881. start = i + 1;
  9882. break;
  9883. }
  9884. } else {
  9885. if (firstNonSlashEnd === -1) {
  9886. matchedSlash = false;
  9887. firstNonSlashEnd = i + 1;
  9888. }
  9889. if (extIdx >= 0) {
  9890. if (path[i] === suffix[extIdx]) {
  9891. if (--extIdx === -1) {
  9892. end = i;
  9893. }
  9894. } else {
  9895. extIdx = -1;
  9896. end = firstNonSlashEnd;
  9897. }
  9898. }
  9899. }
  9900. }
  9901. if (start === end) end = firstNonSlashEnd;
  9902. else if (end === -1) end = path.length;
  9903. return path.slice(start, end);
  9904. }
  9905. for (let i = path.length - 1; i >= 0; --i) {
  9906. if (path[i] === "/") {
  9907. if (!matchedSlash) {
  9908. start = i + 1;
  9909. break;
  9910. }
  9911. } else if (end === -1) {
  9912. matchedSlash = false;
  9913. end = i + 1;
  9914. }
  9915. }
  9916. if (end === -1) return "";
  9917. return path.slice(start, end);
  9918. }
  9919. __name(basename, "basename");
  9920. function parse(path) {
  9921. const isAbsolute = path.startsWith("/");
  9922. const ret = { root: isAbsolute ? "/" : "", dir: "", base: "", ext: "", name: "" };
  9923. if (path.length === 0) return ret;
  9924. const start = isAbsolute ? 1 : 0;
  9925. let startDot = -1;
  9926. let startPart = 0;
  9927. let end = -1;
  9928. let matchedSlash = true;
  9929. let i = path.length - 1;
  9930. let preDotState = 0;
  9931. for (; i >= start; --i) {
  9932. if (path[i] === "/") {
  9933. if (!matchedSlash) {
  9934. startPart = i + 1;
  9935. break;
  9936. }
  9937. continue;
  9938. }
  9939. if (end === -1) {
  9940. matchedSlash = false;
  9941. end = i + 1;
  9942. }
  9943. if (path[i] === ".") {
  9944. if (startDot === -1) startDot = i;
  9945. else if (preDotState !== 1) preDotState = 1;
  9946. } else if (startDot !== -1) {
  9947. preDotState = -1;
  9948. }
  9949. }
  9950. if (end !== -1) {
  9951. const start2 = startPart === 0 && isAbsolute ? 1 : startPart;
  9952. if (startDot === -1 || // We saw a non-dot character immediately before the dot
  9953. preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
  9954. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  9955. ret.base = ret.name = path.slice(start2, end);
  9956. } else {
  9957. ret.name = path.slice(start2, startDot);
  9958. ret.base = path.slice(start2, end);
  9959. ret.ext = path.slice(startDot, end);
  9960. }
  9961. }
  9962. if (startPart > 0) ret.dir = path.slice(0, startPart - 1);
  9963. else if (isAbsolute) ret.dir = "/";
  9964. return ret;
  9965. }
  9966. __name(parse, "parse");
  9967. // src/filesystem.ts
  9968. var FileSystem = class {
  9969. static {
  9970. __name(this, "FileSystem");
  9971. }
  9972. /**
  9973. * Get metadata about the current file syste,
  9974. */
  9975. metadata() {
  9976. return {
  9977. name: this.constructor.name,
  9978. readonly: false,
  9979. totalSpace: 0,
  9980. freeSpace: 0
  9981. };
  9982. }
  9983. constructor(options) {
  9984. }
  9985. async ready() {
  9986. }
  9987. /**
  9988. * Test whether or not the given path exists by checking with the file system.
  9989. */
  9990. async exists(path, cred2) {
  9991. try {
  9992. await this.stat(path, cred2);
  9993. return true;
  9994. } catch (e) {
  9995. return false;
  9996. }
  9997. }
  9998. /**
  9999. * Test whether or not the given path exists by checking with the file system.
  10000. */
  10001. existsSync(path, cred2) {
  10002. try {
  10003. this.statSync(path, cred2);
  10004. return true;
  10005. } catch (e) {
  10006. return false;
  10007. }
  10008. }
  10009. };
  10010. function Sync(FS) {
  10011. class _SyncFS extends FS {
  10012. static {
  10013. __name(this, "_SyncFS");
  10014. }
  10015. async exists(path, cred2) {
  10016. return this.existsSync(path, cred2);
  10017. }
  10018. async rename(oldPath, newPath, cred2) {
  10019. return this.renameSync(oldPath, newPath, cred2);
  10020. }
  10021. async stat(path, cred2) {
  10022. return this.statSync(path, cred2);
  10023. }
  10024. async createFile(path, flag, mode, cred2) {
  10025. return this.createFileSync(path, flag, mode, cred2);
  10026. }
  10027. async openFile(path, flag, cred2) {
  10028. return this.openFileSync(path, flag, cred2);
  10029. }
  10030. async unlink(path, cred2) {
  10031. return this.unlinkSync(path, cred2);
  10032. }
  10033. async rmdir(path, cred2) {
  10034. return this.rmdirSync(path, cred2);
  10035. }
  10036. async mkdir(path, mode, cred2) {
  10037. return this.mkdirSync(path, mode, cred2);
  10038. }
  10039. async readdir(path, cred2) {
  10040. return this.readdirSync(path, cred2);
  10041. }
  10042. async link(srcpath, dstpath, cred2) {
  10043. return this.linkSync(srcpath, dstpath, cred2);
  10044. }
  10045. async sync(path, data, stats) {
  10046. return this.syncSync(path, data, stats);
  10047. }
  10048. }
  10049. return _SyncFS;
  10050. }
  10051. __name(Sync, "Sync");
  10052. function Async(FS) {
  10053. class _AsyncFS extends FS {
  10054. constructor() {
  10055. super(...arguments);
  10056. /**
  10057. * Queue of pending asynchronous operations.
  10058. */
  10059. this._queue = [];
  10060. this._isInitialized = false;
  10061. }
  10062. static {
  10063. __name(this, "_AsyncFS");
  10064. }
  10065. get _queueRunning() {
  10066. return !!this._queue.length;
  10067. }
  10068. queueDone() {
  10069. return new Promise((resolve2) => {
  10070. const check = /* @__PURE__ */ __name(() => this._queueRunning ? setTimeout(check) : resolve2(), "check");
  10071. check();
  10072. });
  10073. }
  10074. async ready() {
  10075. await this._sync.ready();
  10076. await super.ready();
  10077. if (this._isInitialized) {
  10078. return;
  10079. }
  10080. try {
  10081. await this.crossCopy("/");
  10082. this._isInitialized = true;
  10083. } catch (e) {
  10084. this._isInitialized = false;
  10085. throw e;
  10086. }
  10087. }
  10088. renameSync(oldPath, newPath, cred2) {
  10089. this._sync.renameSync(oldPath, newPath, cred2);
  10090. this.queue("rename", oldPath, newPath, cred2);
  10091. }
  10092. statSync(path, cred2) {
  10093. return this._sync.statSync(path, cred2);
  10094. }
  10095. createFileSync(path, flag, mode, cred2) {
  10096. this._sync.createFileSync(path, flag, mode, cred2);
  10097. this.queue("createFile", path, flag, mode, cred2);
  10098. return this.openFileSync(path, flag, cred2);
  10099. }
  10100. openFileSync(path, flag, cred2) {
  10101. const file = this._sync.openFileSync(path, flag, cred2);
  10102. const stats = file.statSync();
  10103. const buffer = new Uint8Array(stats.size);
  10104. file.readSync(buffer);
  10105. return new PreloadFile(this, path, flag, stats, buffer);
  10106. }
  10107. unlinkSync(path, cred2) {
  10108. this._sync.unlinkSync(path, cred2);
  10109. this.queue("unlink", path, cred2);
  10110. }
  10111. rmdirSync(path, cred2) {
  10112. this._sync.rmdirSync(path, cred2);
  10113. this.queue("rmdir", path, cred2);
  10114. }
  10115. mkdirSync(path, mode, cred2) {
  10116. this._sync.mkdirSync(path, mode, cred2);
  10117. this.queue("mkdir", path, mode, cred2);
  10118. }
  10119. readdirSync(path, cred2) {
  10120. return this._sync.readdirSync(path, cred2);
  10121. }
  10122. linkSync(srcpath, dstpath, cred2) {
  10123. this._sync.linkSync(srcpath, dstpath, cred2);
  10124. this.queue("link", srcpath, dstpath, cred2);
  10125. }
  10126. syncSync(path, data, stats) {
  10127. this._sync.syncSync(path, data, stats);
  10128. this.queue("sync", path, data, stats);
  10129. }
  10130. existsSync(path, cred2) {
  10131. return this._sync.existsSync(path, cred2);
  10132. }
  10133. /**
  10134. * @internal
  10135. */
  10136. async crossCopy(path) {
  10137. const stats = await this.stat(path, rootCred);
  10138. if (stats.isDirectory()) {
  10139. if (path !== "/") {
  10140. const stats2 = await this.stat(path, rootCred);
  10141. this._sync.mkdirSync(path, stats2.mode, stats2.cred());
  10142. }
  10143. const files = await this.readdir(path, rootCred);
  10144. for (const file of files) {
  10145. await this.crossCopy(join(path, file));
  10146. }
  10147. } else {
  10148. const asyncFile = await this.openFile(path, parseFlag("r"), rootCred);
  10149. const syncFile = this._sync.createFileSync(path, parseFlag("w"), stats.mode, stats.cred());
  10150. try {
  10151. const buffer = new Uint8Array(stats.size);
  10152. await asyncFile.read(buffer);
  10153. syncFile.writeSync(buffer, 0, stats.size);
  10154. } finally {
  10155. await asyncFile.close();
  10156. syncFile.closeSync();
  10157. }
  10158. }
  10159. }
  10160. /**
  10161. * @internal
  10162. */
  10163. async _next() {
  10164. if (!this._queueRunning) {
  10165. return;
  10166. }
  10167. const [method, ...args] = this._queue.shift();
  10168. await this[method](...args);
  10169. await this._next();
  10170. }
  10171. /**
  10172. * @internal
  10173. */
  10174. queue(...op) {
  10175. this._queue.push(op);
  10176. this._next();
  10177. }
  10178. }
  10179. return _AsyncFS;
  10180. }
  10181. __name(Async, "Async");
  10182. function Readonly(FS) {
  10183. class _ReadonlyFS extends FS {
  10184. static {
  10185. __name(this, "_ReadonlyFS");
  10186. }
  10187. metadata() {
  10188. return { ...super.metadata(), readonly: true };
  10189. }
  10190. /* eslint-disable @typescript-eslint/no-unused-vars */
  10191. async rename(oldPath, newPath, cred2) {
  10192. throw new ErrnoError(30 /* EROFS */);
  10193. }
  10194. renameSync(oldPath, newPath, cred2) {
  10195. throw new ErrnoError(30 /* EROFS */);
  10196. }
  10197. async createFile(path, flag, mode, cred2) {
  10198. throw new ErrnoError(30 /* EROFS */);
  10199. }
  10200. createFileSync(path, flag, mode, cred2) {
  10201. throw new ErrnoError(30 /* EROFS */);
  10202. }
  10203. async unlink(path, cred2) {
  10204. throw new ErrnoError(30 /* EROFS */);
  10205. }
  10206. unlinkSync(path, cred2) {
  10207. throw new ErrnoError(30 /* EROFS */);
  10208. }
  10209. async rmdir(path, cred2) {
  10210. throw new ErrnoError(30 /* EROFS */);
  10211. }
  10212. rmdirSync(path, cred2) {
  10213. throw new ErrnoError(30 /* EROFS */);
  10214. }
  10215. async mkdir(path, mode, cred2) {
  10216. throw new ErrnoError(30 /* EROFS */);
  10217. }
  10218. mkdirSync(path, mode, cred2) {
  10219. throw new ErrnoError(30 /* EROFS */);
  10220. }
  10221. async link(srcpath, dstpath, cred2) {
  10222. throw new ErrnoError(30 /* EROFS */);
  10223. }
  10224. linkSync(srcpath, dstpath, cred2) {
  10225. throw new ErrnoError(30 /* EROFS */);
  10226. }
  10227. async sync(path, data, stats) {
  10228. throw new ErrnoError(30 /* EROFS */);
  10229. }
  10230. syncSync(path, data, stats) {
  10231. throw new ErrnoError(30 /* EROFS */);
  10232. }
  10233. /* eslint-enable @typescript-eslint/no-unused-vars */
  10234. }
  10235. return _ReadonlyFS;
  10236. }
  10237. __name(Readonly, "Readonly");
  10238. // src/utils.ts
  10239. function mkdirpSync(path, mode, cred2, fs) {
  10240. if (!fs.existsSync(path, cred2)) {
  10241. mkdirpSync(dirname(path), mode, cred2, fs);
  10242. fs.mkdirSync(path, mode, cred2);
  10243. }
  10244. }
  10245. __name(mkdirpSync, "mkdirpSync");
  10246. function _min(d0, d1, d2, bx, ay) {
  10247. return Math.min(d0 + 1, d1 + 1, d2 + 1, bx === ay ? d1 : d1 + 1);
  10248. }
  10249. __name(_min, "_min");
  10250. function levenshtein(a, b) {
  10251. if (a === b) {
  10252. return 0;
  10253. }
  10254. if (a.length > b.length) {
  10255. [a, b] = [b, a];
  10256. }
  10257. let la = a.length;
  10258. let lb = b.length;
  10259. while (la > 0 && a.charCodeAt(la - 1) === b.charCodeAt(lb - 1)) {
  10260. la--;
  10261. lb--;
  10262. }
  10263. let offset = 0;
  10264. while (offset < la && a.charCodeAt(offset) === b.charCodeAt(offset)) {
  10265. offset++;
  10266. }
  10267. la -= offset;
  10268. lb -= offset;
  10269. if (la === 0 || lb === 1) {
  10270. return lb;
  10271. }
  10272. const vector = new Array(la << 1);
  10273. for (let y = 0; y < la; ) {
  10274. vector[la + y] = a.charCodeAt(offset + y);
  10275. vector[y] = ++y;
  10276. }
  10277. let x;
  10278. let d0;
  10279. let d1;
  10280. let d2;
  10281. let d3;
  10282. for (x = 0; x + 3 < lb; ) {
  10283. const bx0 = b.charCodeAt(offset + (d0 = x));
  10284. const bx1 = b.charCodeAt(offset + (d1 = x + 1));
  10285. const bx2 = b.charCodeAt(offset + (d2 = x + 2));
  10286. const bx3 = b.charCodeAt(offset + (d3 = x + 3));
  10287. let dd2 = x += 4;
  10288. for (let y = 0; y < la; ) {
  10289. const ay = vector[la + y];
  10290. const dy = vector[y];
  10291. d0 = _min(dy, d0, d1, bx0, ay);
  10292. d1 = _min(d0, d1, d2, bx1, ay);
  10293. d2 = _min(d1, d2, d3, bx2, ay);
  10294. dd2 = _min(d2, d3, dd2, bx3, ay);
  10295. vector[y++] = dd2;
  10296. d3 = d2;
  10297. d2 = d1;
  10298. d1 = d0;
  10299. d0 = dy;
  10300. }
  10301. }
  10302. let dd = 0;
  10303. for (; x < lb; ) {
  10304. const bx0 = b.charCodeAt(offset + (d0 = x));
  10305. dd = ++x;
  10306. for (let y = 0; y < la; y++) {
  10307. const dy = vector[y];
  10308. vector[y] = dd = dy < d0 || dd < d0 ? dy > dd ? dd + 1 : dy + 1 : bx0 === vector[la + y] ? d0 : d0 + 1;
  10309. d0 = dy;
  10310. }
  10311. }
  10312. return dd;
  10313. }
  10314. __name(levenshtein, "levenshtein");
  10315. var setImmediate = typeof globalThis.setImmediate == "function" ? globalThis.setImmediate : (cb) => setTimeout(cb, 0);
  10316. function encode(input) {
  10317. if (typeof input != "string") {
  10318. throw new ErrnoError(22 /* EINVAL */, "Can not encode a non-string");
  10319. }
  10320. return new Uint8Array(Array.from(input).map((char) => char.charCodeAt(0)));
  10321. }
  10322. __name(encode, "encode");
  10323. function decode(input) {
  10324. if (!(input instanceof Uint8Array)) {
  10325. throw new ErrnoError(22 /* EINVAL */, "Can not decode a non-Uint8Array");
  10326. }
  10327. return Array.from(input).map((char) => String.fromCharCode(char)).join("");
  10328. }
  10329. __name(decode, "decode");
  10330. function decodeDirListing(data) {
  10331. return JSON.parse(decode(data), (k, v) => {
  10332. if (k == "") {
  10333. return v;
  10334. }
  10335. return BigInt(v);
  10336. });
  10337. }
  10338. __name(decodeDirListing, "decodeDirListing");
  10339. function encodeDirListing(data) {
  10340. return encode(
  10341. JSON.stringify(data, (k, v) => {
  10342. if (k == "") {
  10343. return v;
  10344. }
  10345. return v.toString();
  10346. })
  10347. );
  10348. }
  10349. __name(encodeDirListing, "encodeDirListing");
  10350. function _toUnixTimestamp(time) {
  10351. if (typeof time === "number") {
  10352. return Math.floor(time);
  10353. }
  10354. if (time instanceof Date) {
  10355. return Math.floor(time.getTime() / 1e3);
  10356. }
  10357. throw new Error("Cannot parse time: " + time);
  10358. }
  10359. __name(_toUnixTimestamp, "_toUnixTimestamp");
  10360. function normalizeMode(mode, def) {
  10361. if (typeof mode == "number") {
  10362. return mode;
  10363. }
  10364. if (typeof mode == "string") {
  10365. const parsed = parseInt(mode, 8);
  10366. if (!isNaN(parsed)) {
  10367. return parsed;
  10368. }
  10369. }
  10370. if (typeof def == "number") {
  10371. return def;
  10372. }
  10373. throw new ErrnoError(22 /* EINVAL */, "Invalid mode: " + mode?.toString());
  10374. }
  10375. __name(normalizeMode, "normalizeMode");
  10376. function normalizeTime(time) {
  10377. if (time instanceof Date) {
  10378. return time;
  10379. }
  10380. if (typeof time == "number") {
  10381. return new Date(time * 1e3);
  10382. }
  10383. if (typeof time == "string") {
  10384. return new Date(time);
  10385. }
  10386. throw new ErrnoError(22 /* EINVAL */, "Invalid time.");
  10387. }
  10388. __name(normalizeTime, "normalizeTime");
  10389. function normalizePath(p) {
  10390. p = p.toString();
  10391. if (p.includes("\0")) {
  10392. throw new ErrnoError(22 /* EINVAL */, "Path can not contain null character");
  10393. }
  10394. if (p.length == 0) {
  10395. throw new ErrnoError(22 /* EINVAL */, "Path can not be empty");
  10396. }
  10397. return resolve(p.replaceAll(/[/\\]+/g, "/"));
  10398. }
  10399. __name(normalizePath, "normalizePath");
  10400. function normalizeOptions(options, encoding = "utf8", flag, mode = 0) {
  10401. if (typeof options != "object" || options === null) {
  10402. return {
  10403. encoding: typeof options == "string" ? options : encoding ?? null,
  10404. flag,
  10405. mode
  10406. };
  10407. }
  10408. return {
  10409. encoding: typeof options?.encoding == "string" ? options.encoding : encoding ?? null,
  10410. flag: typeof options?.flag == "string" ? options.flag : flag,
  10411. mode: normalizeMode("mode" in options ? options?.mode : null, mode)
  10412. };
  10413. }
  10414. __name(normalizeOptions, "normalizeOptions");
  10415. function nop() {
  10416. }
  10417. __name(nop, "nop");
  10418. // src/backends/store/fs.ts
  10419. var maxInodeAllocTries = 5;
  10420. var StoreFS = class extends FileSystem {
  10421. constructor($store) {
  10422. super();
  10423. this.$store = $store;
  10424. this._initialized = false;
  10425. if (!($store instanceof Promise)) {
  10426. this._store = $store;
  10427. this._initialized = true;
  10428. this.makeRootDirectorySync();
  10429. }
  10430. }
  10431. static {
  10432. __name(this, "StoreFS");
  10433. }
  10434. get store() {
  10435. if (!this._store) {
  10436. throw new ErrnoError(61 /* ENODATA */, "No store attached");
  10437. }
  10438. return this._store;
  10439. }
  10440. async ready() {
  10441. await super.ready();
  10442. if (this._initialized) {
  10443. return;
  10444. }
  10445. this._initialized = true;
  10446. this._store = await this.$store;
  10447. }
  10448. metadata() {
  10449. return {
  10450. ...super.metadata(),
  10451. name: this.store.name
  10452. };
  10453. }
  10454. /**
  10455. * Delete all contents stored in the file system.
  10456. */
  10457. async empty() {
  10458. await this.store.clear();
  10459. await this.makeRootDirectory();
  10460. }
  10461. /**
  10462. * Delete all contents stored in the file system.
  10463. */
  10464. emptySync() {
  10465. this.store.clearSync();
  10466. this.makeRootDirectorySync();
  10467. }
  10468. /**
  10469. * @todo Make rename compatible with the cache.
  10470. */
  10471. async rename(oldPath, newPath, cred2) {
  10472. const tx = this.store.transaction(), oldParent = dirname(oldPath), oldName = basename(oldPath), newParent = dirname(newPath), newName = basename(newPath), oldDirNode = await this.findINode(tx, oldParent), oldDirList = await this.getDirListing(tx, oldDirNode, oldParent);
  10473. if (!oldDirNode.toStats().hasAccess(W_OK, cred2)) {
  10474. throw ErrnoError.With("EACCES", oldPath, "rename");
  10475. }
  10476. if (!oldDirList[oldName]) {
  10477. throw ErrnoError.With("ENOENT", oldPath, "rename");
  10478. }
  10479. const nodeId = oldDirList[oldName];
  10480. delete oldDirList[oldName];
  10481. if ((newParent + "/").indexOf(oldPath + "/") === 0) {
  10482. throw new ErrnoError(16 /* EBUSY */, oldParent);
  10483. }
  10484. let newDirNode, newDirList;
  10485. if (newParent === oldParent) {
  10486. newDirNode = oldDirNode;
  10487. newDirList = oldDirList;
  10488. } else {
  10489. newDirNode = await this.findINode(tx, newParent);
  10490. newDirList = await this.getDirListing(tx, newDirNode, newParent);
  10491. }
  10492. if (newDirList[newName]) {
  10493. const newNameNode = await this.getINode(tx, newDirList[newName], newPath);
  10494. if (newNameNode.toStats().isFile()) {
  10495. try {
  10496. await tx.remove(newNameNode.ino);
  10497. await tx.remove(newDirList[newName]);
  10498. } catch (e) {
  10499. await tx.abort();
  10500. throw e;
  10501. }
  10502. } else {
  10503. throw ErrnoError.With("EPERM", newPath, "rename");
  10504. }
  10505. }
  10506. newDirList[newName] = nodeId;
  10507. try {
  10508. await tx.set(oldDirNode.ino, encodeDirListing(oldDirList));
  10509. await tx.set(newDirNode.ino, encodeDirListing(newDirList));
  10510. } catch (e) {
  10511. await tx.abort();
  10512. throw e;
  10513. }
  10514. await tx.commit();
  10515. }
  10516. renameSync(oldPath, newPath, cred2) {
  10517. const tx = this.store.transaction(), oldParent = dirname(oldPath), oldName = basename(oldPath), newParent = dirname(newPath), newName = basename(newPath), oldDirNode = this.findINodeSync(tx, oldParent), oldDirList = this.getDirListingSync(tx, oldDirNode, oldParent);
  10518. if (!oldDirNode.toStats().hasAccess(W_OK, cred2)) {
  10519. throw ErrnoError.With("EACCES", oldPath, "rename");
  10520. }
  10521. if (!oldDirList[oldName]) {
  10522. throw ErrnoError.With("ENOENT", oldPath, "rename");
  10523. }
  10524. const ino = oldDirList[oldName];
  10525. delete oldDirList[oldName];
  10526. if ((newParent + "/").indexOf(oldPath + "/") == 0) {
  10527. throw new ErrnoError(16 /* EBUSY */, oldParent);
  10528. }
  10529. let newDirNode, newDirList;
  10530. if (newParent === oldParent) {
  10531. newDirNode = oldDirNode;
  10532. newDirList = oldDirList;
  10533. } else {
  10534. newDirNode = this.findINodeSync(tx, newParent);
  10535. newDirList = this.getDirListingSync(tx, newDirNode, newParent);
  10536. }
  10537. if (newDirList[newName]) {
  10538. const newNameNode = this.getINodeSync(tx, newDirList[newName], newPath);
  10539. if (newNameNode.toStats().isFile()) {
  10540. try {
  10541. tx.removeSync(newNameNode.ino);
  10542. tx.removeSync(newDirList[newName]);
  10543. } catch (e) {
  10544. tx.abortSync();
  10545. throw e;
  10546. }
  10547. } else {
  10548. throw ErrnoError.With("EPERM", newPath, "rename");
  10549. }
  10550. }
  10551. newDirList[newName] = ino;
  10552. try {
  10553. tx.setSync(oldDirNode.ino, encodeDirListing(oldDirList));
  10554. tx.setSync(newDirNode.ino, encodeDirListing(newDirList));
  10555. } catch (e) {
  10556. tx.abortSync();
  10557. throw e;
  10558. }
  10559. tx.commitSync();
  10560. }
  10561. async stat(path, cred2) {
  10562. const tx = this.store.transaction();
  10563. const inode = await this.findINode(tx, path);
  10564. if (!inode) {
  10565. throw ErrnoError.With("ENOENT", path, "stat");
  10566. }
  10567. const stats = inode.toStats();
  10568. if (!stats.hasAccess(R_OK, cred2)) {
  10569. throw ErrnoError.With("EACCES", path, "stat");
  10570. }
  10571. return stats;
  10572. }
  10573. statSync(path, cred2) {
  10574. const stats = this.findINodeSync(this.store.transaction(), path).toStats();
  10575. if (!stats.hasAccess(R_OK, cred2)) {
  10576. throw ErrnoError.With("EACCES", path, "stat");
  10577. }
  10578. return stats;
  10579. }
  10580. async createFile(path, flag, mode, cred2) {
  10581. const data = new Uint8Array(0);
  10582. const file = await this.commitNew(this.store.transaction(), path, FileType.FILE, mode, cred2, data);
  10583. return new PreloadFile(this, path, flag, file.toStats(), data);
  10584. }
  10585. createFileSync(path, flag, mode, cred2) {
  10586. this.commitNewSync(path, FileType.FILE, mode, cred2);
  10587. return this.openFileSync(path, flag, cred2);
  10588. }
  10589. async openFile(path, flag, cred2) {
  10590. const tx = this.store.transaction(), node = await this.findINode(tx, path), data = await tx.get(node.ino);
  10591. if (!node.toStats().hasAccess(flagToMode(flag), cred2)) {
  10592. throw ErrnoError.With("EACCES", path, "openFile");
  10593. }
  10594. if (!data) {
  10595. throw ErrnoError.With("ENOENT", path, "openFile");
  10596. }
  10597. return new PreloadFile(this, path, flag, node.toStats(), data);
  10598. }
  10599. openFileSync(path, flag, cred2) {
  10600. const tx = this.store.transaction(), node = this.findINodeSync(tx, path), data = tx.getSync(node.ino);
  10601. if (!node.toStats().hasAccess(flagToMode(flag), cred2)) {
  10602. throw ErrnoError.With("EACCES", path, "openFile");
  10603. }
  10604. if (!data) {
  10605. throw ErrnoError.With("ENOENT", path, "openFile");
  10606. }
  10607. return new PreloadFile(this, path, flag, node.toStats(), data);
  10608. }
  10609. async unlink(path, cred2) {
  10610. return this.remove(path, false, cred2);
  10611. }
  10612. unlinkSync(path, cred2) {
  10613. this.removeSync(path, false, cred2);
  10614. }
  10615. async rmdir(path, cred2) {
  10616. const list = await this.readdir(path, cred2);
  10617. if (list.length > 0) {
  10618. throw ErrnoError.With("ENOTEMPTY", path, "rmdir");
  10619. }
  10620. await this.remove(path, true, cred2);
  10621. }
  10622. rmdirSync(path, cred2) {
  10623. if (this.readdirSync(path, cred2).length > 0) {
  10624. throw ErrnoError.With("ENOTEMPTY", path, "rmdir");
  10625. } else {
  10626. this.removeSync(path, true, cred2);
  10627. }
  10628. }
  10629. async mkdir(path, mode, cred2) {
  10630. const tx = this.store.transaction(), data = encode("{}");
  10631. await this.commitNew(tx, path, FileType.DIRECTORY, mode, cred2, data);
  10632. }
  10633. mkdirSync(path, mode, cred2) {
  10634. this.commitNewSync(path, FileType.DIRECTORY, mode, cred2, encode("{}"));
  10635. }
  10636. async readdir(path, cred2) {
  10637. const tx = this.store.transaction();
  10638. const node = await this.findINode(tx, path);
  10639. if (!node.toStats().hasAccess(R_OK, cred2)) {
  10640. throw ErrnoError.With("EACCES", path, "readdur");
  10641. }
  10642. return Object.keys(await this.getDirListing(tx, node, path));
  10643. }
  10644. readdirSync(path, cred2) {
  10645. const tx = this.store.transaction();
  10646. const node = this.findINodeSync(tx, path);
  10647. if (!node.toStats().hasAccess(R_OK, cred2)) {
  10648. throw ErrnoError.With("EACCES", path, "readdir");
  10649. }
  10650. return Object.keys(this.getDirListingSync(tx, node, path));
  10651. }
  10652. /**
  10653. * Updated the inode and data node at the given path
  10654. * @todo Ensure mtime updates properly, and use that to determine if a data update is required.
  10655. */
  10656. async sync(path, data, stats) {
  10657. const tx = this.store.transaction(), fileInodeId = await this._findINode(tx, dirname(path), basename(path)), fileInode = await this.getINode(tx, fileInodeId, path), inodeChanged = fileInode.update(stats);
  10658. try {
  10659. await tx.set(fileInode.ino, data);
  10660. if (inodeChanged) {
  10661. await tx.set(fileInodeId, fileInode.data);
  10662. }
  10663. } catch (e) {
  10664. await tx.abort();
  10665. throw e;
  10666. }
  10667. await tx.commit();
  10668. }
  10669. /**
  10670. * Updated the inode and data node at the given path
  10671. * @todo Ensure mtime updates properly, and use that to determine if a data update is required.
  10672. */
  10673. syncSync(path, data, stats) {
  10674. const tx = this.store.transaction(), fileInodeId = this._findINodeSync(tx, dirname(path), basename(path)), fileInode = this.getINodeSync(tx, fileInodeId, path), inodeChanged = fileInode.update(stats);
  10675. try {
  10676. tx.setSync(fileInode.ino, data);
  10677. if (inodeChanged) {
  10678. tx.setSync(fileInodeId, fileInode.data);
  10679. }
  10680. } catch (e) {
  10681. tx.abortSync();
  10682. throw e;
  10683. }
  10684. tx.commitSync();
  10685. }
  10686. async link(existing, newpath, cred2) {
  10687. const tx = this.store.transaction(), existingDir = dirname(existing), existingDirNode = await this.findINode(tx, existingDir);
  10688. if (!existingDirNode.toStats().hasAccess(R_OK, cred2)) {
  10689. throw ErrnoError.With("EACCES", existingDir, "link");
  10690. }
  10691. const newDir = dirname(newpath), newDirNode = await this.findINode(tx, newDir), newListing = await this.getDirListing(tx, newDirNode, newDir);
  10692. if (!newDirNode.toStats().hasAccess(W_OK, cred2)) {
  10693. throw ErrnoError.With("EACCES", newDir, "link");
  10694. }
  10695. const ino = await this._findINode(tx, existingDir, basename(existing));
  10696. const node = await this.getINode(tx, ino, existing);
  10697. if (!node.toStats().hasAccess(W_OK, cred2)) {
  10698. throw ErrnoError.With("EACCES", newpath, "link");
  10699. }
  10700. node.nlink++;
  10701. newListing[basename(newpath)] = ino;
  10702. try {
  10703. tx.setSync(ino, node.data);
  10704. tx.setSync(newDirNode.ino, encodeDirListing(newListing));
  10705. } catch (e) {
  10706. tx.abortSync();
  10707. throw e;
  10708. }
  10709. tx.commitSync();
  10710. }
  10711. linkSync(existing, newpath, cred2) {
  10712. const tx = this.store.transaction(), existingDir = dirname(existing), existingDirNode = this.findINodeSync(tx, existingDir);
  10713. if (!existingDirNode.toStats().hasAccess(R_OK, cred2)) {
  10714. throw ErrnoError.With("EACCES", existingDir, "link");
  10715. }
  10716. const newDir = dirname(newpath), newDirNode = this.findINodeSync(tx, newDir), newListing = this.getDirListingSync(tx, newDirNode, newDir);
  10717. if (!newDirNode.toStats().hasAccess(W_OK, cred2)) {
  10718. throw ErrnoError.With("EACCES", newDir, "link");
  10719. }
  10720. const ino = this._findINodeSync(tx, existingDir, basename(existing));
  10721. const node = this.getINodeSync(tx, ino, existing);
  10722. if (!node.toStats().hasAccess(W_OK, cred2)) {
  10723. throw ErrnoError.With("EACCES", newpath, "link");
  10724. }
  10725. node.nlink++;
  10726. newListing[basename(newpath)] = ino;
  10727. try {
  10728. tx.setSync(ino, node.data);
  10729. tx.setSync(newDirNode.ino, encodeDirListing(newListing));
  10730. } catch (e) {
  10731. tx.abortSync();
  10732. throw e;
  10733. }
  10734. tx.commitSync();
  10735. }
  10736. /**
  10737. * Checks if the root directory exists. Creates it if it doesn't.
  10738. */
  10739. async makeRootDirectory() {
  10740. const tx = this.store.transaction();
  10741. if (await tx.get(rootIno)) {
  10742. return;
  10743. }
  10744. const inode = new Inode();
  10745. inode.mode = 511 | FileType.DIRECTORY;
  10746. await tx.set(inode.ino, encode("{}"));
  10747. await tx.set(rootIno, inode.data);
  10748. await tx.commit();
  10749. }
  10750. /**
  10751. * Checks if the root directory exists. Creates it if it doesn't.
  10752. */
  10753. makeRootDirectorySync() {
  10754. const tx = this.store.transaction();
  10755. if (tx.getSync(rootIno)) {
  10756. return;
  10757. }
  10758. const inode = new Inode();
  10759. inode.mode = 511 | FileType.DIRECTORY;
  10760. tx.setSync(inode.ino, encode("{}"));
  10761. tx.setSync(rootIno, inode.data);
  10762. tx.commitSync();
  10763. }
  10764. /**
  10765. * Helper function for findINode.
  10766. * @param parent The parent directory of the file we are attempting to find.
  10767. * @param filename The filename of the inode we are attempting to find, minus
  10768. * the parent.
  10769. */
  10770. async _findINode(tx, parent, filename, visited = /* @__PURE__ */ new Set()) {
  10771. const currentPath = join(parent, filename);
  10772. if (visited.has(currentPath)) {
  10773. throw new ErrnoError(5 /* EIO */, "Infinite loop detected while finding inode", currentPath);
  10774. }
  10775. visited.add(currentPath);
  10776. if (parent == "/" && filename === "") {
  10777. return rootIno;
  10778. }
  10779. const inode = parent == "/" ? await this.getINode(tx, rootIno, parent) : await this.findINode(tx, parent, visited);
  10780. const dirList = await this.getDirListing(tx, inode, parent);
  10781. if (!(filename in dirList)) {
  10782. throw ErrnoError.With("ENOENT", resolve(parent, filename), "_findINode");
  10783. }
  10784. return dirList[filename];
  10785. }
  10786. /**
  10787. * Helper function for findINode.
  10788. * @param parent The parent directory of the file we are attempting to find.
  10789. * @param filename The filename of the inode we are attempting to find, minus
  10790. * the parent.
  10791. * @return string The ID of the file's inode in the file system.
  10792. */
  10793. _findINodeSync(tx, parent, filename, visited = /* @__PURE__ */ new Set()) {
  10794. const currentPath = join(parent, filename);
  10795. if (visited.has(currentPath)) {
  10796. throw new ErrnoError(5 /* EIO */, "Infinite loop detected while finding inode", currentPath);
  10797. }
  10798. visited.add(currentPath);
  10799. if (parent == "/" && filename === "") {
  10800. return rootIno;
  10801. }
  10802. const inode = parent == "/" ? this.getINodeSync(tx, rootIno, parent) : this.findINodeSync(tx, parent, visited);
  10803. const dir = this.getDirListingSync(tx, inode, parent);
  10804. if (!(filename in dir)) {
  10805. throw ErrnoError.With("ENOENT", resolve(parent, filename), "_findINode");
  10806. }
  10807. return dir[filename];
  10808. }
  10809. /**
  10810. * Finds the Inode of the given path.
  10811. * @param path The path to look up.
  10812. * @todo memoize/cache
  10813. */
  10814. async findINode(tx, path, visited = /* @__PURE__ */ new Set()) {
  10815. const id = await this._findINode(tx, dirname(path), basename(path), visited);
  10816. return this.getINode(tx, id, path);
  10817. }
  10818. /**
  10819. * Finds the Inode of the given path.
  10820. * @param path The path to look up.
  10821. * @return The Inode of the path p.
  10822. * @todo memoize/cache
  10823. */
  10824. findINodeSync(tx, path, visited = /* @__PURE__ */ new Set()) {
  10825. const ino = this._findINodeSync(tx, dirname(path), basename(path), visited);
  10826. return this.getINodeSync(tx, ino, path);
  10827. }
  10828. /**
  10829. * Given the ID of a node, retrieves the corresponding Inode.
  10830. * @param tx The transaction to use.
  10831. * @param path The corresponding path to the file (used for error messages).
  10832. * @param id The ID to look up.
  10833. */
  10834. async getINode(tx, id, path) {
  10835. const data = await tx.get(id);
  10836. if (!data) {
  10837. throw ErrnoError.With("ENOENT", path, "getINode");
  10838. }
  10839. return new Inode(data.buffer);
  10840. }
  10841. /**
  10842. * Given the ID of a node, retrieves the corresponding Inode.
  10843. * @param tx The transaction to use.
  10844. * @param path The corresponding path to the file (used for error messages).
  10845. * @param id The ID to look up.
  10846. */
  10847. getINodeSync(tx, id, path) {
  10848. const data = tx.getSync(id);
  10849. if (!data) {
  10850. throw ErrnoError.With("ENOENT", path, "getINode");
  10851. }
  10852. const inode = new Inode(data.buffer);
  10853. return inode;
  10854. }
  10855. /**
  10856. * Given the Inode of a directory, retrieves the corresponding directory
  10857. * listing.
  10858. */
  10859. async getDirListing(tx, inode, path) {
  10860. if (!inode.toStats().isDirectory()) {
  10861. throw ErrnoError.With("ENOTDIR", path, "getDirListing");
  10862. }
  10863. const data = await tx.get(inode.ino);
  10864. if (!data) {
  10865. throw ErrnoError.With("ENOENT", path, "getDirListing");
  10866. }
  10867. return decodeDirListing(data);
  10868. }
  10869. /**
  10870. * Given the Inode of a directory, retrieves the corresponding directory listing.
  10871. */
  10872. getDirListingSync(tx, inode, p) {
  10873. if (!inode.toStats().isDirectory()) {
  10874. throw ErrnoError.With("ENOTDIR", p, "getDirListing");
  10875. }
  10876. const data = tx.getSync(inode.ino);
  10877. if (!data) {
  10878. throw ErrnoError.With("ENOENT", p, "getDirListing");
  10879. }
  10880. return decodeDirListing(data);
  10881. }
  10882. /**
  10883. * Adds a new node under a random ID. Retries before giving up in
  10884. * the exceedingly unlikely chance that we try to reuse a random ino.
  10885. */
  10886. async addNew(tx, data, path) {
  10887. for (let i = 0; i < maxInodeAllocTries; i++) {
  10888. const ino = randomIno();
  10889. if (await tx.get(ino)) {
  10890. continue;
  10891. }
  10892. await tx.set(ino, data);
  10893. return ino;
  10894. }
  10895. throw new ErrnoError(28 /* ENOSPC */, "No inode IDs available", path, "addNewNode");
  10896. }
  10897. /**
  10898. * Creates a new node under a random ID. Retries before giving up in
  10899. * the exceedingly unlikely chance that we try to reuse a random ino.
  10900. * @return The ino that the data was stored under.
  10901. */
  10902. addNewSync(tx, data, path) {
  10903. for (let i = 0; i < maxInodeAllocTries; i++) {
  10904. const ino = randomIno();
  10905. if (tx.getSync(ino)) {
  10906. continue;
  10907. }
  10908. tx.setSync(ino, data);
  10909. return ino;
  10910. }
  10911. throw new ErrnoError(28 /* ENOSPC */, "No inode IDs available", path, "addNewNode");
  10912. }
  10913. /**
  10914. * Commits a new file (well, a FILE or a DIRECTORY) to the file system with
  10915. * the given mode.
  10916. * Note: This will commit the transaction.
  10917. * @param path The path to the new file.
  10918. * @param type The type of the new file.
  10919. * @param mode The mode to create the new file with.
  10920. * @param cred The UID/GID to create the file with
  10921. * @param data The data to store at the file's data node.
  10922. */
  10923. async commitNew(tx, path, type, mode, cred2, data) {
  10924. const parentPath = dirname(path), parent = await this.findINode(tx, parentPath);
  10925. if (!parent.toStats().hasAccess(W_OK, cred2)) {
  10926. throw ErrnoError.With("EACCES", path, "commitNewFile");
  10927. }
  10928. const fname = basename(path), listing = await this.getDirListing(tx, parent, parentPath);
  10929. if (path === "/") {
  10930. throw ErrnoError.With("EEXIST", path, "commitNewFile");
  10931. }
  10932. if (listing[fname]) {
  10933. await tx.abort();
  10934. throw ErrnoError.With("EEXIST", path, "commitNewFile");
  10935. }
  10936. try {
  10937. const inode = new Inode();
  10938. inode.ino = await this.addNew(tx, data, path);
  10939. inode.mode = mode | type;
  10940. inode.uid = cred2.uid;
  10941. inode.gid = cred2.gid;
  10942. inode.size = data.length;
  10943. listing[fname] = await this.addNew(tx, inode.data, path);
  10944. await tx.set(parent.ino, encodeDirListing(listing));
  10945. await tx.commit();
  10946. return inode;
  10947. } catch (e) {
  10948. tx.abort();
  10949. throw e;
  10950. }
  10951. }
  10952. /**
  10953. * Commits a new file (well, a FILE or a DIRECTORY) to the file system with the given mode.
  10954. * Note: This will commit the transaction.
  10955. * @param path The path to the new file.
  10956. * @param type The type of the new file.
  10957. * @param mode The mode to create the new file with.
  10958. * @param data The data to store at the file's data node.
  10959. * @return The Inode for the new file.
  10960. */
  10961. commitNewSync(path, type, mode, cred2, data = new Uint8Array()) {
  10962. const tx = this.store.transaction(), parentPath = dirname(path), parent = this.findINodeSync(tx, parentPath);
  10963. if (!parent.toStats().hasAccess(W_OK, cred2)) {
  10964. throw ErrnoError.With("EACCES", path, "commitNewFile");
  10965. }
  10966. const fname = basename(path), listing = this.getDirListingSync(tx, parent, parentPath);
  10967. if (path === "/") {
  10968. throw ErrnoError.With("EEXIST", path, "commitNewFile");
  10969. }
  10970. if (listing[fname]) {
  10971. throw ErrnoError.With("EEXIST", path, "commitNewFile");
  10972. }
  10973. const node = new Inode();
  10974. try {
  10975. node.ino = this.addNewSync(tx, data, path);
  10976. node.size = data.length;
  10977. node.mode = mode | type;
  10978. node.uid = cred2.uid;
  10979. node.gid = cred2.gid;
  10980. listing[fname] = this.addNewSync(tx, node.data, path);
  10981. tx.setSync(parent.ino, encodeDirListing(listing));
  10982. } catch (e) {
  10983. tx.abortSync();
  10984. throw e;
  10985. }
  10986. tx.commitSync();
  10987. return node;
  10988. }
  10989. /**
  10990. * Remove all traces of the given path from the file system.
  10991. * @param path The path to remove from the file system.
  10992. * @param isDir Does the path belong to a directory, or a file?
  10993. * @todo Update mtime.
  10994. */
  10995. async remove(path, isDir, cred2) {
  10996. const tx = this.store.transaction(), parent = dirname(path), parentNode = await this.findINode(tx, parent), listing = await this.getDirListing(tx, parentNode, parent), fileName = basename(path);
  10997. if (!listing[fileName]) {
  10998. throw ErrnoError.With("ENOENT", path, "removeEntry");
  10999. }
  11000. const fileIno = listing[fileName];
  11001. const fileNode = await this.getINode(tx, fileIno, path);
  11002. if (!fileNode.toStats().hasAccess(W_OK, cred2)) {
  11003. throw ErrnoError.With("EACCES", path, "removeEntry");
  11004. }
  11005. delete listing[fileName];
  11006. if (!isDir && fileNode.toStats().isDirectory()) {
  11007. throw ErrnoError.With("EISDIR", path, "removeEntry");
  11008. }
  11009. if (isDir && !fileNode.toStats().isDirectory()) {
  11010. throw ErrnoError.With("ENOTDIR", path, "removeEntry");
  11011. }
  11012. try {
  11013. await tx.set(parentNode.ino, encodeDirListing(listing));
  11014. if (--fileNode.nlink < 1) {
  11015. await tx.remove(fileNode.ino);
  11016. await tx.remove(fileIno);
  11017. }
  11018. } catch (e) {
  11019. await tx.abort();
  11020. throw e;
  11021. }
  11022. await tx.commit();
  11023. }
  11024. /**
  11025. * Remove all traces of the given path from the file system.
  11026. * @param path The path to remove from the file system.
  11027. * @param isDir Does the path belong to a directory, or a file?
  11028. * @todo Update mtime.
  11029. */
  11030. removeSync(path, isDir, cred2) {
  11031. const tx = this.store.transaction(), parent = dirname(path), parentNode = this.findINodeSync(tx, parent), listing = this.getDirListingSync(tx, parentNode, parent), fileName = basename(path), fileIno = listing[fileName];
  11032. if (!fileIno) {
  11033. throw ErrnoError.With("ENOENT", path, "removeEntry");
  11034. }
  11035. const fileNode = this.getINodeSync(tx, fileIno, path);
  11036. if (!fileNode.toStats().hasAccess(W_OK, cred2)) {
  11037. throw ErrnoError.With("EACCES", path, "removeEntry");
  11038. }
  11039. delete listing[fileName];
  11040. if (!isDir && fileNode.toStats().isDirectory()) {
  11041. throw ErrnoError.With("EISDIR", path, "removeEntry");
  11042. }
  11043. if (isDir && !fileNode.toStats().isDirectory()) {
  11044. throw ErrnoError.With("ENOTDIR", path, "removeEntry");
  11045. }
  11046. try {
  11047. tx.setSync(parentNode.ino, encodeDirListing(listing));
  11048. if (--fileNode.nlink < 1) {
  11049. tx.removeSync(fileNode.ino);
  11050. tx.removeSync(fileIno);
  11051. }
  11052. } catch (e) {
  11053. tx.abortSync();
  11054. throw e;
  11055. }
  11056. tx.commitSync();
  11057. }
  11058. };
  11059. // src/backends/store/store.ts
  11060. var Transaction = class {
  11061. constructor() {
  11062. this.aborted = false;
  11063. }
  11064. static {
  11065. __name(this, "Transaction");
  11066. }
  11067. async [Symbol.asyncDispose]() {
  11068. if (this.aborted) {
  11069. return;
  11070. }
  11071. await this.commit();
  11072. }
  11073. [Symbol.dispose]() {
  11074. if (this.aborted) {
  11075. return;
  11076. }
  11077. this.commitSync();
  11078. }
  11079. };
  11080. var SyncTransaction = class extends Transaction {
  11081. static {
  11082. __name(this, "SyncTransaction");
  11083. }
  11084. async get(ino) {
  11085. return this.getSync(ino);
  11086. }
  11087. async set(ino, data) {
  11088. return this.setSync(ino, data);
  11089. }
  11090. async remove(ino) {
  11091. return this.removeSync(ino);
  11092. }
  11093. async commit() {
  11094. return this.commitSync();
  11095. }
  11096. async abort() {
  11097. return this.abortSync();
  11098. }
  11099. };
  11100. var AsyncTransaction = class extends Transaction {
  11101. static {
  11102. __name(this, "AsyncTransaction");
  11103. }
  11104. getSync(ino) {
  11105. throw ErrnoError.With("ENOSYS", void 0, "AsyncTransaction.getSync");
  11106. }
  11107. setSync(ino, data) {
  11108. throw ErrnoError.With("ENOSYS", void 0, "AsyncTransaction.setSync");
  11109. }
  11110. removeSync(ino) {
  11111. throw ErrnoError.With("ENOSYS", void 0, "AsyncTransaction.removeSync");
  11112. }
  11113. commitSync() {
  11114. throw ErrnoError.With("ENOSYS", void 0, "AsyncTransaction.commitSync");
  11115. }
  11116. abortSync() {
  11117. throw ErrnoError.With("ENOSYS", void 0, "AsyncTransaction.abortSync");
  11118. }
  11119. };
  11120. // src/backends/store/simple.ts
  11121. var SimpleAsyncStore = class {
  11122. constructor() {
  11123. this.cache = /* @__PURE__ */ new Map();
  11124. this.queue = /* @__PURE__ */ new Set();
  11125. }
  11126. static {
  11127. __name(this, "SimpleAsyncStore");
  11128. }
  11129. get(ino) {
  11130. return this.cache.get(ino);
  11131. }
  11132. set(ino, data) {
  11133. this.cache.set(ino, data);
  11134. this.queue.add(this._set(ino, data));
  11135. }
  11136. delete(ino) {
  11137. this.cache.delete(ino);
  11138. this.queue.add(this._delete(ino));
  11139. }
  11140. clearSync() {
  11141. this.cache.clear();
  11142. this.queue.add(this.clear());
  11143. }
  11144. async sync() {
  11145. for (const [ino, data] of await this.entries()) {
  11146. if (!this.cache.has(ino)) {
  11147. this.cache.set(ino, data);
  11148. }
  11149. }
  11150. for (const promise of this.queue) {
  11151. await promise;
  11152. }
  11153. }
  11154. transaction() {
  11155. return new SimpleTransaction(this);
  11156. }
  11157. };
  11158. var SimpleTransaction = class extends SyncTransaction {
  11159. constructor(store) {
  11160. super();
  11161. this.store = store;
  11162. /**
  11163. * Stores data in the keys we modify prior to modifying them.
  11164. * Allows us to roll back commits.
  11165. */
  11166. this.originalData = /* @__PURE__ */ new Map();
  11167. /**
  11168. * List of keys modified in this transaction, if any.
  11169. */
  11170. this.modifiedKeys = /* @__PURE__ */ new Set();
  11171. }
  11172. static {
  11173. __name(this, "SimpleTransaction");
  11174. }
  11175. getSync(ino) {
  11176. const val = this.store.get(ino);
  11177. this.stashOldValue(ino, val);
  11178. return val;
  11179. }
  11180. setSync(ino, data) {
  11181. this.markModified(ino);
  11182. return this.store.set(ino, data);
  11183. }
  11184. removeSync(ino) {
  11185. this.markModified(ino);
  11186. this.store.delete(ino);
  11187. }
  11188. commitSync() {
  11189. }
  11190. abortSync() {
  11191. for (const key of this.modifiedKeys) {
  11192. const value = this.originalData.get(key);
  11193. if (!value) {
  11194. this.store.delete(key);
  11195. } else {
  11196. this.store.set(key, value);
  11197. }
  11198. }
  11199. }
  11200. /**
  11201. * Stashes given key value pair into `originalData` if it doesn't already
  11202. * exist. Allows us to stash values the program is requesting anyway to
  11203. * prevent needless `get` requests if the program modifies the data later
  11204. * on during the transaction.
  11205. */
  11206. stashOldValue(ino, value) {
  11207. if (!this.originalData.has(ino)) {
  11208. this.originalData.set(ino, value);
  11209. }
  11210. }
  11211. /**
  11212. * Marks the given key as modified, and stashes its value if it has not been
  11213. * stashed already.
  11214. */
  11215. markModified(ino) {
  11216. this.modifiedKeys.add(ino);
  11217. if (!this.originalData.has(ino)) {
  11218. this.originalData.set(ino, this.store.get(ino));
  11219. }
  11220. }
  11221. };
  11222. // src/backends/memory.ts
  11223. var InMemoryStore = class extends Map {
  11224. constructor(name = "tmp") {
  11225. super();
  11226. this.name = name;
  11227. }
  11228. static {
  11229. __name(this, "InMemoryStore");
  11230. }
  11231. async sync() {
  11232. }
  11233. clearSync() {
  11234. this.clear();
  11235. }
  11236. transaction() {
  11237. return new SimpleTransaction(this);
  11238. }
  11239. };
  11240. var InMemory = {
  11241. name: "InMemory",
  11242. isAvailable: /* @__PURE__ */ __name(function() {
  11243. return true;
  11244. }, "isAvailable"),
  11245. options: {
  11246. name: {
  11247. type: "string",
  11248. required: false,
  11249. description: "The name of the store"
  11250. }
  11251. },
  11252. create: /* @__PURE__ */ __name(function({ name }) {
  11253. return new StoreFS(new InMemoryStore(name));
  11254. }, "create")
  11255. };
  11256. // src/backends/port/rpc.ts
  11257. function isFileData(value) {
  11258. return typeof value == "object" && value != null && "fd" in value && "path" in value && "position" in value;
  11259. }
  11260. __name(isFileData, "isFileData");
  11261. function isMessage(arg) {
  11262. return typeof arg == "object" && arg != null && "_zenfs" in arg && !!arg._zenfs;
  11263. }
  11264. __name(isMessage, "isMessage");
  11265. var executors = /* @__PURE__ */ new Map();
  11266. function request(request2, { port, timeout = 1e3, fs } = {}) {
  11267. const stack = new Error().stack.slice("Error:".length);
  11268. if (!port) {
  11269. throw ErrnoError.With("EINVAL");
  11270. }
  11271. return new Promise((resolve2, reject) => {
  11272. const id = Math.random().toString(16).slice(10);
  11273. executors.set(id, { resolve: resolve2, reject, fs });
  11274. port.postMessage({ ...request2, _zenfs: true, id, stack });
  11275. const _ = setTimeout(() => {
  11276. const error = new ErrnoError(5 /* EIO */, "RPC Failed");
  11277. error.stack += stack;
  11278. reject(error);
  11279. if (typeof _ == "object") _.unref();
  11280. }, timeout);
  11281. });
  11282. }
  11283. __name(request, "request");
  11284. function handleResponse(response) {
  11285. if (!isMessage(response)) {
  11286. return;
  11287. }
  11288. const { id, value, error, stack } = response;
  11289. if (!executors.has(id)) {
  11290. const error2 = new ErrnoError(5 /* EIO */, "Invalid RPC id:" + id);
  11291. error2.stack += stack;
  11292. throw error2;
  11293. }
  11294. const { resolve: resolve2, reject, fs } = executors.get(id);
  11295. if (error) {
  11296. const e = ErrnoError.fromJSON(value);
  11297. e.stack += stack;
  11298. reject(e);
  11299. executors.delete(id);
  11300. return;
  11301. }
  11302. if (isFileData(value)) {
  11303. const { fd, path, position } = value;
  11304. const file = new PortFile(fs, fd, path, position);
  11305. resolve2(file);
  11306. executors.delete(id);
  11307. return;
  11308. }
  11309. resolve2(value);
  11310. executors.delete(id);
  11311. return;
  11312. }
  11313. __name(handleResponse, "handleResponse");
  11314. function attach(port, handler) {
  11315. if (!port) {
  11316. throw ErrnoError.With("EINVAL");
  11317. }
  11318. port["on" in port ? "on" : "addEventListener"]("message", (message) => {
  11319. handler("data" in message ? message.data : message);
  11320. });
  11321. }
  11322. __name(attach, "attach");
  11323. function detach(port, handler) {
  11324. if (!port) {
  11325. throw ErrnoError.With("EINVAL");
  11326. }
  11327. port["off" in port ? "off" : "removeEventListener"]("message", (message) => {
  11328. handler("data" in message ? message.data : message);
  11329. });
  11330. }
  11331. __name(detach, "detach");
  11332. // src/backends/port/fs.ts
  11333. var PortFile = class extends File {
  11334. constructor(fs, fd, path, position) {
  11335. super();
  11336. this.fs = fs;
  11337. this.fd = fd;
  11338. this.path = path;
  11339. this.position = position;
  11340. }
  11341. static {
  11342. __name(this, "PortFile");
  11343. }
  11344. rpc(method, ...args) {
  11345. return request(
  11346. {
  11347. scope: "file",
  11348. fd: this.fd,
  11349. method,
  11350. args
  11351. },
  11352. this.fs.options
  11353. );
  11354. }
  11355. stat() {
  11356. return this.rpc("stat");
  11357. }
  11358. statSync() {
  11359. throw ErrnoError.With("ENOSYS", this.path, "PortFile.stat");
  11360. }
  11361. truncate(len) {
  11362. return this.rpc("truncate", len);
  11363. }
  11364. truncateSync() {
  11365. throw ErrnoError.With("ENOSYS", this.path, "PortFile.truncate");
  11366. }
  11367. write(buffer, offset, length, position) {
  11368. return this.rpc("write", buffer, offset, length, position);
  11369. }
  11370. writeSync() {
  11371. throw ErrnoError.With("ENOSYS", this.path, "PortFile.write");
  11372. }
  11373. async read(buffer, offset, length, position) {
  11374. return await this.rpc("read", buffer, offset, length, position);
  11375. }
  11376. readSync() {
  11377. throw ErrnoError.With("ENOSYS", this.path, "PortFile.read");
  11378. }
  11379. chown(uid, gid) {
  11380. return this.rpc("chown", uid, gid);
  11381. }
  11382. chownSync() {
  11383. throw ErrnoError.With("ENOSYS", this.path, "PortFile.chown");
  11384. }
  11385. chmod(mode) {
  11386. return this.rpc("chmod", mode);
  11387. }
  11388. chmodSync() {
  11389. throw ErrnoError.With("ENOSYS", this.path, "PortFile.chmod");
  11390. }
  11391. utimes(atime, mtime) {
  11392. return this.rpc("utimes", atime, mtime);
  11393. }
  11394. utimesSync() {
  11395. throw ErrnoError.With("ENOSYS", this.path, "PortFile.utimes");
  11396. }
  11397. _setType(type) {
  11398. return this.rpc("_setType", type);
  11399. }
  11400. _setTypeSync() {
  11401. throw ErrnoError.With("ENOSYS", this.path, "PortFile._setType");
  11402. }
  11403. close() {
  11404. return this.rpc("close");
  11405. }
  11406. closeSync() {
  11407. throw ErrnoError.With("ENOSYS", this.path, "PortFile.close");
  11408. }
  11409. sync() {
  11410. return this.rpc("sync");
  11411. }
  11412. syncSync() {
  11413. throw ErrnoError.With("ENOSYS", this.path, "PortFile.sync");
  11414. }
  11415. };
  11416. var PortFS = class extends Async(FileSystem) {
  11417. /**
  11418. * Constructs a new PortFS instance that connects with ZenFS running on
  11419. * the specified port.
  11420. */
  11421. constructor(options) {
  11422. super();
  11423. this.options = options;
  11424. /**
  11425. * @hidden
  11426. */
  11427. this._sync = InMemory.create({ name: "port-tmpfs" });
  11428. this.port = options.port;
  11429. attach(this.port, handleResponse);
  11430. }
  11431. static {
  11432. __name(this, "PortFS");
  11433. }
  11434. metadata() {
  11435. return {
  11436. ...super.metadata(),
  11437. name: "PortFS"
  11438. };
  11439. }
  11440. rpc(method, ...args) {
  11441. return request(
  11442. {
  11443. scope: "fs",
  11444. method,
  11445. args
  11446. },
  11447. { ...this.options, fs: this }
  11448. );
  11449. }
  11450. async ready() {
  11451. await this.rpc("ready");
  11452. await super.ready();
  11453. }
  11454. rename(oldPath, newPath, cred2) {
  11455. return this.rpc("rename", oldPath, newPath, cred2);
  11456. }
  11457. async stat(path, cred2) {
  11458. return new Stats(await this.rpc("stat", path, cred2));
  11459. }
  11460. sync(path, data, stats) {
  11461. return this.rpc("sync", path, data, stats);
  11462. }
  11463. openFile(path, flag, cred2) {
  11464. return this.rpc("openFile", path, flag, cred2);
  11465. }
  11466. createFile(path, flag, mode, cred2) {
  11467. return this.rpc("createFile", path, flag, mode, cred2);
  11468. }
  11469. unlink(path, cred2) {
  11470. return this.rpc("unlink", path, cred2);
  11471. }
  11472. rmdir(path, cred2) {
  11473. return this.rpc("rmdir", path, cred2);
  11474. }
  11475. mkdir(path, mode, cred2) {
  11476. return this.rpc("mkdir", path, mode, cred2);
  11477. }
  11478. readdir(path, cred2) {
  11479. return this.rpc("readdir", path, cred2);
  11480. }
  11481. exists(path, cred2) {
  11482. return this.rpc("exists", path, cred2);
  11483. }
  11484. link(srcpath, dstpath, cred2) {
  11485. return this.rpc("link", srcpath, dstpath, cred2);
  11486. }
  11487. };
  11488. var nextFd = 0;
  11489. var descriptors = /* @__PURE__ */ new Map();
  11490. async function handleRequest(port, fs, request2) {
  11491. if (!isMessage(request2)) {
  11492. return;
  11493. }
  11494. const { method, args, id, scope, stack } = request2;
  11495. let value, error = false;
  11496. try {
  11497. switch (scope) {
  11498. case "fs":
  11499. value = await fs[method](...args);
  11500. if (value instanceof File) {
  11501. descriptors.set(++nextFd, value);
  11502. value = {
  11503. fd: nextFd,
  11504. path: value.path,
  11505. position: value.position
  11506. };
  11507. }
  11508. break;
  11509. case "file":
  11510. const { fd } = request2;
  11511. if (!descriptors.has(fd)) {
  11512. throw new ErrnoError(9 /* EBADF */);
  11513. }
  11514. value = await descriptors.get(fd)[method](...args);
  11515. if (method == "close") {
  11516. descriptors.delete(fd);
  11517. }
  11518. break;
  11519. default:
  11520. return;
  11521. }
  11522. } catch (e) {
  11523. value = e;
  11524. error = true;
  11525. }
  11526. port.postMessage({
  11527. _zenfs: true,
  11528. scope,
  11529. id,
  11530. error,
  11531. method,
  11532. stack,
  11533. value: value instanceof ErrnoError ? value.toJSON() : value
  11534. });
  11535. }
  11536. __name(handleRequest, "handleRequest");
  11537. function attachFS(port, fs) {
  11538. attach(port, (request2) => handleRequest(port, fs, request2));
  11539. }
  11540. __name(attachFS, "attachFS");
  11541. function detachFS(port, fs) {
  11542. detach(port, (request2) => handleRequest(port, fs, request2));
  11543. }
  11544. __name(detachFS, "detachFS");
  11545. var Port = {
  11546. name: "Port",
  11547. options: {
  11548. port: {
  11549. type: "object",
  11550. required: true,
  11551. description: "The target port that you want to connect to",
  11552. validator: /* @__PURE__ */ __name(function(port) {
  11553. if (typeof port?.postMessage != "function") {
  11554. throw new ErrnoError(22 /* EINVAL */, "option must be a port.");
  11555. }
  11556. }, "validator")
  11557. },
  11558. timeout: {
  11559. type: "number",
  11560. required: false,
  11561. description: "How long to wait before the request times out"
  11562. }
  11563. },
  11564. isAvailable: /* @__PURE__ */ __name(async function() {
  11565. return true;
  11566. }, "isAvailable"),
  11567. create: /* @__PURE__ */ __name(function(options) {
  11568. return new PortFS(options);
  11569. }, "create")
  11570. };
  11571. // src/backends/Index.ts
  11572. var FileIndex = class _FileIndex {
  11573. /**
  11574. * Constructs a new FileIndex.
  11575. */
  11576. constructor() {
  11577. // Maps directory paths to directory inodes, which contain files.
  11578. this._index = /* @__PURE__ */ new Map();
  11579. this.add("/", new IndexDirInode());
  11580. }
  11581. static {
  11582. __name(this, "FileIndex");
  11583. }
  11584. /**
  11585. * Static method for constructing indices from a JSON listing.
  11586. * @param listing Directory listing generated by tools
  11587. * @return A new FileIndex object.
  11588. */
  11589. static FromListing(listing) {
  11590. const index = new _FileIndex();
  11591. const rootInode = new IndexDirInode();
  11592. index._index.set("/", rootInode);
  11593. const queue = [{ pwd: "", tree: listing, parent: rootInode }];
  11594. while (queue.length > 0) {
  11595. let inode;
  11596. const { tree, pwd, parent } = queue.pop();
  11597. for (const node in tree) {
  11598. if (!Object.hasOwn(tree, node)) {
  11599. continue;
  11600. }
  11601. const children = tree[node];
  11602. if (children) {
  11603. const path = pwd + "/" + node;
  11604. inode = new IndexDirInode();
  11605. index._index.set(path, inode);
  11606. queue.push({ pwd: path, tree: children, parent: inode });
  11607. } else {
  11608. inode = new IndexFileInode(new Stats({ mode: FileType.FILE | 365 }));
  11609. }
  11610. if (!parent) {
  11611. continue;
  11612. }
  11613. parent._listing.set(node, inode);
  11614. }
  11615. }
  11616. return index;
  11617. }
  11618. files() {
  11619. const files = [];
  11620. for (const dir of this._index.values()) {
  11621. for (const file of dir.listing) {
  11622. const item = dir.get(file);
  11623. if (!item) {
  11624. continue;
  11625. }
  11626. if (!item.isFile()) {
  11627. continue;
  11628. }
  11629. files.push(item);
  11630. }
  11631. }
  11632. return files;
  11633. }
  11634. /**
  11635. * Adds the given absolute path to the index if it is not already in the index.
  11636. * Creates any needed parent directories.
  11637. * @param path The path to add to the index.
  11638. * @param inode The inode for the
  11639. * path to add.
  11640. * @return 'True' if it was added or already exists, 'false' if there
  11641. * was an issue adding it (e.g. item in path is a file, item exists but is
  11642. * different).
  11643. * @todo If adding fails and implicitly creates directories, we do not clean up
  11644. * the new empty directories.
  11645. */
  11646. add(path, inode) {
  11647. if (!inode) {
  11648. throw new ErrnoError(22 /* EINVAL */, "Inode must be specified", path, "FileIndex.add");
  11649. }
  11650. if (!path.startsWith("/")) {
  11651. throw new ErrnoError(22 /* EINVAL */, "Path not absolute", path, "FileIndex.add");
  11652. }
  11653. if (this._index.has(path)) {
  11654. return this._index.get(path) === inode;
  11655. }
  11656. const dirpath = dirname(path);
  11657. const hasParent = this._index.has(dirpath);
  11658. const parent = hasParent ? this._index.get(dirpath) : new IndexDirInode();
  11659. if (!hasParent && path != "/") {
  11660. if (!this.add(dirpath, parent)) {
  11661. return false;
  11662. }
  11663. }
  11664. if (path != "/" && !parent.add(basename(path), inode)) {
  11665. return false;
  11666. }
  11667. if (inode.isDirectory()) {
  11668. this._index.set(path, inode);
  11669. }
  11670. return true;
  11671. }
  11672. /**
  11673. * Adds the given absolute path to the index if it is not already in the index.
  11674. * The path is added without special treatment (no joining of adjacent separators, etc).
  11675. * Creates any needed parent directories.
  11676. * @param path The path to add to the index.
  11677. * @param inode The inode for the path to add.
  11678. * @return 'True' if it was added or already exists, 'false' if there
  11679. * was an issue adding it (e.g. item in path is a file, item exists but is
  11680. * different).
  11681. * @todo If adding fails and implicitly creates directories, we do not clean up the new empty directories.
  11682. */
  11683. addFast(path, inode) {
  11684. const parentPath = dirname(path);
  11685. const itemName = basename(path);
  11686. let parent = this._index.get(parentPath);
  11687. if (!parent) {
  11688. parent = new IndexDirInode();
  11689. this.addFast(parentPath, parent);
  11690. }
  11691. if (!parent.add(itemName, inode)) {
  11692. return false;
  11693. }
  11694. if (inode.isDirectory()) {
  11695. this._index.set(path, inode);
  11696. }
  11697. return true;
  11698. }
  11699. /**
  11700. * Removes the given path. Can be a file or a directory.
  11701. * @return The removed item,
  11702. * or null if it did not exist.
  11703. */
  11704. remove(path) {
  11705. const dirpath = dirname(path);
  11706. const parent = this._index.get(dirpath);
  11707. if (!parent) {
  11708. return;
  11709. }
  11710. const inode = parent.remove(basename(path));
  11711. if (!inode) {
  11712. return;
  11713. }
  11714. if (!inode.isDirectory()) {
  11715. return inode;
  11716. }
  11717. const children = inode.listing;
  11718. for (const child of children) {
  11719. this.remove(join(path, child));
  11720. }
  11721. if (path != "/") {
  11722. this._index.delete(path);
  11723. }
  11724. }
  11725. /**
  11726. * Retrieves the directory listing of the given path.
  11727. * @return An array of files in the given path, or 'null' if it does not exist.
  11728. */
  11729. ls(path) {
  11730. return this._index.get(path)?.listing;
  11731. }
  11732. /**
  11733. * Returns the inode of the given item.
  11734. * @return Returns null if the item does not exist.
  11735. */
  11736. get(path) {
  11737. const dirpath = dirname(path);
  11738. const parent = this._index.get(dirpath);
  11739. if (dirpath == path) {
  11740. return parent;
  11741. }
  11742. return parent?.get(basename(path));
  11743. }
  11744. };
  11745. var IndexInode = class {
  11746. constructor(data) {
  11747. this.data = data;
  11748. }
  11749. static {
  11750. __name(this, "IndexInode");
  11751. }
  11752. };
  11753. var IndexFileInode = class extends IndexInode {
  11754. static {
  11755. __name(this, "IndexFileInode");
  11756. }
  11757. isFile() {
  11758. return true;
  11759. }
  11760. isDirectory() {
  11761. return false;
  11762. }
  11763. toStats() {
  11764. return new Stats({ mode: FileType.FILE | 438, size: 4096 });
  11765. }
  11766. };
  11767. var IndexDirInode = class extends IndexInode {
  11768. constructor() {
  11769. super(...arguments);
  11770. /**
  11771. * @internal
  11772. */
  11773. this._listing = /* @__PURE__ */ new Map();
  11774. }
  11775. static {
  11776. __name(this, "IndexDirInode");
  11777. }
  11778. isFile() {
  11779. return false;
  11780. }
  11781. isDirectory() {
  11782. return true;
  11783. }
  11784. /**
  11785. * Return a Stats object for this inode.
  11786. * @todo Should probably remove this at some point. This isn't the responsibility of the FileIndex.
  11787. */
  11788. get stats() {
  11789. return new Stats({ mode: FileType.DIRECTORY | 365, size: 4096 });
  11790. }
  11791. /**
  11792. * Alias of getStats()
  11793. * @todo Remove this at some point. This isn't the responsibility of the FileIndex.
  11794. */
  11795. toStats() {
  11796. return this.stats;
  11797. }
  11798. /**
  11799. * Returns the directory listing for this directory. Paths in the directory are
  11800. * relative to the directory's path.
  11801. * @return The directory listing for this directory.
  11802. */
  11803. get listing() {
  11804. return [...this._listing.keys()];
  11805. }
  11806. /**
  11807. * Returns the inode for the indicated item, or null if it does not exist.
  11808. * @param path Name of item in this directory.
  11809. */
  11810. get(path) {
  11811. return this._listing.get(path);
  11812. }
  11813. /**
  11814. * Add the given item to the directory listing. Note that the given inode is
  11815. * not copied, and will be mutated by the DirInode if it is a DirInode.
  11816. * @param path Item name to add to the directory listing.
  11817. * @param inode The inode for the
  11818. * item to add to the directory inode.
  11819. * @return True if it was added, false if it already existed.
  11820. */
  11821. add(path, inode) {
  11822. if (this._listing.has(path)) {
  11823. return false;
  11824. }
  11825. this._listing.set(path, inode);
  11826. return true;
  11827. }
  11828. /**
  11829. * Removes the given item from the directory listing.
  11830. * @param path Name of item to remove from the directory listing.
  11831. * @return Returns the item
  11832. * removed, or null if the item did not exist.
  11833. */
  11834. remove(path) {
  11835. const item = this._listing.get(path);
  11836. if (!item) {
  11837. return;
  11838. }
  11839. this._listing.delete(path);
  11840. return item;
  11841. }
  11842. };
  11843. var IndexFS = class extends Readonly(FileSystem) {
  11844. static {
  11845. __name(this, "IndexFS");
  11846. }
  11847. constructor(index) {
  11848. super();
  11849. this._index = FileIndex.FromListing(index);
  11850. }
  11851. async stat(path) {
  11852. const inode = this._index.get(path);
  11853. if (!inode) {
  11854. throw ErrnoError.With("ENOENT", path, "stat");
  11855. }
  11856. if (inode.isDirectory()) {
  11857. return inode.stats;
  11858. }
  11859. if (inode.isFile()) {
  11860. return this.statFileInode(inode, path);
  11861. }
  11862. throw new ErrnoError(22 /* EINVAL */, "Invalid inode.");
  11863. }
  11864. statSync(path) {
  11865. const inode = this._index.get(path);
  11866. if (!inode) {
  11867. throw ErrnoError.With("ENOENT", path, "stat");
  11868. }
  11869. if (inode.isDirectory()) {
  11870. return inode.stats;
  11871. }
  11872. if (inode.isFile()) {
  11873. return this.statFileInodeSync(inode, path);
  11874. }
  11875. throw new ErrnoError(22 /* EINVAL */, "Invalid inode.");
  11876. }
  11877. async openFile(path, flag, cred2) {
  11878. if (isWriteable(flag)) {
  11879. throw new ErrnoError(1 /* EPERM */, path);
  11880. }
  11881. const inode = this._index.get(path);
  11882. if (!inode) {
  11883. throw ErrnoError.With("ENOENT", path, "openFile");
  11884. }
  11885. if (!inode.toStats().hasAccess(flagToMode(flag), cred2)) {
  11886. throw ErrnoError.With("EACCES", path, "openFile");
  11887. }
  11888. if (inode.isDirectory()) {
  11889. const stats = inode.stats;
  11890. return new NoSyncFile(this, path, flag, stats, stats.fileData);
  11891. }
  11892. return this.openFileInode(inode, path, flag);
  11893. }
  11894. openFileSync(path, flag, cred2) {
  11895. if (isWriteable(flag)) {
  11896. throw new ErrnoError(1 /* EPERM */, path);
  11897. }
  11898. const inode = this._index.get(path);
  11899. if (!inode) {
  11900. throw ErrnoError.With("ENOENT", path, "openFile");
  11901. }
  11902. if (!inode.toStats().hasAccess(flagToMode(flag), cred2)) {
  11903. throw ErrnoError.With("EACCES", path, "openFile");
  11904. }
  11905. if (inode.isDirectory()) {
  11906. const stats = inode.stats;
  11907. return new NoSyncFile(this, path, flag, stats, stats.fileData);
  11908. }
  11909. return this.openFileInodeSync(inode, path, flag);
  11910. }
  11911. async readdir(path) {
  11912. const inode = this._index.get(path);
  11913. if (!inode) {
  11914. throw ErrnoError.With("ENOENT", path, "readdir");
  11915. }
  11916. if (inode.isDirectory()) {
  11917. return inode.listing;
  11918. }
  11919. throw ErrnoError.With("ENOTDIR", path, "readdir");
  11920. }
  11921. readdirSync(path) {
  11922. const inode = this._index.get(path);
  11923. if (!inode) {
  11924. throw ErrnoError.With("ENOENT", path, "readdir");
  11925. }
  11926. if (inode.isDirectory()) {
  11927. return inode.listing;
  11928. }
  11929. throw ErrnoError.With("ENOTDIR", path, "readdir");
  11930. }
  11931. };
  11932. var SyncIndexFS = class extends IndexFS {
  11933. static {
  11934. __name(this, "SyncIndexFS");
  11935. }
  11936. async statFileInode(inode, path) {
  11937. return this.statFileInodeSync(inode, path);
  11938. }
  11939. async openFileInode(inode, path, flag) {
  11940. return this.openFileInodeSync(inode, path, flag);
  11941. }
  11942. };
  11943. var AsyncIndexFS = class extends IndexFS {
  11944. static {
  11945. __name(this, "AsyncIndexFS");
  11946. }
  11947. statFileInodeSync(inode, path) {
  11948. throw ErrnoError.With("ENOSYS", path, "AsyncIndexFS.statFileInodeSync");
  11949. }
  11950. openFileInodeSync(inode, path, flag) {
  11951. throw ErrnoError.With("ENOSYS", path, "AsyncIndexFS.openFileInodeSync");
  11952. }
  11953. };
  11954. // src/backends/fetch.ts
  11955. function convertError(e) {
  11956. throw new ErrnoError(5 /* EIO */, e.message);
  11957. }
  11958. __name(convertError, "convertError");
  11959. async function fetchFile(path, type) {
  11960. const response = await fetch(path).catch(convertError);
  11961. if (!response.ok) {
  11962. throw new ErrnoError(5 /* EIO */, "fetch failed: response returned code " + response.status);
  11963. }
  11964. switch (type) {
  11965. case "buffer":
  11966. const arrayBuffer = await response.arrayBuffer().catch(convertError);
  11967. return new Uint8Array(arrayBuffer);
  11968. case "json":
  11969. return response.json().catch(convertError);
  11970. default:
  11971. throw new ErrnoError(22 /* EINVAL */, "Invalid download type: " + type);
  11972. }
  11973. }
  11974. __name(fetchFile, "fetchFile");
  11975. async function fetchSize(path) {
  11976. const response = await fetch(path, { method: "HEAD" }).catch(convertError);
  11977. if (!response.ok) {
  11978. throw new ErrnoError(5 /* EIO */, "fetch failed: HEAD response returned code " + response.status);
  11979. }
  11980. return parseInt(response.headers.get("Content-Length") || "-1", 10);
  11981. }
  11982. __name(fetchSize, "fetchSize");
  11983. var FetchFS = class _FetchFS extends AsyncIndexFS {
  11984. static {
  11985. __name(this, "FetchFS");
  11986. }
  11987. async _initialize(index) {
  11988. if (typeof index != "string") {
  11989. this._index = FileIndex.FromListing(index);
  11990. return;
  11991. }
  11992. try {
  11993. const response = await fetch(index);
  11994. this._index = FileIndex.FromListing(await response.json());
  11995. } catch (e) {
  11996. throw new ErrnoError(22 /* EINVAL */, "Invalid or unavailable file listing tree");
  11997. }
  11998. }
  11999. async ready() {
  12000. await this._init;
  12001. }
  12002. constructor({ index = "index.json", baseUrl = "" }) {
  12003. super({});
  12004. if (baseUrl.at(-1) != "/") {
  12005. baseUrl += "/";
  12006. }
  12007. this.prefixUrl = baseUrl;
  12008. this._init = this._initialize(index);
  12009. }
  12010. metadata() {
  12011. return {
  12012. ...super.metadata(),
  12013. name: _FetchFS.name,
  12014. readonly: true
  12015. };
  12016. }
  12017. empty() {
  12018. for (const file of this._index.files()) {
  12019. delete file.data.fileData;
  12020. }
  12021. }
  12022. /**
  12023. * Special function: Preload the given file into the index.
  12024. * @param path
  12025. * @param buffer
  12026. */
  12027. preloadFile(path, buffer) {
  12028. const inode = this._index.get(path);
  12029. if (!inode) {
  12030. throw ErrnoError.With("ENOENT", path, "preloadFile");
  12031. }
  12032. if (!inode.isFile()) {
  12033. throw ErrnoError.With("EISDIR", path, "preloadFile");
  12034. }
  12035. const stats = inode.data;
  12036. stats.size = buffer.length;
  12037. stats.fileData = buffer;
  12038. }
  12039. async statFileInode(inode, path) {
  12040. const stats = inode.data;
  12041. if (stats.size < 0) {
  12042. stats.size = await this._fetchSize(path);
  12043. }
  12044. return stats;
  12045. }
  12046. async openFileInode(inode, path, flag) {
  12047. const stats = inode.data;
  12048. if (stats.fileData) {
  12049. return new NoSyncFile(this, path, flag, new Stats(stats), stats.fileData);
  12050. }
  12051. const data = await this._fetchFile(path, "buffer");
  12052. stats.size = data.length;
  12053. stats.fileData = data;
  12054. return new NoSyncFile(this, path, flag, new Stats(stats), data);
  12055. }
  12056. _getRemotePath(filePath) {
  12057. if (filePath.charAt(0) === "/") {
  12058. filePath = filePath.slice(1);
  12059. }
  12060. return this.prefixUrl + filePath;
  12061. }
  12062. _fetchFile(path, type) {
  12063. return fetchFile(this._getRemotePath(path), type);
  12064. }
  12065. /**
  12066. * Only requests the HEAD content, for the file size.
  12067. */
  12068. _fetchSize(path) {
  12069. return fetchSize(this._getRemotePath(path));
  12070. }
  12071. };
  12072. var Fetch = {
  12073. name: "Fetch",
  12074. options: {
  12075. index: {
  12076. type: ["string", "object"],
  12077. required: false,
  12078. description: "URL to a file index as a JSON file or the file index object itself, generated with the make-index script. Defaults to `index.json`."
  12079. },
  12080. baseUrl: {
  12081. type: "string",
  12082. required: false,
  12083. description: "Used as the URL prefix for fetched files. Default: Fetch files relative to the index."
  12084. }
  12085. },
  12086. isAvailable: /* @__PURE__ */ __name(function() {
  12087. return typeof globalThis.fetch == "function";
  12088. }, "isAvailable"),
  12089. create: /* @__PURE__ */ __name(function(options) {
  12090. return new FetchFS(options);
  12091. }, "create")
  12092. };
  12093. // src/mutex.ts
  12094. var Mutex = class {
  12095. constructor() {
  12096. this._locks = /* @__PURE__ */ new Map();
  12097. }
  12098. static {
  12099. __name(this, "Mutex");
  12100. }
  12101. lock(path) {
  12102. return new Promise((resolve2) => {
  12103. if (this._locks.has(path)) {
  12104. this._locks.get(path).push(resolve2);
  12105. } else {
  12106. this._locks.set(path, [resolve2]);
  12107. }
  12108. });
  12109. }
  12110. unlock(path) {
  12111. if (!this._locks.has(path)) {
  12112. throw new ErrnoError(1 /* EPERM */, "Can not unlock an already unlocked path", path);
  12113. }
  12114. const next = this._locks.get(path)?.shift();
  12115. if (next) {
  12116. setTimeout(next, 0);
  12117. return;
  12118. }
  12119. this._locks.delete(path);
  12120. }
  12121. tryLock(path) {
  12122. if (this._locks.has(path)) {
  12123. return false;
  12124. }
  12125. this._locks.set(path, []);
  12126. return true;
  12127. }
  12128. isLocked(path) {
  12129. return this._locks.has(path);
  12130. }
  12131. };
  12132. // src/backends/locked.ts
  12133. var LockedFS = class {
  12134. constructor(fs) {
  12135. this.fs = fs;
  12136. this._mu = new Mutex();
  12137. }
  12138. static {
  12139. __name(this, "LockedFS");
  12140. }
  12141. async ready() {
  12142. await this.fs.ready();
  12143. }
  12144. metadata() {
  12145. return {
  12146. ...this.fs.metadata(),
  12147. name: "Locked<" + this.fs.metadata().name + ">"
  12148. };
  12149. }
  12150. async rename(oldPath, newPath, cred2) {
  12151. await this._mu.lock(oldPath);
  12152. await this.fs.rename(oldPath, newPath, cred2);
  12153. this._mu.unlock(oldPath);
  12154. }
  12155. renameSync(oldPath, newPath, cred2) {
  12156. if (this._mu.isLocked(oldPath)) {
  12157. throw ErrnoError.With("EBUSY", oldPath, "rename");
  12158. }
  12159. return this.fs.renameSync(oldPath, newPath, cred2);
  12160. }
  12161. async stat(path, cred2) {
  12162. await this._mu.lock(path);
  12163. const stats = await this.fs.stat(path, cred2);
  12164. this._mu.unlock(path);
  12165. return stats;
  12166. }
  12167. statSync(path, cred2) {
  12168. if (this._mu.isLocked(path)) {
  12169. throw ErrnoError.With("EBUSY", path, "stat");
  12170. }
  12171. return this.fs.statSync(path, cred2);
  12172. }
  12173. async openFile(path, flag, cred2) {
  12174. await this._mu.lock(path);
  12175. const fd = await this.fs.openFile(path, flag, cred2);
  12176. this._mu.unlock(path);
  12177. return fd;
  12178. }
  12179. openFileSync(path, flag, cred2) {
  12180. if (this._mu.isLocked(path)) {
  12181. throw ErrnoError.With("EBUSY", path, "openFile");
  12182. }
  12183. return this.fs.openFileSync(path, flag, cred2);
  12184. }
  12185. async createFile(path, flag, mode, cred2) {
  12186. await this._mu.lock(path);
  12187. const fd = await this.fs.createFile(path, flag, mode, cred2);
  12188. this._mu.unlock(path);
  12189. return fd;
  12190. }
  12191. createFileSync(path, flag, mode, cred2) {
  12192. if (this._mu.isLocked(path)) {
  12193. throw ErrnoError.With("EBUSY", path, "createFile");
  12194. }
  12195. return this.fs.createFileSync(path, flag, mode, cred2);
  12196. }
  12197. async unlink(path, cred2) {
  12198. await this._mu.lock(path);
  12199. await this.fs.unlink(path, cred2);
  12200. this._mu.unlock(path);
  12201. }
  12202. unlinkSync(path, cred2) {
  12203. if (this._mu.isLocked(path)) {
  12204. throw ErrnoError.With("EBUSY", path, "unlink");
  12205. }
  12206. return this.fs.unlinkSync(path, cred2);
  12207. }
  12208. async rmdir(path, cred2) {
  12209. await this._mu.lock(path);
  12210. await this.fs.rmdir(path, cred2);
  12211. this._mu.unlock(path);
  12212. }
  12213. rmdirSync(path, cred2) {
  12214. if (this._mu.isLocked(path)) {
  12215. throw ErrnoError.With("EBUSY", path, "rmdir");
  12216. }
  12217. return this.fs.rmdirSync(path, cred2);
  12218. }
  12219. async mkdir(path, mode, cred2) {
  12220. await this._mu.lock(path);
  12221. await this.fs.mkdir(path, mode, cred2);
  12222. this._mu.unlock(path);
  12223. }
  12224. mkdirSync(path, mode, cred2) {
  12225. if (this._mu.isLocked(path)) {
  12226. throw ErrnoError.With("EBUSY", path, "mkdir");
  12227. }
  12228. return this.fs.mkdirSync(path, mode, cred2);
  12229. }
  12230. async readdir(path, cred2) {
  12231. await this._mu.lock(path);
  12232. const files = await this.fs.readdir(path, cred2);
  12233. this._mu.unlock(path);
  12234. return files;
  12235. }
  12236. readdirSync(path, cred2) {
  12237. if (this._mu.isLocked(path)) {
  12238. throw ErrnoError.With("EBUSY", path, "readdir");
  12239. }
  12240. return this.fs.readdirSync(path, cred2);
  12241. }
  12242. async exists(path, cred2) {
  12243. await this._mu.lock(path);
  12244. const exists3 = await this.fs.exists(path, cred2);
  12245. this._mu.unlock(path);
  12246. return exists3;
  12247. }
  12248. existsSync(path, cred2) {
  12249. if (this._mu.isLocked(path)) {
  12250. throw ErrnoError.With("EBUSY", path, "exists");
  12251. }
  12252. return this.fs.existsSync(path, cred2);
  12253. }
  12254. async link(srcpath, dstpath, cred2) {
  12255. await this._mu.lock(srcpath);
  12256. await this.fs.link(srcpath, dstpath, cred2);
  12257. this._mu.unlock(srcpath);
  12258. }
  12259. linkSync(srcpath, dstpath, cred2) {
  12260. if (this._mu.isLocked(srcpath)) {
  12261. throw ErrnoError.With("EBUSY", srcpath, "link");
  12262. }
  12263. return this.fs.linkSync(srcpath, dstpath, cred2);
  12264. }
  12265. async sync(path, data, stats) {
  12266. await this._mu.lock(path);
  12267. await this.fs.sync(path, data, stats);
  12268. this._mu.unlock(path);
  12269. }
  12270. syncSync(path, data, stats) {
  12271. if (this._mu.isLocked(path)) {
  12272. throw ErrnoError.With("EBUSY", path, "sync");
  12273. }
  12274. return this.fs.syncSync(path, data, stats);
  12275. }
  12276. };
  12277. // src/backends/overlay.ts
  12278. var deletionLogPath = "/.deleted";
  12279. var UnlockedOverlayFS = class extends FileSystem {
  12280. constructor({ writable, readable }) {
  12281. super();
  12282. this._isInitialized = false;
  12283. this._deletedFiles = /* @__PURE__ */ new Set();
  12284. this._deleteLog = "";
  12285. // If 'true', we have scheduled a delete log update.
  12286. this._deleteLogUpdatePending = false;
  12287. // If 'true', a delete log update is needed after the scheduled delete log
  12288. // update finishes.
  12289. this._deleteLogUpdateNeeded = false;
  12290. this._writable = writable;
  12291. this._readable = readable;
  12292. if (this._writable.metadata().readonly) {
  12293. throw new ErrnoError(22 /* EINVAL */, "Writable file system must be writable.");
  12294. }
  12295. this._ready = this._initialize();
  12296. }
  12297. static {
  12298. __name(this, "UnlockedOverlayFS");
  12299. }
  12300. async ready() {
  12301. await this._readable.ready();
  12302. await this._writable.ready();
  12303. await this._ready;
  12304. }
  12305. metadata() {
  12306. return {
  12307. ...super.metadata(),
  12308. name: OverlayFS.name
  12309. };
  12310. }
  12311. getOverlayedFileSystems() {
  12312. return {
  12313. readable: this._readable,
  12314. writable: this._writable
  12315. };
  12316. }
  12317. async sync(path, data, stats) {
  12318. const cred2 = stats.cred(0, 0);
  12319. await this.createParentDirectories(path, cred2);
  12320. await this._writable.sync(path, data, stats);
  12321. }
  12322. syncSync(path, data, stats) {
  12323. const cred2 = stats.cred(0, 0);
  12324. this.createParentDirectoriesSync(path, cred2);
  12325. this._writable.syncSync(path, data, stats);
  12326. }
  12327. /**
  12328. * Called once to load up metadata stored on the writable file system.
  12329. * @internal
  12330. */
  12331. async _initialize() {
  12332. if (this._isInitialized) {
  12333. return;
  12334. }
  12335. try {
  12336. const file = await this._writable.openFile(deletionLogPath, parseFlag("r"), rootCred);
  12337. const { size } = await file.stat();
  12338. const { buffer } = await file.read(new Uint8Array(size));
  12339. this._deleteLog = decode(buffer);
  12340. } catch (err) {
  12341. if (err.errno !== 2 /* ENOENT */) {
  12342. throw err;
  12343. }
  12344. }
  12345. this._isInitialized = true;
  12346. this._reparseDeletionLog();
  12347. }
  12348. getDeletionLog() {
  12349. return this._deleteLog;
  12350. }
  12351. restoreDeletionLog(log, cred2) {
  12352. this._deleteLog = log;
  12353. this._reparseDeletionLog();
  12354. this.updateLog("", cred2);
  12355. }
  12356. async rename(oldPath, newPath, cred2) {
  12357. this.checkInitialized();
  12358. this.checkPath(oldPath);
  12359. this.checkPath(newPath);
  12360. try {
  12361. await this._writable.rename(oldPath, newPath, cred2);
  12362. } catch (e) {
  12363. if (this._deletedFiles.has(oldPath)) {
  12364. throw ErrnoError.With("ENOENT", oldPath, "rename");
  12365. }
  12366. }
  12367. }
  12368. renameSync(oldPath, newPath, cred2) {
  12369. this.checkInitialized();
  12370. this.checkPath(oldPath);
  12371. this.checkPath(newPath);
  12372. try {
  12373. this._writable.renameSync(oldPath, newPath, cred2);
  12374. } catch (e) {
  12375. if (this._deletedFiles.has(oldPath)) {
  12376. throw ErrnoError.With("ENOENT", oldPath, "rename");
  12377. }
  12378. }
  12379. }
  12380. async stat(path, cred2) {
  12381. this.checkInitialized();
  12382. try {
  12383. return this._writable.stat(path, cred2);
  12384. } catch (e) {
  12385. if (this._deletedFiles.has(path)) {
  12386. throw ErrnoError.With("ENOENT", path, "stat");
  12387. }
  12388. const oldStat = new Stats(await this._readable.stat(path, cred2));
  12389. oldStat.mode |= 146;
  12390. return oldStat;
  12391. }
  12392. }
  12393. statSync(path, cred2) {
  12394. this.checkInitialized();
  12395. try {
  12396. return this._writable.statSync(path, cred2);
  12397. } catch (e) {
  12398. if (this._deletedFiles.has(path)) {
  12399. throw ErrnoError.With("ENOENT", path, "stat");
  12400. }
  12401. const oldStat = new Stats(this._readable.statSync(path, cred2));
  12402. oldStat.mode |= 146;
  12403. return oldStat;
  12404. }
  12405. }
  12406. async openFile(path, flag, cred2) {
  12407. if (await this._writable.exists(path, cred2)) {
  12408. return this._writable.openFile(path, flag, cred2);
  12409. }
  12410. const file = await this._readable.openFile(path, parseFlag("r"), cred2);
  12411. const stats = new Stats(await file.stat());
  12412. const { buffer } = await file.read(new Uint8Array(stats.size));
  12413. return new PreloadFile(this, path, flag, stats, buffer);
  12414. }
  12415. openFileSync(path, flag, cred2) {
  12416. if (this._writable.existsSync(path, cred2)) {
  12417. return this._writable.openFileSync(path, flag, cred2);
  12418. }
  12419. const file = this._readable.openFileSync(path, parseFlag("r"), cred2);
  12420. const stats = Stats.clone(file.statSync());
  12421. const data = new Uint8Array(stats.size);
  12422. file.readSync(data);
  12423. return new PreloadFile(this, path, flag, stats, data);
  12424. }
  12425. async createFile(path, flag, mode, cred2) {
  12426. this.checkInitialized();
  12427. await this._writable.createFile(path, flag, mode, cred2);
  12428. return this.openFile(path, flag, cred2);
  12429. }
  12430. createFileSync(path, flag, mode, cred2) {
  12431. this.checkInitialized();
  12432. this._writable.createFileSync(path, flag, mode, cred2);
  12433. return this.openFileSync(path, flag, cred2);
  12434. }
  12435. async link(srcpath, dstpath, cred2) {
  12436. this.checkInitialized();
  12437. await this._writable.link(srcpath, dstpath, cred2);
  12438. }
  12439. linkSync(srcpath, dstpath, cred2) {
  12440. this.checkInitialized();
  12441. this._writable.linkSync(srcpath, dstpath, cred2);
  12442. }
  12443. async unlink(path, cred2) {
  12444. this.checkInitialized();
  12445. this.checkPath(path);
  12446. if (!await this.exists(path, cred2)) {
  12447. throw ErrnoError.With("ENOENT", path, "unlink");
  12448. }
  12449. if (await this._writable.exists(path, cred2)) {
  12450. await this._writable.unlink(path, cred2);
  12451. }
  12452. if (await this.exists(path, cred2)) {
  12453. this.deletePath(path, cred2);
  12454. }
  12455. }
  12456. unlinkSync(path, cred2) {
  12457. this.checkInitialized();
  12458. this.checkPath(path);
  12459. if (!this.existsSync(path, cred2)) {
  12460. throw ErrnoError.With("ENOENT", path, "unlink");
  12461. }
  12462. if (this._writable.existsSync(path, cred2)) {
  12463. this._writable.unlinkSync(path, cred2);
  12464. }
  12465. if (this.existsSync(path, cred2)) {
  12466. this.deletePath(path, cred2);
  12467. }
  12468. }
  12469. async rmdir(path, cred2) {
  12470. this.checkInitialized();
  12471. if (!await this.exists(path, cred2)) {
  12472. throw ErrnoError.With("ENOENT", path, "rmdir");
  12473. }
  12474. if (await this._writable.exists(path, cred2)) {
  12475. await this._writable.rmdir(path, cred2);
  12476. }
  12477. if (await this.exists(path, cred2)) {
  12478. if ((await this.readdir(path, cred2)).length > 0) {
  12479. throw ErrnoError.With("ENOTEMPTY", path, "rmdir");
  12480. } else {
  12481. this.deletePath(path, cred2);
  12482. }
  12483. }
  12484. }
  12485. rmdirSync(path, cred2) {
  12486. this.checkInitialized();
  12487. if (!this.existsSync(path, cred2)) {
  12488. throw ErrnoError.With("ENOENT", path, "rmdir");
  12489. }
  12490. if (this._writable.existsSync(path, cred2)) {
  12491. this._writable.rmdirSync(path, cred2);
  12492. }
  12493. if (this.existsSync(path, cred2)) {
  12494. if (this.readdirSync(path, cred2).length > 0) {
  12495. throw ErrnoError.With("ENOTEMPTY", path, "rmdir");
  12496. } else {
  12497. this.deletePath(path, cred2);
  12498. }
  12499. }
  12500. }
  12501. async mkdir(path, mode, cred2) {
  12502. this.checkInitialized();
  12503. if (await this.exists(path, cred2)) {
  12504. throw ErrnoError.With("EEXIST", path, "mkdir");
  12505. }
  12506. await this.createParentDirectories(path, cred2);
  12507. await this._writable.mkdir(path, mode, cred2);
  12508. }
  12509. mkdirSync(path, mode, cred2) {
  12510. this.checkInitialized();
  12511. if (this.existsSync(path, cred2)) {
  12512. throw ErrnoError.With("EEXIST", path, "mkdir");
  12513. }
  12514. this.createParentDirectoriesSync(path, cred2);
  12515. this._writable.mkdirSync(path, mode, cred2);
  12516. }
  12517. async readdir(path, cred2) {
  12518. this.checkInitialized();
  12519. const dirStats = await this.stat(path, cred2);
  12520. if (!dirStats.isDirectory()) {
  12521. throw ErrnoError.With("ENOTDIR", path, "readdir");
  12522. }
  12523. const contents = [];
  12524. try {
  12525. contents.push(...await this._writable.readdir(path, cred2));
  12526. } catch (e) {
  12527. }
  12528. try {
  12529. contents.push(...(await this._readable.readdir(path, cred2)).filter((fPath) => !this._deletedFiles.has(`${path}/${fPath}`)));
  12530. } catch (e) {
  12531. }
  12532. const seenMap = {};
  12533. return contents.filter((path2) => {
  12534. const result = !seenMap[path2];
  12535. seenMap[path2] = true;
  12536. return result;
  12537. });
  12538. }
  12539. readdirSync(path, cred2) {
  12540. this.checkInitialized();
  12541. const dirStats = this.statSync(path, cred2);
  12542. if (!dirStats.isDirectory()) {
  12543. throw ErrnoError.With("ENOTDIR", path, "readdir");
  12544. }
  12545. let contents = [];
  12546. try {
  12547. contents = contents.concat(this._writable.readdirSync(path, cred2));
  12548. } catch (e) {
  12549. }
  12550. try {
  12551. contents = contents.concat(this._readable.readdirSync(path, cred2).filter((fPath) => !this._deletedFiles.has(`${path}/${fPath}`)));
  12552. } catch (e) {
  12553. }
  12554. const seenMap = {};
  12555. return contents.filter((path2) => {
  12556. const result = !seenMap[path2];
  12557. seenMap[path2] = true;
  12558. return result;
  12559. });
  12560. }
  12561. deletePath(path, cred2) {
  12562. this._deletedFiles.add(path);
  12563. this.updateLog(`d${path}
  12564. `, cred2);
  12565. }
  12566. async updateLog(addition, cred2) {
  12567. this._deleteLog += addition;
  12568. if (this._deleteLogUpdatePending) {
  12569. this._deleteLogUpdateNeeded = true;
  12570. return;
  12571. }
  12572. this._deleteLogUpdatePending = true;
  12573. const log = await this._writable.openFile(deletionLogPath, parseFlag("w"), cred2);
  12574. try {
  12575. await log.write(encode(this._deleteLog));
  12576. if (this._deleteLogUpdateNeeded) {
  12577. this._deleteLogUpdateNeeded = false;
  12578. this.updateLog("", cred2);
  12579. }
  12580. } catch (e) {
  12581. this._deleteLogError = e;
  12582. } finally {
  12583. this._deleteLogUpdatePending = false;
  12584. }
  12585. }
  12586. _reparseDeletionLog() {
  12587. this._deletedFiles.clear();
  12588. for (const entry of this._deleteLog.split("\n")) {
  12589. if (!entry.startsWith("d")) {
  12590. continue;
  12591. }
  12592. this._deletedFiles.add(entry.slice(1));
  12593. }
  12594. }
  12595. checkInitialized() {
  12596. if (!this._isInitialized) {
  12597. throw new ErrnoError(1 /* EPERM */, "OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.");
  12598. }
  12599. if (!this._deleteLogError) {
  12600. return;
  12601. }
  12602. const error = this._deleteLogError;
  12603. delete this._deleteLogError;
  12604. throw error;
  12605. }
  12606. checkPath(path) {
  12607. if (path == deletionLogPath) {
  12608. throw ErrnoError.With("EPERM", path, "checkPath");
  12609. }
  12610. }
  12611. /**
  12612. * With the given path, create the needed parent directories on the writable storage
  12613. * should they not exist. Use modes from the read-only storage.
  12614. */
  12615. createParentDirectoriesSync(path, cred2) {
  12616. let parent = dirname(path), toCreate = [];
  12617. while (!this._writable.existsSync(parent, cred2)) {
  12618. toCreate.push(parent);
  12619. parent = dirname(parent);
  12620. }
  12621. toCreate = toCreate.reverse();
  12622. for (const p of toCreate) {
  12623. this._writable.mkdirSync(p, this.statSync(p, cred2).mode, cred2);
  12624. }
  12625. }
  12626. async createParentDirectories(path, cred2) {
  12627. let parent = dirname(path), toCreate = [];
  12628. while (!await this._writable.exists(parent, cred2)) {
  12629. toCreate.push(parent);
  12630. parent = dirname(parent);
  12631. }
  12632. toCreate = toCreate.reverse();
  12633. for (const p of toCreate) {
  12634. const stats = await this.stat(p, cred2);
  12635. await this._writable.mkdir(p, stats.mode, cred2);
  12636. }
  12637. }
  12638. /**
  12639. * Helper function:
  12640. * - Ensures p is on writable before proceeding. Throws an error if it doesn't exist.
  12641. * - Calls f to perform operation on writable.
  12642. */
  12643. operateOnWritable(path, cred2) {
  12644. if (!this.existsSync(path, cred2)) {
  12645. throw ErrnoError.With("ENOENT", path, "operateOnWriteable");
  12646. }
  12647. if (!this._writable.existsSync(path, cred2)) {
  12648. this.copyToWritableSync(path, cred2);
  12649. }
  12650. }
  12651. async operateOnWritableAsync(path, cred2) {
  12652. if (!await this.exists(path, cred2)) {
  12653. throw ErrnoError.With("ENOENT", path, "operateOnWritable");
  12654. }
  12655. if (!await this._writable.exists(path, cred2)) {
  12656. return this.copyToWritable(path, cred2);
  12657. }
  12658. }
  12659. /**
  12660. * Copy from readable to writable storage.
  12661. * PRECONDITION: File does not exist on writable storage.
  12662. */
  12663. copyToWritableSync(path, cred2) {
  12664. const stats = this.statSync(path, cred2);
  12665. if (stats.isDirectory()) {
  12666. this._writable.mkdirSync(path, stats.mode, cred2);
  12667. return;
  12668. }
  12669. const data = new Uint8Array(stats.size);
  12670. const readable = this._readable.openFileSync(path, parseFlag("r"), cred2);
  12671. readable.readSync(data);
  12672. readable.closeSync();
  12673. const writable = this._writable.openFileSync(path, parseFlag("w"), cred2);
  12674. writable.writeSync(data);
  12675. writable.closeSync();
  12676. }
  12677. async copyToWritable(path, cred2) {
  12678. const stats = await this.stat(path, cred2);
  12679. if (stats.isDirectory()) {
  12680. await this._writable.mkdir(path, stats.mode, cred2);
  12681. return;
  12682. }
  12683. const data = new Uint8Array(stats.size);
  12684. const readable = await this._readable.openFile(path, parseFlag("r"), cred2);
  12685. await readable.read(data);
  12686. await readable.close();
  12687. const writable = await this._writable.openFile(path, parseFlag("w"), cred2);
  12688. await writable.write(data);
  12689. await writable.close();
  12690. }
  12691. };
  12692. var OverlayFS = class extends LockedFS {
  12693. static {
  12694. __name(this, "OverlayFS");
  12695. }
  12696. /**
  12697. * @param options The options to initialize the OverlayFS with
  12698. */
  12699. constructor(options) {
  12700. super(new UnlockedOverlayFS(options));
  12701. }
  12702. getOverlayedFileSystems() {
  12703. return super.fs.getOverlayedFileSystems();
  12704. }
  12705. getDeletionLog() {
  12706. return super.fs.getDeletionLog();
  12707. }
  12708. resDeletionLog() {
  12709. return super.fs.getDeletionLog();
  12710. }
  12711. unwrap() {
  12712. return super.fs;
  12713. }
  12714. };
  12715. var Overlay = {
  12716. name: "Overlay",
  12717. options: {
  12718. writable: {
  12719. type: "object",
  12720. required: true,
  12721. description: "The file system to write modified files to."
  12722. },
  12723. readable: {
  12724. type: "object",
  12725. required: true,
  12726. description: "The file system that initially populates this file system."
  12727. }
  12728. },
  12729. isAvailable: /* @__PURE__ */ __name(function() {
  12730. return true;
  12731. }, "isAvailable"),
  12732. create: /* @__PURE__ */ __name(function(options) {
  12733. return new OverlayFS(options);
  12734. }, "create")
  12735. };
  12736. // src/backends/backend.ts
  12737. function isBackend(arg) {
  12738. return arg != null && typeof arg == "object" && "isAvailable" in arg && typeof arg.isAvailable == "function" && "create" in arg && typeof arg.create == "function";
  12739. }
  12740. __name(isBackend, "isBackend");
  12741. async function checkOptions(backend, opts) {
  12742. if (typeof opts != "object" || opts === null) {
  12743. throw new ErrnoError(22 /* EINVAL */, "Invalid options");
  12744. }
  12745. for (const [optName, opt] of Object.entries(backend.options)) {
  12746. const providedValue = opts?.[optName];
  12747. if (providedValue === void 0 || providedValue === null) {
  12748. if (!opt.required) {
  12749. continue;
  12750. }
  12751. const incorrectOptions = Object.keys(opts).filter((o) => !(o in backend.options)).map((a) => {
  12752. return { str: a, distance: levenshtein(optName, a) };
  12753. }).filter((o) => o.distance < 5).sort((a, b) => a.distance - b.distance);
  12754. throw new ErrnoError(
  12755. 22 /* EINVAL */,
  12756. `${backend.name}: Required option '${optName}' not provided.${incorrectOptions.length > 0 ? ` You provided '${incorrectOptions[0].str}', did you mean '${optName}'.` : ""}`
  12757. );
  12758. }
  12759. const typeMatches = Array.isArray(opt.type) ? opt.type.indexOf(typeof providedValue) != -1 : typeof providedValue == opt.type;
  12760. if (!typeMatches) {
  12761. throw new ErrnoError(
  12762. 22 /* EINVAL */,
  12763. `${backend.name}: Value provided for option ${optName} is not the proper type. Expected ${Array.isArray(opt.type) ? `one of {${opt.type.join(", ")}}` : opt.type}, but received ${typeof providedValue}`
  12764. );
  12765. }
  12766. if (opt.validator) {
  12767. await opt.validator(providedValue);
  12768. }
  12769. }
  12770. }
  12771. __name(checkOptions, "checkOptions");
  12772. function isBackendConfig(arg) {
  12773. return arg != null && typeof arg == "object" && "backend" in arg && isBackend(arg.backend);
  12774. }
  12775. __name(isBackendConfig, "isBackendConfig");
  12776. // src/emulation/index.ts
  12777. var emulation_exports = {};
  12778. __export(emulation_exports, {
  12779. BigIntStats: () => BigIntStats,
  12780. Dir: () => Dir,
  12781. Dirent: () => Dirent,
  12782. ReadStream: () => ReadStream,
  12783. Stats: () => Stats,
  12784. StatsFs: () => StatsFs,
  12785. WriteStream: () => WriteStream,
  12786. access: () => access2,
  12787. accessSync: () => accessSync,
  12788. appendFile: () => appendFile2,
  12789. appendFileSync: () => appendFileSync,
  12790. chmod: () => chmod2,
  12791. chmodSync: () => chmodSync,
  12792. chown: () => chown2,
  12793. chownSync: () => chownSync,
  12794. close: () => close,
  12795. closeSync: () => closeSync,
  12796. constants: () => constants_exports,
  12797. copyFile: () => copyFile2,
  12798. copyFileSync: () => copyFileSync,
  12799. cp: () => cp2,
  12800. cpSync: () => cpSync,
  12801. createReadStream: () => createReadStream,
  12802. createWriteStream: () => createWriteStream,
  12803. exists: () => exists2,
  12804. existsSync: () => existsSync,
  12805. fchmod: () => fchmod,
  12806. fchmodSync: () => fchmodSync,
  12807. fchown: () => fchown,
  12808. fchownSync: () => fchownSync,
  12809. fdatasync: () => fdatasync,
  12810. fdatasyncSync: () => fdatasyncSync,
  12811. fstat: () => fstat,
  12812. fstatSync: () => fstatSync,
  12813. fsync: () => fsync,
  12814. fsyncSync: () => fsyncSync,
  12815. ftruncate: () => ftruncate,
  12816. ftruncateSync: () => ftruncateSync,
  12817. futimes: () => futimes,
  12818. futimesSync: () => futimesSync,
  12819. lchmod: () => lchmod2,
  12820. lchmodSync: () => lchmodSync,
  12821. lchown: () => lchown2,
  12822. lchownSync: () => lchownSync,
  12823. link: () => link2,
  12824. linkSync: () => linkSync,
  12825. lopenSync: () => lopenSync,
  12826. lstat: () => lstat2,
  12827. lstatSync: () => lstatSync,
  12828. lutimes: () => lutimes2,
  12829. lutimesSync: () => lutimesSync,
  12830. mkdir: () => mkdir2,
  12831. mkdirSync: () => mkdirSync,
  12832. mkdtemp: () => mkdtemp2,
  12833. mkdtempSync: () => mkdtempSync,
  12834. mount: () => mount,
  12835. mountObject: () => mountObject,
  12836. mounts: () => mounts,
  12837. open: () => open2,
  12838. openAsBlob: () => openAsBlob,
  12839. openSync: () => openSync,
  12840. opendir: () => opendir2,
  12841. opendirSync: () => opendirSync,
  12842. promises: () => promises_exports,
  12843. read: () => read,
  12844. readFile: () => readFile2,
  12845. readFileSync: () => readFileSync,
  12846. readSync: () => readSync,
  12847. readdir: () => readdir2,
  12848. readdirSync: () => readdirSync,
  12849. readlink: () => readlink2,
  12850. readlinkSync: () => readlinkSync,
  12851. readv: () => readv,
  12852. readvSync: () => readvSync,
  12853. realpath: () => realpath2,
  12854. realpathSync: () => realpathSync,
  12855. rename: () => rename2,
  12856. renameSync: () => renameSync,
  12857. rm: () => rm2,
  12858. rmSync: () => rmSync,
  12859. rmdir: () => rmdir2,
  12860. rmdirSync: () => rmdirSync,
  12861. stat: () => stat2,
  12862. statSync: () => statSync,
  12863. statfs: () => statfs2,
  12864. statfsSync: () => statfsSync,
  12865. symlink: () => symlink2,
  12866. symlinkSync: () => symlinkSync,
  12867. truncate: () => truncate2,
  12868. truncateSync: () => truncateSync,
  12869. umount: () => umount,
  12870. unlink: () => unlink2,
  12871. unlinkSync: () => unlinkSync,
  12872. unwatchFile: () => unwatchFile,
  12873. utimes: () => utimes2,
  12874. utimesSync: () => utimesSync,
  12875. watch: () => watch2,
  12876. watchFile: () => watchFile,
  12877. write: () => write,
  12878. writeFile: () => writeFile2,
  12879. writeFileSync: () => writeFileSync,
  12880. writeSync: () => writeSync,
  12881. writev: () => writev,
  12882. writevSync: () => writevSync
  12883. });
  12884. // src/emulation/promises.ts
  12885. var promises_exports = {};
  12886. __export(promises_exports, {
  12887. FileHandle: () => FileHandle,
  12888. access: () => access,
  12889. appendFile: () => appendFile,
  12890. chmod: () => chmod,
  12891. chown: () => chown,
  12892. constants: () => constants_exports,
  12893. copyFile: () => copyFile,
  12894. cp: () => cp,
  12895. exists: () => exists,
  12896. lchmod: () => lchmod,
  12897. lchown: () => lchown,
  12898. link: () => link,
  12899. lstat: () => lstat,
  12900. lutimes: () => lutimes,
  12901. mkdir: () => mkdir,
  12902. mkdtemp: () => mkdtemp,
  12903. open: () => open,
  12904. opendir: () => opendir,
  12905. readFile: () => readFile,
  12906. readdir: () => readdir,
  12907. readlink: () => readlink,
  12908. realpath: () => realpath,
  12909. rename: () => rename,
  12910. rm: () => rm,
  12911. rmdir: () => rmdir,
  12912. stat: () => stat,
  12913. statfs: () => statfs,
  12914. symlink: () => symlink,
  12915. truncate: () => truncate,
  12916. unlink: () => unlink,
  12917. utimes: () => utimes,
  12918. watch: () => watch,
  12919. writeFile: () => writeFile
  12920. });
  12921. var import_buffer2 = __toESM(require_buffer(), 1);
  12922. // src/emulation/sync.ts
  12923. var import_buffer = __toESM(require_buffer(), 1);
  12924. // src/emulation/shared.ts
  12925. var cred = rootCred;
  12926. function setCred(val) {
  12927. cred = val;
  12928. }
  12929. __name(setCred, "setCred");
  12930. var fdMap = /* @__PURE__ */ new Map();
  12931. var nextFd2 = 100;
  12932. function file2fd(file) {
  12933. const fd = nextFd2++;
  12934. fdMap.set(fd, file);
  12935. return fd;
  12936. }
  12937. __name(file2fd, "file2fd");
  12938. function fd2file(fd) {
  12939. if (!fdMap.has(fd)) {
  12940. throw new ErrnoError(9 /* EBADF */);
  12941. }
  12942. return fdMap.get(fd);
  12943. }
  12944. __name(fd2file, "fd2file");
  12945. var mounts = /* @__PURE__ */ new Map();
  12946. mount("/", InMemory.create({ name: "root" }));
  12947. function mount(mountPoint, fs) {
  12948. if (mountPoint[0] !== "/") {
  12949. mountPoint = "/" + mountPoint;
  12950. }
  12951. mountPoint = resolve(mountPoint);
  12952. if (mounts.has(mountPoint)) {
  12953. throw new ErrnoError(22 /* EINVAL */, "Mount point " + mountPoint + " is already in use.");
  12954. }
  12955. mounts.set(mountPoint, fs);
  12956. }
  12957. __name(mount, "mount");
  12958. function umount(mountPoint) {
  12959. if (mountPoint[0] !== "/") {
  12960. mountPoint = `/${mountPoint}`;
  12961. }
  12962. mountPoint = resolve(mountPoint);
  12963. if (!mounts.has(mountPoint)) {
  12964. throw new ErrnoError(22 /* EINVAL */, "Mount point " + mountPoint + " is already unmounted.");
  12965. }
  12966. mounts.delete(mountPoint);
  12967. }
  12968. __name(umount, "umount");
  12969. function resolveMount(path) {
  12970. path = normalizePath(path);
  12971. const sortedMounts = [...mounts].sort((a, b) => a[0].length > b[0].length ? -1 : 1);
  12972. for (const [mountPoint, fs] of sortedMounts) {
  12973. if (mountPoint.length <= path.length && path.startsWith(mountPoint)) {
  12974. path = path.slice(mountPoint.length > 1 ? mountPoint.length : 0);
  12975. if (path === "") {
  12976. path = "/";
  12977. }
  12978. return { fs, path, mountPoint };
  12979. }
  12980. }
  12981. throw new ErrnoError(5 /* EIO */, "ZenFS not initialized with a file system");
  12982. }
  12983. __name(resolveMount, "resolveMount");
  12984. function fixPaths(text, paths) {
  12985. for (const [from, to] of Object.entries(paths)) {
  12986. text = text?.replaceAll(from, to);
  12987. }
  12988. return text;
  12989. }
  12990. __name(fixPaths, "fixPaths");
  12991. function fixError(e, paths) {
  12992. if (typeof e.stack == "string") {
  12993. e.stack = fixPaths(e.stack, paths);
  12994. }
  12995. e.message = fixPaths(e.message, paths);
  12996. return e;
  12997. }
  12998. __name(fixError, "fixError");
  12999. function mountObject(mounts2) {
  13000. if ("/" in mounts2) {
  13001. umount("/");
  13002. }
  13003. for (const [point, fs] of Object.entries(mounts2)) {
  13004. mount(point, fs);
  13005. }
  13006. }
  13007. __name(mountObject, "mountObject");
  13008. // src/emulation/sync.ts
  13009. function wrap(...[name, resolveSymlinks, path, ...args]) {
  13010. path = normalizePath(path);
  13011. const { fs, path: resolvedPath } = resolveMount(resolveSymlinks && existsSync(path) ? realpathSync(path) : path);
  13012. try {
  13013. return fs[name](resolvedPath, ...args);
  13014. } catch (e) {
  13015. throw fixError(e, { [resolvedPath]: path });
  13016. }
  13017. }
  13018. __name(wrap, "wrap");
  13019. function renameSync(oldPath, newPath) {
  13020. oldPath = normalizePath(oldPath);
  13021. newPath = normalizePath(newPath);
  13022. const _old = resolveMount(oldPath);
  13023. const _new = resolveMount(newPath);
  13024. const paths = { [_old.path]: oldPath, [_new.path]: newPath };
  13025. try {
  13026. if (_old === _new) {
  13027. return _old.fs.renameSync(_old.path, _new.path, cred);
  13028. }
  13029. writeFileSync(newPath, readFileSync(oldPath));
  13030. unlinkSync(oldPath);
  13031. } catch (e) {
  13032. throw fixError(e, paths);
  13033. }
  13034. }
  13035. __name(renameSync, "renameSync");
  13036. function existsSync(path) {
  13037. path = normalizePath(path);
  13038. try {
  13039. const { fs, path: resolvedPath } = resolveMount(realpathSync(path));
  13040. return fs.existsSync(resolvedPath, cred);
  13041. } catch (e) {
  13042. if (e.errno == 2 /* ENOENT */) {
  13043. return false;
  13044. }
  13045. throw e;
  13046. }
  13047. }
  13048. __name(existsSync, "existsSync");
  13049. function statSync(path, options) {
  13050. const stats = wrap("statSync", true, path.toString(), cred);
  13051. return options?.bigint ? new BigIntStats(stats) : stats;
  13052. }
  13053. __name(statSync, "statSync");
  13054. function lstatSync(path, options) {
  13055. const stats = wrap("statSync", false, path.toString(), cred);
  13056. return options?.bigint ? new BigIntStats(stats) : stats;
  13057. }
  13058. __name(lstatSync, "lstatSync");
  13059. function truncateSync(path, len = 0) {
  13060. const fd = openSync(path, "r+");
  13061. try {
  13062. ftruncateSync(fd, len);
  13063. } finally {
  13064. closeSync(fd);
  13065. }
  13066. }
  13067. __name(truncateSync, "truncateSync");
  13068. function unlinkSync(path) {
  13069. return wrap("unlinkSync", false, path.toString(), cred);
  13070. }
  13071. __name(unlinkSync, "unlinkSync");
  13072. function _openSync(_path, _flag, _mode, resolveSymlinks = true) {
  13073. const path = normalizePath(_path), mode = normalizeMode(_mode, 420), flag = parseFlag(_flag);
  13074. let stats;
  13075. try {
  13076. stats = wrap("statSync", resolveSymlinks, path, cred);
  13077. } catch (e) {
  13078. switch (pathNotExistsAction(flag)) {
  13079. case 3 /* CREATE */:
  13080. const parentStats = wrap("statSync", resolveSymlinks, dirname(path), cred);
  13081. if (!parentStats.isDirectory()) {
  13082. throw ErrnoError.With("ENOTDIR", dirname(path), "_open");
  13083. }
  13084. return wrap("createFileSync", resolveSymlinks, path, flag, mode, cred);
  13085. case 1 /* THROW */:
  13086. throw ErrnoError.With("ENOENT", path, "_open");
  13087. default:
  13088. throw new ErrnoError(22 /* EINVAL */, "Invalid FileFlag object.");
  13089. }
  13090. }
  13091. if (!stats.hasAccess(mode, cred)) {
  13092. throw ErrnoError.With("EACCES", path, "_open");
  13093. }
  13094. switch (pathExistsAction(flag)) {
  13095. case 1 /* THROW */:
  13096. throw ErrnoError.With("EEXIST", path, "_open");
  13097. case 2 /* TRUNCATE */:
  13098. wrap("unlinkSync", resolveSymlinks, path, cred);
  13099. return wrap("createFileSync", resolveSymlinks, path, flag, stats.mode, cred);
  13100. case 0 /* NOP */:
  13101. return wrap("openFileSync", resolveSymlinks, path, flag, cred);
  13102. default:
  13103. throw new ErrnoError(22 /* EINVAL */, "Invalid FileFlag object.");
  13104. }
  13105. }
  13106. __name(_openSync, "_openSync");
  13107. function openSync(path, flag, mode = F_OK) {
  13108. return file2fd(_openSync(path, flag, mode, true));
  13109. }
  13110. __name(openSync, "openSync");
  13111. function lopenSync(path, flag, mode) {
  13112. return file2fd(_openSync(path, flag, mode, false));
  13113. }
  13114. __name(lopenSync, "lopenSync");
  13115. function _readFileSync(fname, flag, resolveSymlinks) {
  13116. const file = _openSync(fname, flag, 420, resolveSymlinks);
  13117. try {
  13118. const stat3 = file.statSync();
  13119. const data = new Uint8Array(stat3.size);
  13120. file.readSync(data, 0, stat3.size, 0);
  13121. file.closeSync();
  13122. return data;
  13123. } finally {
  13124. file.closeSync();
  13125. }
  13126. }
  13127. __name(_readFileSync, "_readFileSync");
  13128. function readFileSync(path, _options = {}) {
  13129. const options = normalizeOptions(_options, null, "r", 420);
  13130. const flag = parseFlag(options.flag);
  13131. if (!isReadable(flag)) {
  13132. throw new ErrnoError(22 /* EINVAL */, "Flag passed to readFile must allow for reading.");
  13133. }
  13134. const data = import_buffer.Buffer.from(_readFileSync(typeof path == "number" ? fd2file(path).path : path.toString(), options.flag, true));
  13135. return options.encoding ? data.toString(options.encoding) : data;
  13136. }
  13137. __name(readFileSync, "readFileSync");
  13138. function writeFileSync(path, data, _options = {}) {
  13139. const options = normalizeOptions(_options, "utf8", "w+", 420);
  13140. const flag = parseFlag(options.flag);
  13141. if (!isWriteable(flag)) {
  13142. throw new ErrnoError(22 /* EINVAL */, "Flag passed to writeFile must allow for writing.");
  13143. }
  13144. if (typeof data != "string" && !options.encoding) {
  13145. throw new ErrnoError(22 /* EINVAL */, "Encoding not specified");
  13146. }
  13147. const encodedData = typeof data == "string" ? import_buffer.Buffer.from(data, options.encoding) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  13148. if (!encodedData) {
  13149. throw new ErrnoError(22 /* EINVAL */, "Data not specified");
  13150. }
  13151. const file = _openSync(typeof path == "number" ? fd2file(path).path : path.toString(), flag, options.mode, true);
  13152. try {
  13153. file.writeSync(encodedData, 0, encodedData.byteLength, 0);
  13154. } finally {
  13155. file.closeSync();
  13156. }
  13157. }
  13158. __name(writeFileSync, "writeFileSync");
  13159. function appendFileSync(filename, data, _options = {}) {
  13160. const options = normalizeOptions(_options, "utf8", "a", 420);
  13161. const flag = parseFlag(options.flag);
  13162. if (!isAppendable(flag)) {
  13163. throw new ErrnoError(22 /* EINVAL */, "Flag passed to appendFile must allow for appending.");
  13164. }
  13165. if (typeof data != "string" && !options.encoding) {
  13166. throw new ErrnoError(22 /* EINVAL */, "Encoding not specified");
  13167. }
  13168. const encodedData = typeof data == "string" ? import_buffer.Buffer.from(data, options.encoding) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  13169. const file = _openSync(typeof filename == "number" ? fd2file(filename).path : filename.toString(), flag, options.mode, true);
  13170. try {
  13171. file.writeSync(encodedData, 0, encodedData.byteLength, null);
  13172. } finally {
  13173. file.closeSync();
  13174. }
  13175. }
  13176. __name(appendFileSync, "appendFileSync");
  13177. function fstatSync(fd, options) {
  13178. const stats = fd2file(fd).statSync();
  13179. return options?.bigint ? new BigIntStats(stats) : stats;
  13180. }
  13181. __name(fstatSync, "fstatSync");
  13182. function closeSync(fd) {
  13183. fd2file(fd).closeSync();
  13184. fdMap.delete(fd);
  13185. }
  13186. __name(closeSync, "closeSync");
  13187. function ftruncateSync(fd, len = 0) {
  13188. len ||= 0;
  13189. if (len < 0) {
  13190. throw new ErrnoError(22 /* EINVAL */);
  13191. }
  13192. fd2file(fd).truncateSync(len);
  13193. }
  13194. __name(ftruncateSync, "ftruncateSync");
  13195. function fsyncSync(fd) {
  13196. fd2file(fd).syncSync();
  13197. }
  13198. __name(fsyncSync, "fsyncSync");
  13199. function fdatasyncSync(fd) {
  13200. fd2file(fd).datasyncSync();
  13201. }
  13202. __name(fdatasyncSync, "fdatasyncSync");
  13203. function writeSync(fd, data, posOrOff, lenOrEnc, pos) {
  13204. let buffer, offset, length, position;
  13205. if (typeof data === "string") {
  13206. position = typeof posOrOff === "number" ? posOrOff : null;
  13207. const encoding = typeof lenOrEnc === "string" ? lenOrEnc : "utf8";
  13208. offset = 0;
  13209. buffer = import_buffer.Buffer.from(data, encoding);
  13210. length = buffer.byteLength;
  13211. } else {
  13212. buffer = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  13213. offset = posOrOff;
  13214. length = lenOrEnc;
  13215. position = typeof pos === "number" ? pos : null;
  13216. }
  13217. const file = fd2file(fd);
  13218. position ??= file.position;
  13219. return file.writeSync(buffer, offset, length, position);
  13220. }
  13221. __name(writeSync, "writeSync");
  13222. function readSync(fd, buffer, opts, length, position) {
  13223. const file = fd2file(fd);
  13224. const offset = typeof opts == "object" ? opts.offset : opts;
  13225. if (typeof opts == "object") {
  13226. length = opts.length;
  13227. position = opts.position;
  13228. }
  13229. position = Number(position);
  13230. if (isNaN(position)) {
  13231. position = file.position;
  13232. }
  13233. return file.readSync(buffer, offset, length, position);
  13234. }
  13235. __name(readSync, "readSync");
  13236. function fchownSync(fd, uid, gid) {
  13237. fd2file(fd).chownSync(uid, gid);
  13238. }
  13239. __name(fchownSync, "fchownSync");
  13240. function fchmodSync(fd, mode) {
  13241. const numMode = normalizeMode(mode, -1);
  13242. if (numMode < 0) {
  13243. throw new ErrnoError(22 /* EINVAL */, `Invalid mode.`);
  13244. }
  13245. fd2file(fd).chmodSync(numMode);
  13246. }
  13247. __name(fchmodSync, "fchmodSync");
  13248. function futimesSync(fd, atime, mtime) {
  13249. fd2file(fd).utimesSync(normalizeTime(atime), normalizeTime(mtime));
  13250. }
  13251. __name(futimesSync, "futimesSync");
  13252. function rmdirSync(path) {
  13253. return wrap("rmdirSync", true, path.toString(), cred);
  13254. }
  13255. __name(rmdirSync, "rmdirSync");
  13256. function mkdirSync(path, options) {
  13257. const mode = typeof options == "number" || typeof options == "string" ? options : options?.mode;
  13258. const recursive = typeof options == "object" && options?.recursive;
  13259. wrap("mkdirSync", true, path.toString(), normalizeMode(mode, 511), cred);
  13260. }
  13261. __name(mkdirSync, "mkdirSync");
  13262. function readdirSync(path, options) {
  13263. path = normalizePath(path);
  13264. const entries = wrap("readdirSync", true, path, cred);
  13265. for (const mount2 of mounts.keys()) {
  13266. if (!mount2.startsWith(path)) {
  13267. continue;
  13268. }
  13269. const entry = mount2.slice(path.length);
  13270. if (entry.includes("/") || entry.length == 0) {
  13271. continue;
  13272. }
  13273. entries.push(entry);
  13274. }
  13275. return entries.map((entry) => {
  13276. if (typeof options == "object" && options?.withFileTypes) {
  13277. return new Dirent(entry, statSync(join(path.toString(), entry)));
  13278. }
  13279. if (options == "buffer" || typeof options == "object" && options?.encoding == "buffer") {
  13280. return import_buffer.Buffer.from(entry);
  13281. }
  13282. return entry;
  13283. });
  13284. }
  13285. __name(readdirSync, "readdirSync");
  13286. function linkSync(existing, newpath) {
  13287. newpath = normalizePath(newpath);
  13288. return wrap("linkSync", false, existing.toString(), newpath.toString(), cred);
  13289. }
  13290. __name(linkSync, "linkSync");
  13291. function symlinkSync(target, path, type = "file") {
  13292. if (!["file", "dir", "junction"].includes(type)) {
  13293. throw new ErrnoError(22 /* EINVAL */, "Invalid type: " + type);
  13294. }
  13295. if (existsSync(path)) {
  13296. throw ErrnoError.With("EEXIST", path.toString(), "symlink");
  13297. }
  13298. writeFileSync(path, target.toString());
  13299. const file = _openSync(path, "r+", 420, false);
  13300. file._setTypeSync(FileType.SYMLINK);
  13301. }
  13302. __name(symlinkSync, "symlinkSync");
  13303. function readlinkSync(path, options) {
  13304. const value = import_buffer.Buffer.from(_readFileSync(path.toString(), "r", false));
  13305. const encoding = typeof options == "object" ? options?.encoding : options;
  13306. if (encoding == "buffer") {
  13307. return value;
  13308. }
  13309. return value.toString(encoding);
  13310. }
  13311. __name(readlinkSync, "readlinkSync");
  13312. function chownSync(path, uid, gid) {
  13313. const fd = openSync(path, "r+");
  13314. fchownSync(fd, uid, gid);
  13315. closeSync(fd);
  13316. }
  13317. __name(chownSync, "chownSync");
  13318. function lchownSync(path, uid, gid) {
  13319. const fd = lopenSync(path, "r+");
  13320. fchownSync(fd, uid, gid);
  13321. closeSync(fd);
  13322. }
  13323. __name(lchownSync, "lchownSync");
  13324. function chmodSync(path, mode) {
  13325. const fd = openSync(path, "r+");
  13326. fchmodSync(fd, mode);
  13327. closeSync(fd);
  13328. }
  13329. __name(chmodSync, "chmodSync");
  13330. function lchmodSync(path, mode) {
  13331. const fd = lopenSync(path, "r+");
  13332. fchmodSync(fd, mode);
  13333. closeSync(fd);
  13334. }
  13335. __name(lchmodSync, "lchmodSync");
  13336. function utimesSync(path, atime, mtime) {
  13337. const fd = openSync(path, "r+");
  13338. futimesSync(fd, atime, mtime);
  13339. closeSync(fd);
  13340. }
  13341. __name(utimesSync, "utimesSync");
  13342. function lutimesSync(path, atime, mtime) {
  13343. const fd = lopenSync(path, "r+");
  13344. futimesSync(fd, atime, mtime);
  13345. closeSync(fd);
  13346. }
  13347. __name(lutimesSync, "lutimesSync");
  13348. function realpathSync(path, options) {
  13349. path = normalizePath(path);
  13350. const { base, dir } = parse(path);
  13351. const lpath = join(dir == "/" ? "/" : realpathSync(dir), base);
  13352. const { fs, path: resolvedPath, mountPoint } = resolveMount(lpath);
  13353. try {
  13354. const stats = fs.statSync(resolvedPath, cred);
  13355. if (!stats.isSymbolicLink()) {
  13356. return lpath;
  13357. }
  13358. return realpathSync(mountPoint + readlinkSync(lpath));
  13359. } catch (e) {
  13360. throw fixError(e, { [resolvedPath]: lpath });
  13361. }
  13362. }
  13363. __name(realpathSync, "realpathSync");
  13364. function accessSync(path, mode = 384) {
  13365. const stats = statSync(path);
  13366. if (!stats.hasAccess(mode, cred)) {
  13367. throw new ErrnoError(13 /* EACCES */);
  13368. }
  13369. }
  13370. __name(accessSync, "accessSync");
  13371. function rmSync(path, options) {
  13372. path = normalizePath(path);
  13373. const stats = statSync(path);
  13374. switch (stats.mode & S_IFMT) {
  13375. case S_IFDIR:
  13376. if (options?.recursive) {
  13377. for (const entry of readdirSync(path)) {
  13378. rmSync(join(path, entry));
  13379. }
  13380. }
  13381. rmdirSync(path);
  13382. return;
  13383. case S_IFREG:
  13384. case S_IFLNK:
  13385. unlinkSync(path);
  13386. return;
  13387. case S_IFBLK:
  13388. case S_IFCHR:
  13389. case S_IFIFO:
  13390. case S_IFSOCK:
  13391. default:
  13392. throw new ErrnoError(1 /* EPERM */, "File type not supported", path, "rm");
  13393. }
  13394. }
  13395. __name(rmSync, "rmSync");
  13396. function mkdtempSync(prefix, options) {
  13397. const encoding = typeof options === "object" ? options?.encoding : options || "utf8";
  13398. const fsName = `${prefix}${Date.now()}-${Math.random().toString(36).slice(2)}`;
  13399. const resolvedPath = "/tmp/" + fsName;
  13400. mkdirSync(resolvedPath);
  13401. return encoding == "buffer" ? import_buffer.Buffer.from(resolvedPath) : resolvedPath;
  13402. }
  13403. __name(mkdtempSync, "mkdtempSync");
  13404. function copyFileSync(src, dest, flags) {
  13405. src = normalizePath(src);
  13406. dest = normalizePath(dest);
  13407. if (flags && flags & COPYFILE_EXCL && existsSync(dest)) {
  13408. throw new ErrnoError(17 /* EEXIST */, "Destination file already exists.", dest, "copyFile");
  13409. }
  13410. writeFileSync(dest, readFileSync(src));
  13411. }
  13412. __name(copyFileSync, "copyFileSync");
  13413. function readvSync(fd, buffers, position) {
  13414. const file = fd2file(fd);
  13415. let bytesRead = 0;
  13416. for (const buffer of buffers) {
  13417. bytesRead += file.readSync(buffer, 0, buffer.byteLength, position + bytesRead);
  13418. }
  13419. return bytesRead;
  13420. }
  13421. __name(readvSync, "readvSync");
  13422. function writevSync(fd, buffers, position) {
  13423. const file = fd2file(fd);
  13424. let bytesWritten = 0;
  13425. for (const buffer of buffers) {
  13426. bytesWritten += file.writeSync(new Uint8Array(buffer.buffer), 0, buffer.byteLength, position + bytesWritten);
  13427. }
  13428. return bytesWritten;
  13429. }
  13430. __name(writevSync, "writevSync");
  13431. function opendirSync(path, options) {
  13432. path = normalizePath(path);
  13433. return new Dir(path);
  13434. }
  13435. __name(opendirSync, "opendirSync");
  13436. function cpSync(source, destination, opts) {
  13437. source = normalizePath(source);
  13438. destination = normalizePath(destination);
  13439. const srcStats = lstatSync(source);
  13440. if (opts?.errorOnExist && existsSync(destination)) {
  13441. throw new ErrnoError(17 /* EEXIST */, "Destination file or directory already exists.", destination, "cp");
  13442. }
  13443. switch (srcStats.mode & S_IFMT) {
  13444. case S_IFDIR:
  13445. if (!opts?.recursive) {
  13446. throw new ErrnoError(21 /* EISDIR */, source + " is a directory (not copied)", source, "cp");
  13447. }
  13448. mkdirSync(destination, { recursive: true });
  13449. for (const dirent of readdirSync(source, { withFileTypes: true })) {
  13450. if (opts.filter && !opts.filter(join(source, dirent.name), join(destination, dirent.name))) {
  13451. continue;
  13452. }
  13453. cpSync(join(source, dirent.name), join(destination, dirent.name), opts);
  13454. }
  13455. break;
  13456. case S_IFREG:
  13457. case S_IFLNK:
  13458. copyFileSync(source, destination);
  13459. break;
  13460. case S_IFBLK:
  13461. case S_IFCHR:
  13462. case S_IFIFO:
  13463. case S_IFSOCK:
  13464. default:
  13465. throw new ErrnoError(1 /* EPERM */, "File type not supported", source, "rm");
  13466. }
  13467. if (opts?.preserveTimestamps) {
  13468. utimesSync(destination, srcStats.atime, srcStats.mtime);
  13469. }
  13470. }
  13471. __name(cpSync, "cpSync");
  13472. function statfsSync(path, options) {
  13473. throw ErrnoError.With("ENOSYS", path.toString(), "statfs");
  13474. }
  13475. __name(statfsSync, "statfsSync");
  13476. // src/emulation/dir.ts
  13477. var Dirent = class {
  13478. constructor(path, stats) {
  13479. this.path = path;
  13480. this.stats = stats;
  13481. }
  13482. static {
  13483. __name(this, "Dirent");
  13484. }
  13485. get name() {
  13486. return basename(this.path);
  13487. }
  13488. isFile() {
  13489. return this.stats.isFile();
  13490. }
  13491. isDirectory() {
  13492. return this.stats.isDirectory();
  13493. }
  13494. isBlockDevice() {
  13495. return this.stats.isBlockDevice();
  13496. }
  13497. isCharacterDevice() {
  13498. return this.stats.isCharacterDevice();
  13499. }
  13500. isSymbolicLink() {
  13501. return this.stats.isSymbolicLink();
  13502. }
  13503. isFIFO() {
  13504. return this.stats.isFIFO();
  13505. }
  13506. isSocket() {
  13507. return this.stats.isSocket();
  13508. }
  13509. };
  13510. var Dir = class {
  13511. constructor(path) {
  13512. this.path = path;
  13513. this.closed = false;
  13514. this._entries = [];
  13515. }
  13516. static {
  13517. __name(this, "Dir");
  13518. }
  13519. checkClosed() {
  13520. if (this.closed) {
  13521. throw new ErrnoError(9 /* EBADF */, "Can not use closed Dir");
  13522. }
  13523. }
  13524. close(cb) {
  13525. this.closed = true;
  13526. if (!cb) {
  13527. return Promise.resolve();
  13528. }
  13529. cb();
  13530. }
  13531. /**
  13532. * Synchronously close the directory's underlying resource handle.
  13533. * Subsequent reads will result in errors.
  13534. */
  13535. closeSync() {
  13536. this.closed = true;
  13537. }
  13538. async _read() {
  13539. if (!this._entries) {
  13540. this._entries = await readdir(this.path, { withFileTypes: true });
  13541. }
  13542. if (!this._entries.length) {
  13543. return null;
  13544. }
  13545. return this._entries.shift() || null;
  13546. }
  13547. read(cb) {
  13548. if (!cb) {
  13549. return this._read();
  13550. }
  13551. this._read().then((value) => cb(void 0, value));
  13552. }
  13553. /**
  13554. * Synchronously read the next directory entry via `readdir(3)` as a `Dirent`.
  13555. * If there are no more directory entries to read, null will be returned.
  13556. * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms.
  13557. */
  13558. readSync() {
  13559. if (!this._entries) {
  13560. this._entries = readdirSync(this.path, { withFileTypes: true });
  13561. }
  13562. if (!this._entries.length) {
  13563. return null;
  13564. }
  13565. return this._entries.shift() || null;
  13566. }
  13567. /**
  13568. * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read.
  13569. */
  13570. [Symbol.asyncIterator]() {
  13571. const _this = this;
  13572. return {
  13573. [Symbol.asyncIterator]: this[Symbol.asyncIterator],
  13574. next: /* @__PURE__ */ __name(async function() {
  13575. const value = await _this._read();
  13576. if (value != null) {
  13577. return { done: false, value };
  13578. }
  13579. await _this.close();
  13580. return { done: true, value: void 0 };
  13581. }, "next")
  13582. };
  13583. }
  13584. };
  13585. // src/emulation/streams.ts
  13586. var import_readable_stream = __toESM(require_browser3(), 1);
  13587. var ReadStream = class extends import_readable_stream.Readable {
  13588. static {
  13589. __name(this, "ReadStream");
  13590. }
  13591. close(callback = () => null) {
  13592. try {
  13593. super.destroy();
  13594. super.emit("close");
  13595. callback();
  13596. } catch (err) {
  13597. callback(new ErrnoError(5 /* EIO */, err.toString()));
  13598. }
  13599. }
  13600. };
  13601. var WriteStream = class extends import_readable_stream.Writable {
  13602. static {
  13603. __name(this, "WriteStream");
  13604. }
  13605. close(callback = () => null) {
  13606. try {
  13607. super.destroy();
  13608. super.emit("close");
  13609. callback();
  13610. } catch (err) {
  13611. callback(new ErrnoError(5 /* EIO */, err.toString()));
  13612. }
  13613. }
  13614. };
  13615. // src/emulation/promises.ts
  13616. var FileHandle = class {
  13617. static {
  13618. __name(this, "FileHandle");
  13619. }
  13620. constructor(fdOrFile) {
  13621. const isFile = typeof fdOrFile != "number";
  13622. this.fd = isFile ? file2fd(fdOrFile) : fdOrFile;
  13623. this.file = isFile ? fdOrFile : fd2file(fdOrFile);
  13624. }
  13625. /**
  13626. * Asynchronous fchown(2) - Change ownership of a file.
  13627. */
  13628. chown(uid, gid) {
  13629. return this.file.chown(uid, gid);
  13630. }
  13631. /**
  13632. * Asynchronous fchmod(2) - Change permissions of a file.
  13633. * @param mode A file mode. If a string is passed, it is parsed as an octal integer.
  13634. */
  13635. chmod(mode) {
  13636. const numMode = normalizeMode(mode, -1);
  13637. if (numMode < 0) {
  13638. throw new ErrnoError(22 /* EINVAL */, "Invalid mode.");
  13639. }
  13640. return this.file.chmod(numMode);
  13641. }
  13642. /**
  13643. * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device.
  13644. */
  13645. datasync() {
  13646. return this.file.datasync();
  13647. }
  13648. /**
  13649. * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device.
  13650. */
  13651. sync() {
  13652. return this.file.sync();
  13653. }
  13654. /**
  13655. * Asynchronous ftruncate(2) - Truncate a file to a specified length.
  13656. * @param len If not specified, defaults to `0`.
  13657. */
  13658. truncate(len) {
  13659. len ||= 0;
  13660. if (len < 0) {
  13661. throw new ErrnoError(22 /* EINVAL */);
  13662. }
  13663. return this.file.truncate(len);
  13664. }
  13665. /**
  13666. * Asynchronously change file timestamps of the file.
  13667. * @param atime The last access time. If a string is provided, it will be coerced to number.
  13668. * @param mtime The last modified time. If a string is provided, it will be coerced to number.
  13669. */
  13670. utimes(atime, mtime) {
  13671. return this.file.utimes(normalizeTime(atime), normalizeTime(mtime));
  13672. }
  13673. /**
  13674. * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically.
  13675. * The `FileHandle` must have been opened for appending.
  13676. * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string.
  13677. * @param _options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
  13678. * If `encoding` is not supplied, the default of `'utf8'` is used.
  13679. * If `mode` is not supplied, the default of `0o666` is used.
  13680. * If `mode` is a string, it is parsed as an octal integer.
  13681. * If `flag` is not supplied, the default of `'a'` is used.
  13682. */
  13683. async appendFile(data, _options = {}) {
  13684. const options = normalizeOptions(_options, "utf8", "a", 420);
  13685. const flag = parseFlag(options.flag);
  13686. if (!isAppendable(flag)) {
  13687. throw new ErrnoError(22 /* EINVAL */, "Flag passed to appendFile must allow for appending.");
  13688. }
  13689. if (typeof data != "string" && !options.encoding) {
  13690. throw new ErrnoError(22 /* EINVAL */, "Encoding not specified");
  13691. }
  13692. const encodedData = typeof data == "string" ? import_buffer2.Buffer.from(data, options.encoding) : data;
  13693. await this.file.write(encodedData, 0, encodedData.length, null);
  13694. }
  13695. /**
  13696. * Asynchronously reads data from the file.
  13697. * The `FileHandle` must have been opened for reading.
  13698. * @param buffer The buffer that the data will be written to.
  13699. * @param offset The offset in the buffer at which to start writing.
  13700. * @param length The number of bytes to read.
  13701. * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position.
  13702. */
  13703. read(buffer, offset, length, position) {
  13704. if (isNaN(+position)) {
  13705. position = this.file.position;
  13706. }
  13707. return this.file.read(buffer, offset, length, position);
  13708. }
  13709. async readFile(_options) {
  13710. const options = normalizeOptions(_options, null, "r", 292);
  13711. const flag = parseFlag(options.flag);
  13712. if (!isReadable(flag)) {
  13713. throw new ErrnoError(22 /* EINVAL */, "Flag passed must allow for reading.");
  13714. }
  13715. const { size } = await this.stat();
  13716. const data = new Uint8Array(size);
  13717. await this.file.read(data, 0, size, 0);
  13718. const buffer = import_buffer2.Buffer.from(data);
  13719. return options.encoding ? buffer.toString(options.encoding) : buffer;
  13720. }
  13721. /**
  13722. * Returns a `ReadableStream` that may be used to read the files data.
  13723. *
  13724. * An error will be thrown if this method is called more than once or is called after the `FileHandle` is closed
  13725. * or closing.
  13726. *
  13727. * While the `ReadableStream` will read the file to completion, it will not close the `FileHandle` automatically. User code must still call the `fileHandle.close()` method.
  13728. *
  13729. * @since v17.0.0
  13730. * @experimental
  13731. */
  13732. readableWebStream(options = {}) {
  13733. const start = /* @__PURE__ */ __name(async ({ close: close2, enqueue, error }) => {
  13734. try {
  13735. const chunkSize = 64 * 1024, maxChunks = 1e7;
  13736. let i = 0, position = 0, bytesRead = NaN;
  13737. while (bytesRead > 0) {
  13738. const result = await this.read(new Uint8Array(chunkSize), 0, chunkSize, position);
  13739. if (!result.bytesRead) {
  13740. close2();
  13741. return;
  13742. }
  13743. enqueue(result.buffer.slice(0, result.bytesRead));
  13744. position += result.bytesRead;
  13745. if (++i >= maxChunks) {
  13746. throw new ErrnoError(27 /* EFBIG */, "Too many iterations on readable stream", this.file.path, "FileHandle.readableWebStream");
  13747. }
  13748. bytesRead = result.bytesRead;
  13749. }
  13750. } catch (e) {
  13751. error(e);
  13752. }
  13753. }, "start");
  13754. return new globalThis.ReadableStream({ start, type: options.type });
  13755. }
  13756. readLines(options) {
  13757. throw ErrnoError.With("ENOSYS", this.file.path, "FileHandle.readLines");
  13758. }
  13759. [Symbol.asyncDispose]() {
  13760. return this.close();
  13761. }
  13762. async stat(opts) {
  13763. const stats = await this.file.stat();
  13764. return opts?.bigint ? new BigIntStats(stats) : stats;
  13765. }
  13766. async write(data, posOrOff, lenOrEnc, position) {
  13767. let buffer, offset, length;
  13768. if (typeof data === "string") {
  13769. position = typeof posOrOff === "number" ? posOrOff : null;
  13770. const encoding = typeof lenOrEnc === "string" ? lenOrEnc : "utf8";
  13771. offset = 0;
  13772. buffer = import_buffer2.Buffer.from(data, encoding);
  13773. length = buffer.length;
  13774. } else {
  13775. buffer = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  13776. offset = posOrOff;
  13777. length = lenOrEnc;
  13778. position = typeof position === "number" ? position : null;
  13779. }
  13780. position ??= this.file.position;
  13781. const bytesWritten = await this.file.write(buffer, offset, length, position);
  13782. return { buffer, bytesWritten };
  13783. }
  13784. /**
  13785. * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically.
  13786. * The `FileHandle` must have been opened for writing.
  13787. * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected).
  13788. * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string.
  13789. * @param _options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
  13790. * If `encoding` is not supplied, the default of `'utf8'` is used.
  13791. * If `mode` is not supplied, the default of `0o666` is used.
  13792. * If `mode` is a string, it is parsed as an octal integer.
  13793. * If `flag` is not supplied, the default of `'w'` is used.
  13794. */
  13795. async writeFile(data, _options = {}) {
  13796. const options = normalizeOptions(_options, "utf8", "w", 420);
  13797. const flag = parseFlag(options.flag);
  13798. if (!isWriteable(flag)) {
  13799. throw new ErrnoError(22 /* EINVAL */, "Flag passed must allow for writing.");
  13800. }
  13801. if (typeof data != "string" && !options.encoding) {
  13802. throw new ErrnoError(22 /* EINVAL */, "Encoding not specified");
  13803. }
  13804. const encodedData = typeof data == "string" ? import_buffer2.Buffer.from(data, options.encoding) : data;
  13805. await this.file.write(encodedData, 0, encodedData.length, 0);
  13806. }
  13807. /**
  13808. * Asynchronous close(2) - close a `FileHandle`.
  13809. */
  13810. async close() {
  13811. await this.file.close();
  13812. fdMap.delete(this.fd);
  13813. }
  13814. /**
  13815. * Asynchronous `writev`. Writes from multiple buffers.
  13816. * @param buffers An array of Uint8Array buffers.
  13817. * @param position The position in the file where to begin writing.
  13818. * @returns The number of bytes written.
  13819. */
  13820. async writev(buffers, position) {
  13821. let bytesWritten = 0;
  13822. for (const buffer of buffers) {
  13823. bytesWritten += (await this.write(buffer, 0, buffer.length, position + bytesWritten)).bytesWritten;
  13824. }
  13825. return { bytesWritten, buffers };
  13826. }
  13827. /**
  13828. * Asynchronous `readv`. Reads into multiple buffers.
  13829. * @param buffers An array of Uint8Array buffers.
  13830. * @param position The position in the file where to begin reading.
  13831. * @returns The number of bytes read.
  13832. */
  13833. async readv(buffers, position) {
  13834. let bytesRead = 0;
  13835. for (const buffer of buffers) {
  13836. bytesRead += (await this.read(buffer, 0, buffer.byteLength, position + bytesRead)).bytesRead;
  13837. }
  13838. return { bytesRead, buffers };
  13839. }
  13840. /**
  13841. * Creates a `ReadStream` for reading from the file.
  13842. *
  13843. * @param options Options for the readable stream
  13844. * @returns A `ReadStream` object.
  13845. */
  13846. createReadStream(options) {
  13847. const stream = new ReadStream({
  13848. highWaterMark: options?.highWaterMark || 64 * 1024,
  13849. encoding: options.encoding,
  13850. read: /* @__PURE__ */ __name(async (size) => {
  13851. try {
  13852. const result = await this.read(new Uint8Array(size), 0, size, this.file.position);
  13853. stream.push(!result.bytesRead ? null : result.buffer.slice(0, result.bytesRead));
  13854. this.file.position += result.bytesRead;
  13855. } catch (error) {
  13856. stream.destroy(error);
  13857. }
  13858. }, "read")
  13859. });
  13860. stream.path = this.file.path;
  13861. return stream;
  13862. }
  13863. /**
  13864. * Creates a `WriteStream` for writing to the file.
  13865. *
  13866. * @param options Options for the writeable stream.
  13867. * @returns A `WriteStream` object
  13868. */
  13869. createWriteStream(options) {
  13870. const streamOptions = {
  13871. highWaterMark: options?.highWaterMark,
  13872. encoding: options?.encoding,
  13873. write: /* @__PURE__ */ __name(async (chunk, encoding, callback) => {
  13874. try {
  13875. const { bytesWritten } = await this.write(chunk, null, encoding);
  13876. callback(bytesWritten == chunk.length ? null : new Error("Failed to write full chunk"));
  13877. } catch (error) {
  13878. callback(error);
  13879. }
  13880. }, "write")
  13881. };
  13882. const stream = new WriteStream(streamOptions);
  13883. stream.path = this.file.path;
  13884. return stream;
  13885. }
  13886. };
  13887. async function rename(oldPath, newPath) {
  13888. oldPath = normalizePath(oldPath);
  13889. newPath = normalizePath(newPath);
  13890. const src = resolveMount(oldPath);
  13891. const dst = resolveMount(newPath);
  13892. try {
  13893. if (src.mountPoint == dst.mountPoint) {
  13894. await src.fs.rename(src.path, dst.path, cred);
  13895. return;
  13896. }
  13897. await writeFile(newPath, await readFile(oldPath));
  13898. await unlink(oldPath);
  13899. } catch (e) {
  13900. throw fixError(e, { [src.path]: oldPath, [dst.path]: newPath });
  13901. }
  13902. }
  13903. __name(rename, "rename");
  13904. async function exists(path) {
  13905. try {
  13906. const { fs, path: resolved } = resolveMount(await realpath(path));
  13907. return await fs.exists(resolved, cred);
  13908. } catch (e) {
  13909. if (e instanceof ErrnoError && e.code == "ENOENT") {
  13910. return false;
  13911. }
  13912. throw e;
  13913. }
  13914. }
  13915. __name(exists, "exists");
  13916. async function stat(path, options) {
  13917. path = normalizePath(path);
  13918. const { fs, path: resolved } = resolveMount(await exists(path) ? await realpath(path) : path);
  13919. try {
  13920. const stats = await fs.stat(resolved, cred);
  13921. return options?.bigint ? new BigIntStats(stats) : stats;
  13922. } catch (e) {
  13923. throw fixError(e, { [resolved]: path });
  13924. }
  13925. }
  13926. __name(stat, "stat");
  13927. async function lstat(path, options) {
  13928. path = normalizePath(path);
  13929. const { fs, path: resolved } = resolveMount(path);
  13930. try {
  13931. const stats = await fs.stat(resolved, cred);
  13932. return options?.bigint ? new BigIntStats(stats) : stats;
  13933. } catch (e) {
  13934. throw fixError(e, { [resolved]: path });
  13935. }
  13936. }
  13937. __name(lstat, "lstat");
  13938. async function truncate(path, len = 0) {
  13939. const handle = await open(path, "r+");
  13940. try {
  13941. await handle.truncate(len);
  13942. } finally {
  13943. await handle.close();
  13944. }
  13945. }
  13946. __name(truncate, "truncate");
  13947. async function unlink(path) {
  13948. path = normalizePath(path);
  13949. const { fs, path: resolved } = resolveMount(path);
  13950. try {
  13951. await fs.unlink(resolved, cred);
  13952. } catch (e) {
  13953. throw fixError(e, { [resolved]: path });
  13954. }
  13955. }
  13956. __name(unlink, "unlink");
  13957. async function _open(path, _flag, _mode = 420, resolveSymlinks) {
  13958. path = normalizePath(path);
  13959. const mode = normalizeMode(_mode, 420), flag = parseFlag(_flag);
  13960. path = resolveSymlinks && await exists(path) ? await realpath(path) : path;
  13961. const { fs, path: resolved } = resolveMount(path);
  13962. try {
  13963. switch (pathExistsAction(flag)) {
  13964. case 1 /* THROW */:
  13965. throw ErrnoError.With("EEXIST", path, "_open");
  13966. case 2 /* TRUNCATE */:
  13967. const file = await fs.openFile(resolved, flag, cred);
  13968. await file.truncate(0);
  13969. await file.sync();
  13970. return new FileHandle(file);
  13971. case 0 /* NOP */:
  13972. return new FileHandle(await fs.openFile(resolved, flag, cred));
  13973. default:
  13974. throw new ErrnoError(22 /* EINVAL */, "Invalid file flag");
  13975. }
  13976. } catch (e) {
  13977. switch (pathNotExistsAction(flag)) {
  13978. case 3 /* CREATE */:
  13979. const parentStats = await fs.stat(dirname(resolved), cred);
  13980. if (parentStats && !parentStats.isDirectory()) {
  13981. throw ErrnoError.With("ENOTDIR", dirname(path), "_open");
  13982. }
  13983. return new FileHandle(await fs.createFile(resolved, flag, mode, cred));
  13984. case 1 /* THROW */:
  13985. throw ErrnoError.With("ENOENT", path, "_open");
  13986. default:
  13987. throw new ErrnoError(22 /* EINVAL */, "Invalid file flag");
  13988. }
  13989. }
  13990. }
  13991. __name(_open, "_open");
  13992. async function open(path, flag = "r", mode = 420) {
  13993. return await _open(path, flag, mode, true);
  13994. }
  13995. __name(open, "open");
  13996. async function readFile(path, _options) {
  13997. const options = normalizeOptions(_options, null, "r", 420);
  13998. const handle = typeof path == "object" && "fd" in path ? path : await open(path, options.flag, options.mode);
  13999. try {
  14000. return await handle.readFile(options);
  14001. } finally {
  14002. await handle.close();
  14003. }
  14004. }
  14005. __name(readFile, "readFile");
  14006. async function writeFile(path, data, _options) {
  14007. const options = normalizeOptions(_options, "utf8", "w+", 420);
  14008. const handle = path instanceof FileHandle ? path : await open(path.toString(), options.flag, options.mode);
  14009. try {
  14010. const _data = typeof data == "string" ? data : data;
  14011. if (typeof _data != "string" && !(_data instanceof Uint8Array)) {
  14012. throw new ErrnoError(22 /* EINVAL */, "Iterables and streams not supported", handle.file.path, "writeFile");
  14013. }
  14014. await handle.writeFile(_data, options);
  14015. } finally {
  14016. await handle.close();
  14017. }
  14018. }
  14019. __name(writeFile, "writeFile");
  14020. async function appendFile(path, data, _options) {
  14021. const options = normalizeOptions(_options, "utf8", "a", 420);
  14022. const flag = parseFlag(options.flag);
  14023. if (!isAppendable(flag)) {
  14024. throw new ErrnoError(22 /* EINVAL */, "Flag passed to appendFile must allow for appending.");
  14025. }
  14026. if (typeof data != "string" && !options.encoding) {
  14027. throw new ErrnoError(22 /* EINVAL */, "Encoding not specified");
  14028. }
  14029. const encodedData = typeof data == "string" ? import_buffer2.Buffer.from(data, options.encoding) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  14030. const handle = typeof path == "object" && "fd" in path ? path : await open(path, options.flag, options.mode);
  14031. try {
  14032. await handle.appendFile(encodedData, options);
  14033. } finally {
  14034. await handle.close();
  14035. }
  14036. }
  14037. __name(appendFile, "appendFile");
  14038. async function rmdir(path) {
  14039. path = normalizePath(path);
  14040. path = await exists(path) ? await realpath(path) : path;
  14041. const { fs, path: resolved } = resolveMount(path);
  14042. try {
  14043. await fs.rmdir(resolved, cred);
  14044. } catch (e) {
  14045. throw fixError(e, { [resolved]: path });
  14046. }
  14047. }
  14048. __name(rmdir, "rmdir");
  14049. async function mkdir(path, options) {
  14050. path = normalizePath(path);
  14051. path = await exists(path) ? await realpath(path) : path;
  14052. const { fs, path: resolved } = resolveMount(path);
  14053. try {
  14054. await fs.mkdir(resolved, normalizeMode(typeof options == "object" ? options?.mode : options, 511), cred);
  14055. } catch (e) {
  14056. throw fixError(e, { [resolved]: path });
  14057. }
  14058. }
  14059. __name(mkdir, "mkdir");
  14060. async function readdir(path, options) {
  14061. path = normalizePath(path);
  14062. path = await exists(path) ? await realpath(path) : path;
  14063. const { fs, path: resolved } = resolveMount(path);
  14064. let entries;
  14065. try {
  14066. entries = await fs.readdir(resolved, cred);
  14067. } catch (e) {
  14068. throw fixError(e, { [resolved]: path });
  14069. }
  14070. for (const point of mounts.keys()) {
  14071. if (point.startsWith(path)) {
  14072. const entry = point.slice(path.length);
  14073. if (entry.includes("/") || entry.length == 0) {
  14074. continue;
  14075. }
  14076. entries.push(entry);
  14077. }
  14078. }
  14079. const values = [];
  14080. for (const entry of entries) {
  14081. values.push(typeof options == "object" && options?.withFileTypes ? new Dirent(entry, await stat(join(path, entry))) : entry);
  14082. }
  14083. return values;
  14084. }
  14085. __name(readdir, "readdir");
  14086. async function link(existing, newpath) {
  14087. existing = normalizePath(existing);
  14088. newpath = normalizePath(newpath);
  14089. const { fs, path: resolved } = resolveMount(newpath);
  14090. try {
  14091. return await fs.link(existing, newpath, cred);
  14092. } catch (e) {
  14093. throw fixError(e, { [resolved]: newpath });
  14094. }
  14095. }
  14096. __name(link, "link");
  14097. async function symlink(target, path, type = "file") {
  14098. if (!["file", "dir", "junction"].includes(type)) {
  14099. throw new ErrnoError(22 /* EINVAL */, "Invalid symlink type: " + type);
  14100. }
  14101. if (await exists(path)) {
  14102. throw ErrnoError.With("EEXIST", path.toString(), "symlink");
  14103. }
  14104. await writeFile(path, target.toString());
  14105. const handle = await _open(path, "r+", 420, false);
  14106. await handle.file._setType(FileType.SYMLINK);
  14107. }
  14108. __name(symlink, "symlink");
  14109. async function readlink(path, options) {
  14110. const handle = await _open(normalizePath(path), "r", 420, false);
  14111. try {
  14112. const value = await handle.readFile();
  14113. const encoding = typeof options == "object" ? options?.encoding : options;
  14114. return encoding == "buffer" ? value : value.toString(encoding);
  14115. } finally {
  14116. await handle.close();
  14117. }
  14118. }
  14119. __name(readlink, "readlink");
  14120. async function chown(path, uid, gid) {
  14121. const handle = await open(path, "r+");
  14122. try {
  14123. await handle.chown(uid, gid);
  14124. } finally {
  14125. await handle.close();
  14126. }
  14127. }
  14128. __name(chown, "chown");
  14129. async function lchown(path, uid, gid) {
  14130. const handle = await _open(path, "r+", 420, false);
  14131. try {
  14132. await handle.chown(uid, gid);
  14133. } finally {
  14134. await handle.close();
  14135. }
  14136. }
  14137. __name(lchown, "lchown");
  14138. async function chmod(path, mode) {
  14139. const handle = await open(path, "r+");
  14140. try {
  14141. await handle.chmod(mode);
  14142. } finally {
  14143. await handle.close();
  14144. }
  14145. }
  14146. __name(chmod, "chmod");
  14147. async function lchmod(path, mode) {
  14148. const handle = await _open(path, "r+", 420, false);
  14149. try {
  14150. await handle.chmod(mode);
  14151. } finally {
  14152. await handle.close();
  14153. }
  14154. }
  14155. __name(lchmod, "lchmod");
  14156. async function utimes(path, atime, mtime) {
  14157. const handle = await open(path, "r+");
  14158. try {
  14159. await handle.utimes(atime, mtime);
  14160. } finally {
  14161. await handle.close();
  14162. }
  14163. }
  14164. __name(utimes, "utimes");
  14165. async function lutimes(path, atime, mtime) {
  14166. const handle = await _open(path, "r+", 420, false);
  14167. try {
  14168. await handle.utimes(new Date(atime), new Date(mtime));
  14169. } finally {
  14170. await handle.close();
  14171. }
  14172. }
  14173. __name(lutimes, "lutimes");
  14174. async function realpath(path, options) {
  14175. path = normalizePath(path);
  14176. const { base, dir } = parse(path);
  14177. const lpath = join(dir == "/" ? "/" : await realpath(dir), base);
  14178. const { fs, path: resolvedPath, mountPoint } = resolveMount(lpath);
  14179. try {
  14180. const stats = await fs.stat(resolvedPath, cred);
  14181. if (!stats.isSymbolicLink()) {
  14182. return lpath;
  14183. }
  14184. return realpath(mountPoint + await readlink(lpath));
  14185. } catch (e) {
  14186. throw fixError(e, { [resolvedPath]: lpath });
  14187. }
  14188. }
  14189. __name(realpath, "realpath");
  14190. function watch(filename, options = {}) {
  14191. throw ErrnoError.With("ENOSYS", filename.toString(), "watch");
  14192. }
  14193. __name(watch, "watch");
  14194. async function access(path, mode = F_OK) {
  14195. const stats = await stat(path);
  14196. if (!stats.hasAccess(mode, cred)) {
  14197. throw new ErrnoError(13 /* EACCES */);
  14198. }
  14199. }
  14200. __name(access, "access");
  14201. async function rm(path, options) {
  14202. path = normalizePath(path);
  14203. const stats = await stat(path);
  14204. switch (stats.mode & S_IFMT) {
  14205. case S_IFDIR:
  14206. if (options?.recursive) {
  14207. for (const entry of await readdir(path)) {
  14208. await rm(join(path, entry));
  14209. }
  14210. }
  14211. await rmdir(path);
  14212. return;
  14213. case S_IFREG:
  14214. case S_IFLNK:
  14215. await unlink(path);
  14216. return;
  14217. case S_IFBLK:
  14218. case S_IFCHR:
  14219. case S_IFIFO:
  14220. case S_IFSOCK:
  14221. default:
  14222. throw new ErrnoError(1 /* EPERM */, "File type not supported", path, "rm");
  14223. }
  14224. }
  14225. __name(rm, "rm");
  14226. async function mkdtemp(prefix, options) {
  14227. const encoding = typeof options === "object" ? options?.encoding : options || "utf8";
  14228. const fsName = `${prefix}${Date.now()}-${Math.random().toString(36).slice(2)}`;
  14229. const resolvedPath = "/tmp/" + fsName;
  14230. await mkdir(resolvedPath);
  14231. return encoding == "buffer" ? import_buffer2.Buffer.from(resolvedPath) : resolvedPath;
  14232. }
  14233. __name(mkdtemp, "mkdtemp");
  14234. async function copyFile(src, dest, mode) {
  14235. src = normalizePath(src);
  14236. dest = normalizePath(dest);
  14237. if (mode && mode & COPYFILE_EXCL && await exists(dest)) {
  14238. throw new ErrnoError(17 /* EEXIST */, "Destination file already exists.", dest, "copyFile");
  14239. }
  14240. await writeFile(dest, await readFile(src));
  14241. }
  14242. __name(copyFile, "copyFile");
  14243. async function opendir(path, options) {
  14244. path = normalizePath(path);
  14245. return new Dir(path);
  14246. }
  14247. __name(opendir, "opendir");
  14248. async function cp(source, destination, opts) {
  14249. source = normalizePath(source);
  14250. destination = normalizePath(destination);
  14251. const srcStats = await lstat(source);
  14252. if (opts?.errorOnExist && await exists(destination)) {
  14253. throw new ErrnoError(17 /* EEXIST */, "Destination file or directory already exists.", destination, "cp");
  14254. }
  14255. switch (srcStats.mode & S_IFMT) {
  14256. case S_IFDIR:
  14257. if (!opts?.recursive) {
  14258. throw new ErrnoError(21 /* EISDIR */, source + " is a directory (not copied)", source, "cp");
  14259. }
  14260. await mkdir(destination, { recursive: true });
  14261. for (const dirent of await readdir(source, { withFileTypes: true })) {
  14262. if (opts.filter && !opts.filter(join(source, dirent.name), join(destination, dirent.name))) {
  14263. continue;
  14264. }
  14265. await cp(join(source, dirent.name), join(destination, dirent.name), opts);
  14266. }
  14267. break;
  14268. case S_IFREG:
  14269. case S_IFLNK:
  14270. await copyFile(source, destination);
  14271. break;
  14272. case S_IFBLK:
  14273. case S_IFCHR:
  14274. case S_IFIFO:
  14275. case S_IFSOCK:
  14276. default:
  14277. throw new ErrnoError(1 /* EPERM */, "File type not supported", source, "rm");
  14278. }
  14279. if (opts?.preserveTimestamps) {
  14280. await utimes(destination, srcStats.atime, srcStats.mtime);
  14281. }
  14282. }
  14283. __name(cp, "cp");
  14284. async function statfs(path, opts) {
  14285. throw ErrnoError.With("ENOSYS", path.toString(), "statfs");
  14286. }
  14287. __name(statfs, "statfs");
  14288. // src/emulation/async.ts
  14289. function rename2(oldPath, newPath, cb = nop) {
  14290. rename(oldPath, newPath).then(() => cb()).catch(cb);
  14291. }
  14292. __name(rename2, "rename");
  14293. function exists2(path, cb = nop) {
  14294. exists(path).then(cb).catch(() => cb(false));
  14295. }
  14296. __name(exists2, "exists");
  14297. function stat2(path, options, callback = nop) {
  14298. callback = typeof options == "function" ? options : callback;
  14299. stat(path, typeof options != "function" ? options : {}).then((stats) => callback(void 0, stats)).catch(callback);
  14300. }
  14301. __name(stat2, "stat");
  14302. function lstat2(path, options, callback = nop) {
  14303. callback = typeof options == "function" ? options : callback;
  14304. lstat(path, typeof options != "function" ? options : {}).then((stats) => callback(void 0, stats)).catch(callback);
  14305. }
  14306. __name(lstat2, "lstat");
  14307. function truncate2(path, cbLen = 0, cb = nop) {
  14308. cb = typeof cbLen === "function" ? cbLen : cb;
  14309. const len = typeof cbLen === "number" ? cbLen : 0;
  14310. truncate(path, len).then(() => cb()).catch(cb);
  14311. }
  14312. __name(truncate2, "truncate");
  14313. function unlink2(path, cb = nop) {
  14314. unlink(path).then(() => cb()).catch(cb);
  14315. }
  14316. __name(unlink2, "unlink");
  14317. function open2(path, flag, cbMode, cb = nop) {
  14318. const mode = normalizeMode(cbMode, 420);
  14319. cb = typeof cbMode === "function" ? cbMode : cb;
  14320. open(path, flag, mode).then((handle) => cb(void 0, handle.fd)).catch(cb);
  14321. }
  14322. __name(open2, "open");
  14323. function readFile2(filename, options, cb = nop) {
  14324. cb = typeof options === "function" ? options : cb;
  14325. readFile(filename, typeof options === "function" ? null : options).then((data) => cb(void 0, data)).catch(cb);
  14326. }
  14327. __name(readFile2, "readFile");
  14328. function writeFile2(filename, data, cbEncOpts, cb = nop) {
  14329. cb = typeof cbEncOpts === "function" ? cbEncOpts : cb;
  14330. writeFile(filename, data, typeof cbEncOpts != "function" ? cbEncOpts : null).then(() => cb(void 0)).catch(cb);
  14331. }
  14332. __name(writeFile2, "writeFile");
  14333. function appendFile2(filename, data, cbEncOpts, cb = nop) {
  14334. cb = typeof cbEncOpts === "function" ? cbEncOpts : cb;
  14335. appendFile(filename, data, typeof cbEncOpts === "function" ? null : cbEncOpts).then(() => cb()).catch(cb);
  14336. }
  14337. __name(appendFile2, "appendFile");
  14338. function fstat(fd, options, cb = nop) {
  14339. cb = typeof options == "function" ? options : cb;
  14340. fd2file(fd).stat().then((stats) => cb(void 0, typeof options == "object" && options?.bigint ? new BigIntStats(stats) : stats)).catch(cb);
  14341. }
  14342. __name(fstat, "fstat");
  14343. function close(fd, cb = nop) {
  14344. new FileHandle(fd).close().then(() => cb()).catch(cb);
  14345. }
  14346. __name(close, "close");
  14347. function ftruncate(fd, lenOrCB, cb = nop) {
  14348. const length = typeof lenOrCB === "number" ? lenOrCB : 0;
  14349. cb = typeof lenOrCB === "function" ? lenOrCB : cb;
  14350. const file = fd2file(fd);
  14351. if (length < 0) {
  14352. throw new ErrnoError(22 /* EINVAL */);
  14353. }
  14354. file.truncate(length).then(() => cb()).catch(cb);
  14355. }
  14356. __name(ftruncate, "ftruncate");
  14357. function fsync(fd, cb = nop) {
  14358. fd2file(fd).sync().then(() => cb()).catch(cb);
  14359. }
  14360. __name(fsync, "fsync");
  14361. function fdatasync(fd, cb = nop) {
  14362. fd2file(fd).datasync().then(() => cb()).catch(cb);
  14363. }
  14364. __name(fdatasync, "fdatasync");
  14365. function write(fd, data, cbPosOff, cbLenEnc, cbPos, cb = nop) {
  14366. let buffer, offset, length, position, encoding;
  14367. const handle = new FileHandle(fd);
  14368. if (typeof data === "string") {
  14369. encoding = "utf8";
  14370. switch (typeof cbPosOff) {
  14371. case "function":
  14372. cb = cbPosOff;
  14373. break;
  14374. case "number":
  14375. position = cbPosOff;
  14376. encoding = typeof cbLenEnc === "string" ? cbLenEnc : "utf8";
  14377. cb = typeof cbPos === "function" ? cbPos : cb;
  14378. break;
  14379. default:
  14380. cb = typeof cbLenEnc === "function" ? cbLenEnc : typeof cbPos === "function" ? cbPos : cb;
  14381. cb(new ErrnoError(22 /* EINVAL */, "Invalid arguments."));
  14382. return;
  14383. }
  14384. buffer = Buffer.from(data);
  14385. offset = 0;
  14386. length = buffer.length;
  14387. const _cb = cb;
  14388. handle.write(buffer, offset, length, position).then(({ bytesWritten }) => _cb(void 0, bytesWritten, buffer.toString(encoding))).catch(_cb);
  14389. } else {
  14390. buffer = Buffer.from(data.buffer);
  14391. offset = cbPosOff;
  14392. length = cbLenEnc;
  14393. position = typeof cbPos === "number" ? cbPos : null;
  14394. const _cb = typeof cbPos === "function" ? cbPos : cb;
  14395. handle.write(buffer, offset, length, position).then(({ bytesWritten }) => _cb(void 0, bytesWritten, buffer)).catch(_cb);
  14396. }
  14397. }
  14398. __name(write, "write");
  14399. function read(fd, buffer, offset, length, position, cb = nop) {
  14400. new FileHandle(fd).read(buffer, offset, length, position).then(({ bytesRead, buffer: buffer2 }) => cb(void 0, bytesRead, buffer2)).catch(cb);
  14401. }
  14402. __name(read, "read");
  14403. function fchown(fd, uid, gid, cb = nop) {
  14404. new FileHandle(fd).chown(uid, gid).then(() => cb()).catch(cb);
  14405. }
  14406. __name(fchown, "fchown");
  14407. function fchmod(fd, mode, cb) {
  14408. new FileHandle(fd).chmod(mode).then(() => cb()).catch(cb);
  14409. }
  14410. __name(fchmod, "fchmod");
  14411. function futimes(fd, atime, mtime, cb = nop) {
  14412. new FileHandle(fd).utimes(atime, mtime).then(() => cb()).catch(cb);
  14413. }
  14414. __name(futimes, "futimes");
  14415. function rmdir2(path, cb = nop) {
  14416. rmdir(path).then(() => cb()).catch(cb);
  14417. }
  14418. __name(rmdir2, "rmdir");
  14419. function mkdir2(path, mode, cb = nop) {
  14420. mkdir(path, mode).then(() => cb()).catch(cb);
  14421. }
  14422. __name(mkdir2, "mkdir");
  14423. function readdir2(path, _options, cb = nop) {
  14424. cb = typeof _options == "function" ? _options : cb;
  14425. const options = typeof _options != "function" ? _options : {};
  14426. readdir(path, options).then((entries) => cb(void 0, entries)).catch(cb);
  14427. }
  14428. __name(readdir2, "readdir");
  14429. function link2(existing, newpath, cb = nop) {
  14430. link(existing, newpath).then(() => cb()).catch(cb);
  14431. }
  14432. __name(link2, "link");
  14433. function symlink2(target, path, typeOrCB, cb = nop) {
  14434. const type = typeof typeOrCB === "string" ? typeOrCB : "file";
  14435. cb = typeof typeOrCB === "function" ? typeOrCB : cb;
  14436. symlink(target, path, type).then(() => cb()).catch(cb);
  14437. }
  14438. __name(symlink2, "symlink");
  14439. function readlink2(path, options, callback = nop) {
  14440. callback = typeof options == "function" ? options : callback;
  14441. readlink(path).then((result) => callback(void 0, result)).catch(callback);
  14442. }
  14443. __name(readlink2, "readlink");
  14444. function chown2(path, uid, gid, cb = nop) {
  14445. chown(path, uid, gid).then(() => cb()).catch(cb);
  14446. }
  14447. __name(chown2, "chown");
  14448. function lchown2(path, uid, gid, cb = nop) {
  14449. lchown(path, uid, gid).then(() => cb()).catch(cb);
  14450. }
  14451. __name(lchown2, "lchown");
  14452. function chmod2(path, mode, cb = nop) {
  14453. chmod(path, mode).then(() => cb()).catch(cb);
  14454. }
  14455. __name(chmod2, "chmod");
  14456. function lchmod2(path, mode, cb = nop) {
  14457. lchmod(path, mode).then(() => cb()).catch(cb);
  14458. }
  14459. __name(lchmod2, "lchmod");
  14460. function utimes2(path, atime, mtime, cb = nop) {
  14461. utimes(path, atime, mtime).then(() => cb()).catch(cb);
  14462. }
  14463. __name(utimes2, "utimes");
  14464. function lutimes2(path, atime, mtime, cb = nop) {
  14465. lutimes(path, atime, mtime).then(() => cb()).catch(cb);
  14466. }
  14467. __name(lutimes2, "lutimes");
  14468. function realpath2(path, arg2, cb = nop) {
  14469. cb = typeof arg2 === "function" ? arg2 : cb;
  14470. realpath(path, typeof arg2 === "function" ? null : arg2).then((result) => cb(void 0, result)).catch(cb);
  14471. }
  14472. __name(realpath2, "realpath");
  14473. function access2(path, cbMode, cb = nop) {
  14474. const mode = typeof cbMode === "number" ? cbMode : R_OK;
  14475. cb = typeof cbMode === "function" ? cbMode : cb;
  14476. access(path, typeof cbMode === "function" ? null : cbMode).then(() => cb()).catch(cb);
  14477. }
  14478. __name(access2, "access");
  14479. function watchFile(path, optsListener, listener = nop) {
  14480. throw ErrnoError.With("ENOSYS", path.toString(), "watchFile");
  14481. }
  14482. __name(watchFile, "watchFile");
  14483. function unwatchFile(path, listener = nop) {
  14484. throw ErrnoError.With("ENOSYS", path.toString(), "unwatchFile");
  14485. }
  14486. __name(unwatchFile, "unwatchFile");
  14487. function watch2(path, options, listener = nop) {
  14488. throw ErrnoError.With("ENOSYS", path.toString(), "watch");
  14489. }
  14490. __name(watch2, "watch");
  14491. function createReadStream(path, _options) {
  14492. const options = typeof _options == "object" ? _options : { encoding: _options };
  14493. let handle;
  14494. const stream = new ReadStream({
  14495. highWaterMark: options.highWaterMark || 64 * 1024,
  14496. encoding: options.encoding || "utf8",
  14497. read: /* @__PURE__ */ __name(async function(size) {
  14498. try {
  14499. handle ||= await open(path, "r", options?.mode);
  14500. const result = await handle.read(new Uint8Array(size), 0, size, handle.file.position);
  14501. stream.push(!result.bytesRead ? null : result.buffer.slice(0, result.bytesRead));
  14502. handle.file.position += result.bytesRead;
  14503. if (!result.bytesRead) {
  14504. await handle.close();
  14505. }
  14506. } catch (error) {
  14507. await handle?.close();
  14508. stream.destroy(error);
  14509. }
  14510. }, "read"),
  14511. destroy: /* @__PURE__ */ __name(function(error, callback) {
  14512. handle?.close().then(() => callback(error)).catch(callback);
  14513. }, "destroy")
  14514. });
  14515. stream.path = path.toString();
  14516. return stream;
  14517. }
  14518. __name(createReadStream, "createReadStream");
  14519. function createWriteStream(path, _options) {
  14520. const options = typeof _options == "object" ? _options : { encoding: _options };
  14521. let handle;
  14522. const stream = new WriteStream({
  14523. highWaterMark: options?.highWaterMark,
  14524. write: /* @__PURE__ */ __name(async function(chunk, encoding, callback) {
  14525. try {
  14526. handle ||= await open(path, "w", options?.mode || 438);
  14527. await handle.write(chunk, 0, encoding);
  14528. callback(void 0);
  14529. } catch (error) {
  14530. await handle?.close();
  14531. callback(error);
  14532. }
  14533. }, "write"),
  14534. destroy: /* @__PURE__ */ __name(function(error, callback) {
  14535. callback(error);
  14536. handle?.close().then(() => callback(error)).catch(callback);
  14537. }, "destroy"),
  14538. final: /* @__PURE__ */ __name(function(callback) {
  14539. handle?.close().then(() => callback()).catch(callback);
  14540. }, "final")
  14541. });
  14542. stream.path = path.toString();
  14543. return stream;
  14544. }
  14545. __name(createWriteStream, "createWriteStream");
  14546. function rm2(path, options, callback = nop) {
  14547. callback = typeof options === "function" ? options : callback;
  14548. rm(path, typeof options === "function" ? void 0 : options).then(() => callback(void 0)).catch(callback);
  14549. }
  14550. __name(rm2, "rm");
  14551. function mkdtemp2(prefix, options, callback = nop) {
  14552. callback = typeof options === "function" ? options : callback;
  14553. mkdtemp(prefix, typeof options != "function" ? options : null).then((result) => callback(void 0, result)).catch(callback);
  14554. }
  14555. __name(mkdtemp2, "mkdtemp");
  14556. function copyFile2(src, dest, flags, callback = nop) {
  14557. callback = typeof flags === "function" ? flags : callback;
  14558. copyFile(src, dest, typeof flags === "function" ? void 0 : flags).then(() => callback(void 0)).catch(callback);
  14559. }
  14560. __name(copyFile2, "copyFile");
  14561. function readv(fd, buffers, position, cb = nop) {
  14562. cb = typeof position === "function" ? position : cb;
  14563. new FileHandle(fd).readv(buffers, typeof position === "function" ? void 0 : position).then(({ buffers: buffers2, bytesRead }) => cb(void 0, bytesRead, buffers2)).catch(cb);
  14564. }
  14565. __name(readv, "readv");
  14566. function writev(fd, buffers, position, cb = nop) {
  14567. cb = typeof position === "function" ? position : cb;
  14568. new FileHandle(fd).writev(buffers, typeof position === "function" ? void 0 : position).then(({ buffers: buffers2, bytesWritten }) => cb(void 0, bytesWritten, buffers2)).catch(cb);
  14569. }
  14570. __name(writev, "writev");
  14571. function opendir2(path, options, cb = nop) {
  14572. cb = typeof options === "function" ? options : cb;
  14573. opendir(path, typeof options === "function" ? void 0 : options).then((result) => cb(void 0, result)).catch(cb);
  14574. }
  14575. __name(opendir2, "opendir");
  14576. function cp2(source, destination, opts, callback = nop) {
  14577. callback = typeof opts === "function" ? opts : callback;
  14578. cp(source, destination, typeof opts === "function" ? void 0 : opts).then(() => callback(void 0)).catch(callback);
  14579. }
  14580. __name(cp2, "cp");
  14581. function statfs2(path, options, callback = nop) {
  14582. callback = typeof options === "function" ? options : callback;
  14583. statfs(path, typeof options === "function" ? void 0 : options).then((result) => callback(void 0, result)).catch(callback);
  14584. }
  14585. __name(statfs2, "statfs");
  14586. async function openAsBlob(path, options) {
  14587. const handle = await open(path.toString(), "r");
  14588. const buffer = await handle.readFile();
  14589. await handle.close();
  14590. return new Blob([buffer], options);
  14591. }
  14592. __name(openAsBlob, "openAsBlob");
  14593. // src/config.ts
  14594. function isMountConfig(arg) {
  14595. return isBackendConfig(arg) || isBackend(arg) || arg instanceof FileSystem;
  14596. }
  14597. __name(isMountConfig, "isMountConfig");
  14598. async function resolveMountConfig(config, _depth = 0) {
  14599. if (typeof config !== "object" || config == null) {
  14600. throw new ErrnoError(22 /* EINVAL */, "Invalid options on mount configuration");
  14601. }
  14602. if (!isMountConfig(config)) {
  14603. throw new ErrnoError(22 /* EINVAL */, "Invalid mount configuration");
  14604. }
  14605. if (config instanceof FileSystem) {
  14606. return config;
  14607. }
  14608. if (isBackend(config)) {
  14609. config = { backend: config };
  14610. }
  14611. for (const [key, value] of Object.entries(config)) {
  14612. if (key == "backend") {
  14613. continue;
  14614. }
  14615. if (!isMountConfig(value)) {
  14616. continue;
  14617. }
  14618. if (_depth > 10) {
  14619. throw new ErrnoError(22 /* EINVAL */, "Invalid configuration, too deep and possibly infinite");
  14620. }
  14621. config[key] = await resolveMountConfig(value, ++_depth);
  14622. }
  14623. const { backend } = config;
  14624. if (!await backend.isAvailable()) {
  14625. throw new ErrnoError(1 /* EPERM */, "Backend not available: " + backend);
  14626. }
  14627. checkOptions(backend, config);
  14628. const mount2 = await backend.create(config);
  14629. await mount2.ready();
  14630. return mount2;
  14631. }
  14632. __name(resolveMountConfig, "resolveMountConfig");
  14633. async function configure(config) {
  14634. const uid = "uid" in config ? config.uid || 0 : 0;
  14635. const gid = "gid" in config ? config.gid || 0 : 0;
  14636. if (isMountConfig(config)) {
  14637. config = { mounts: { "/": config } };
  14638. }
  14639. for (const [point, value] of Object.entries(config.mounts)) {
  14640. if (!point.startsWith("/")) {
  14641. throw new ErrnoError(22 /* EINVAL */, "Mount points must have absolute paths");
  14642. }
  14643. config.mounts[point] = await resolveMountConfig(value);
  14644. }
  14645. mountObject(config.mounts);
  14646. setCred({ uid, gid, suid: uid, sgid: gid, euid: uid, egid: gid });
  14647. }
  14648. __name(configure, "configure");
  14649. // src/index.ts
  14650. var src_default = emulation_exports;
  14651. return __toCommonJS(src_exports);
  14652. })();
  14653. /*! Bundled license information:
  14654. ieee754/index.js:
  14655. (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
  14656. buffer/index.js:
  14657. (*!
  14658. * The buffer module from node.js, for the browser.
  14659. *
  14660. * @author Feross Aboukhadijeh <https://feross.org>
  14661. * @license MIT
  14662. *)
  14663. safe-buffer/index.js:
  14664. (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
  14665. */
  14666. //# sourceMappingURL=browser.min.js.map