index.mjs 278 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174
  1. var __create = Object.create;
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __getProtoOf = Object.getPrototypeOf;
  6. var __hasOwnProp = Object.prototype.hasOwnProperty;
  7. var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  8. get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
  9. }) : x)(function(x) {
  10. if (typeof require !== "undefined")
  11. return require.apply(this, arguments);
  12. throw new Error('Dynamic require of "' + x + '" is not supported');
  13. });
  14. var __commonJS = (cb, mod) => function __require2() {
  15. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  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. // node_modules/.pnpm/defer-to-connect@2.0.1/node_modules/defer-to-connect/dist/source/index.js
  34. var require_source = __commonJS({
  35. "node_modules/.pnpm/defer-to-connect@2.0.1/node_modules/defer-to-connect/dist/source/index.js"(exports, module) {
  36. "use strict";
  37. Object.defineProperty(exports, "__esModule", { value: true });
  38. function isTLSSocket(socket) {
  39. return socket.encrypted;
  40. }
  41. var deferToConnect2 = (socket, fn) => {
  42. let listeners;
  43. if (typeof fn === "function") {
  44. const connect = fn;
  45. listeners = { connect };
  46. } else {
  47. listeners = fn;
  48. }
  49. const hasConnectListener = typeof listeners.connect === "function";
  50. const hasSecureConnectListener = typeof listeners.secureConnect === "function";
  51. const hasCloseListener = typeof listeners.close === "function";
  52. const onConnect = () => {
  53. if (hasConnectListener) {
  54. listeners.connect();
  55. }
  56. if (isTLSSocket(socket) && hasSecureConnectListener) {
  57. if (socket.authorized) {
  58. listeners.secureConnect();
  59. } else if (!socket.authorizationError) {
  60. socket.once("secureConnect", listeners.secureConnect);
  61. }
  62. }
  63. if (hasCloseListener) {
  64. socket.once("close", listeners.close);
  65. }
  66. };
  67. if (socket.writable && !socket.connecting) {
  68. onConnect();
  69. } else if (socket.connecting) {
  70. socket.once("connect", onConnect);
  71. } else if (socket.destroyed && hasCloseListener) {
  72. listeners.close(socket._hadError);
  73. }
  74. };
  75. exports.default = deferToConnect2;
  76. module.exports = deferToConnect2;
  77. module.exports.default = deferToConnect2;
  78. }
  79. });
  80. // node_modules/.pnpm/get-stream@6.0.1/node_modules/get-stream/buffer-stream.js
  81. var require_buffer_stream = __commonJS({
  82. "node_modules/.pnpm/get-stream@6.0.1/node_modules/get-stream/buffer-stream.js"(exports, module) {
  83. "use strict";
  84. var { PassThrough: PassThroughStream2 } = __require("stream");
  85. module.exports = (options) => {
  86. options = { ...options };
  87. const { array } = options;
  88. let { encoding } = options;
  89. const isBuffer = encoding === "buffer";
  90. let objectMode = false;
  91. if (array) {
  92. objectMode = !(encoding || isBuffer);
  93. } else {
  94. encoding = encoding || "utf8";
  95. }
  96. if (isBuffer) {
  97. encoding = null;
  98. }
  99. const stream2 = new PassThroughStream2({ objectMode });
  100. if (encoding) {
  101. stream2.setEncoding(encoding);
  102. }
  103. let length = 0;
  104. const chunks = [];
  105. stream2.on("data", (chunk) => {
  106. chunks.push(chunk);
  107. if (objectMode) {
  108. length = chunks.length;
  109. } else {
  110. length += chunk.length;
  111. }
  112. });
  113. stream2.getBufferedValue = () => {
  114. if (array) {
  115. return chunks;
  116. }
  117. return isBuffer ? Buffer.concat(chunks, length) : chunks.join("");
  118. };
  119. stream2.getBufferedLength = () => length;
  120. return stream2;
  121. };
  122. }
  123. });
  124. // node_modules/.pnpm/get-stream@6.0.1/node_modules/get-stream/index.js
  125. var require_get_stream = __commonJS({
  126. "node_modules/.pnpm/get-stream@6.0.1/node_modules/get-stream/index.js"(exports, module) {
  127. "use strict";
  128. var { constants: BufferConstants } = __require("buffer");
  129. var stream2 = __require("stream");
  130. var { promisify: promisify4 } = __require("util");
  131. var bufferStream = require_buffer_stream();
  132. var streamPipelinePromisified = promisify4(stream2.pipeline);
  133. var MaxBufferError = class extends Error {
  134. constructor() {
  135. super("maxBuffer exceeded");
  136. this.name = "MaxBufferError";
  137. }
  138. };
  139. async function getStream2(inputStream, options) {
  140. if (!inputStream) {
  141. throw new Error("Expected a stream");
  142. }
  143. options = {
  144. maxBuffer: Infinity,
  145. ...options
  146. };
  147. const { maxBuffer } = options;
  148. const stream3 = bufferStream(options);
  149. await new Promise((resolve, reject) => {
  150. const rejectPromise = (error) => {
  151. if (error && stream3.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
  152. error.bufferedData = stream3.getBufferedValue();
  153. }
  154. reject(error);
  155. };
  156. (async () => {
  157. try {
  158. await streamPipelinePromisified(inputStream, stream3);
  159. resolve();
  160. } catch (error) {
  161. rejectPromise(error);
  162. }
  163. })();
  164. stream3.on("data", () => {
  165. if (stream3.getBufferedLength() > maxBuffer) {
  166. rejectPromise(new MaxBufferError());
  167. }
  168. });
  169. });
  170. return stream3.getBufferedValue();
  171. }
  172. module.exports = getStream2;
  173. module.exports.buffer = (stream3, options) => getStream2(stream3, { ...options, encoding: "buffer" });
  174. module.exports.array = (stream3, options) => getStream2(stream3, { ...options, array: true });
  175. module.exports.MaxBufferError = MaxBufferError;
  176. }
  177. });
  178. // node_modules/.pnpm/http-cache-semantics@4.1.1/node_modules/http-cache-semantics/index.js
  179. var require_http_cache_semantics = __commonJS({
  180. "node_modules/.pnpm/http-cache-semantics@4.1.1/node_modules/http-cache-semantics/index.js"(exports, module) {
  181. "use strict";
  182. var statusCodeCacheableByDefault = /* @__PURE__ */ new Set([
  183. 200,
  184. 203,
  185. 204,
  186. 206,
  187. 300,
  188. 301,
  189. 308,
  190. 404,
  191. 405,
  192. 410,
  193. 414,
  194. 501
  195. ]);
  196. var understoodStatuses = /* @__PURE__ */ new Set([
  197. 200,
  198. 203,
  199. 204,
  200. 300,
  201. 301,
  202. 302,
  203. 303,
  204. 307,
  205. 308,
  206. 404,
  207. 405,
  208. 410,
  209. 414,
  210. 501
  211. ]);
  212. var errorStatusCodes = /* @__PURE__ */ new Set([
  213. 500,
  214. 502,
  215. 503,
  216. 504
  217. ]);
  218. var hopByHopHeaders = {
  219. date: true,
  220. // included, because we add Age update Date
  221. connection: true,
  222. "keep-alive": true,
  223. "proxy-authenticate": true,
  224. "proxy-authorization": true,
  225. te: true,
  226. trailer: true,
  227. "transfer-encoding": true,
  228. upgrade: true
  229. };
  230. var excludedFromRevalidationUpdate = {
  231. // Since the old body is reused, it doesn't make sense to change properties of the body
  232. "content-length": true,
  233. "content-encoding": true,
  234. "transfer-encoding": true,
  235. "content-range": true
  236. };
  237. function toNumberOrZero(s) {
  238. const n = parseInt(s, 10);
  239. return isFinite(n) ? n : 0;
  240. }
  241. function isErrorResponse(response) {
  242. if (!response) {
  243. return true;
  244. }
  245. return errorStatusCodes.has(response.status);
  246. }
  247. function parseCacheControl(header) {
  248. const cc = {};
  249. if (!header)
  250. return cc;
  251. const parts = header.trim().split(/,/);
  252. for (const part of parts) {
  253. const [k, v] = part.split(/=/, 2);
  254. cc[k.trim()] = v === void 0 ? true : v.trim().replace(/^"|"$/g, "");
  255. }
  256. return cc;
  257. }
  258. function formatCacheControl(cc) {
  259. let parts = [];
  260. for (const k in cc) {
  261. const v = cc[k];
  262. parts.push(v === true ? k : k + "=" + v);
  263. }
  264. if (!parts.length) {
  265. return void 0;
  266. }
  267. return parts.join(", ");
  268. }
  269. module.exports = class CachePolicy {
  270. constructor(req, res, {
  271. shared,
  272. cacheHeuristic,
  273. immutableMinTimeToLive,
  274. ignoreCargoCult,
  275. _fromObject
  276. } = {}) {
  277. if (_fromObject) {
  278. this._fromObject(_fromObject);
  279. return;
  280. }
  281. if (!res || !res.headers) {
  282. throw Error("Response headers missing");
  283. }
  284. this._assertRequestHasHeaders(req);
  285. this._responseTime = this.now();
  286. this._isShared = shared !== false;
  287. this._cacheHeuristic = void 0 !== cacheHeuristic ? cacheHeuristic : 0.1;
  288. this._immutableMinTtl = void 0 !== immutableMinTimeToLive ? immutableMinTimeToLive : 24 * 3600 * 1e3;
  289. this._status = "status" in res ? res.status : 200;
  290. this._resHeaders = res.headers;
  291. this._rescc = parseCacheControl(res.headers["cache-control"]);
  292. this._method = "method" in req ? req.method : "GET";
  293. this._url = req.url;
  294. this._host = req.headers.host;
  295. this._noAuthorization = !req.headers.authorization;
  296. this._reqHeaders = res.headers.vary ? req.headers : null;
  297. this._reqcc = parseCacheControl(req.headers["cache-control"]);
  298. if (ignoreCargoCult && "pre-check" in this._rescc && "post-check" in this._rescc) {
  299. delete this._rescc["pre-check"];
  300. delete this._rescc["post-check"];
  301. delete this._rescc["no-cache"];
  302. delete this._rescc["no-store"];
  303. delete this._rescc["must-revalidate"];
  304. this._resHeaders = Object.assign({}, this._resHeaders, {
  305. "cache-control": formatCacheControl(this._rescc)
  306. });
  307. delete this._resHeaders.expires;
  308. delete this._resHeaders.pragma;
  309. }
  310. if (res.headers["cache-control"] == null && /no-cache/.test(res.headers.pragma)) {
  311. this._rescc["no-cache"] = true;
  312. }
  313. }
  314. now() {
  315. return Date.now();
  316. }
  317. storable() {
  318. return !!(!this._reqcc["no-store"] && // A cache MUST NOT store a response to any request, unless:
  319. // The request method is understood by the cache and defined as being cacheable, and
  320. ("GET" === this._method || "HEAD" === this._method || "POST" === this._method && this._hasExplicitExpiration()) && // the response status code is understood by the cache, and
  321. understoodStatuses.has(this._status) && // the "no-store" cache directive does not appear in request or response header fields, and
  322. !this._rescc["no-store"] && // the "private" response directive does not appear in the response, if the cache is shared, and
  323. (!this._isShared || !this._rescc.private) && // the Authorization header field does not appear in the request, if the cache is shared,
  324. (!this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) && // the response either:
  325. // contains an Expires header field, or
  326. (this._resHeaders.expires || // contains a max-age response directive, or
  327. // contains a s-maxage response directive and the cache is shared, or
  328. // contains a public response directive.
  329. this._rescc["max-age"] || this._isShared && this._rescc["s-maxage"] || this._rescc.public || // has a status code that is defined as cacheable by default
  330. statusCodeCacheableByDefault.has(this._status)));
  331. }
  332. _hasExplicitExpiration() {
  333. return this._isShared && this._rescc["s-maxage"] || this._rescc["max-age"] || this._resHeaders.expires;
  334. }
  335. _assertRequestHasHeaders(req) {
  336. if (!req || !req.headers) {
  337. throw Error("Request headers missing");
  338. }
  339. }
  340. satisfiesWithoutRevalidation(req) {
  341. this._assertRequestHasHeaders(req);
  342. const requestCC = parseCacheControl(req.headers["cache-control"]);
  343. if (requestCC["no-cache"] || /no-cache/.test(req.headers.pragma)) {
  344. return false;
  345. }
  346. if (requestCC["max-age"] && this.age() > requestCC["max-age"]) {
  347. return false;
  348. }
  349. if (requestCC["min-fresh"] && this.timeToLive() < 1e3 * requestCC["min-fresh"]) {
  350. return false;
  351. }
  352. if (this.stale()) {
  353. const allowsStale = requestCC["max-stale"] && !this._rescc["must-revalidate"] && (true === requestCC["max-stale"] || requestCC["max-stale"] > this.age() - this.maxAge());
  354. if (!allowsStale) {
  355. return false;
  356. }
  357. }
  358. return this._requestMatches(req, false);
  359. }
  360. _requestMatches(req, allowHeadMethod) {
  361. return (!this._url || this._url === req.url) && this._host === req.headers.host && // the request method associated with the stored response allows it to be used for the presented request, and
  362. (!req.method || this._method === req.method || allowHeadMethod && "HEAD" === req.method) && // selecting header fields nominated by the stored response (if any) match those presented, and
  363. this._varyMatches(req);
  364. }
  365. _allowsStoringAuthenticated() {
  366. return this._rescc["must-revalidate"] || this._rescc.public || this._rescc["s-maxage"];
  367. }
  368. _varyMatches(req) {
  369. if (!this._resHeaders.vary) {
  370. return true;
  371. }
  372. if (this._resHeaders.vary === "*") {
  373. return false;
  374. }
  375. const fields = this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);
  376. for (const name of fields) {
  377. if (req.headers[name] !== this._reqHeaders[name])
  378. return false;
  379. }
  380. return true;
  381. }
  382. _copyWithoutHopByHopHeaders(inHeaders) {
  383. const headers = {};
  384. for (const name in inHeaders) {
  385. if (hopByHopHeaders[name])
  386. continue;
  387. headers[name] = inHeaders[name];
  388. }
  389. if (inHeaders.connection) {
  390. const tokens = inHeaders.connection.trim().split(/\s*,\s*/);
  391. for (const name of tokens) {
  392. delete headers[name];
  393. }
  394. }
  395. if (headers.warning) {
  396. const warnings = headers.warning.split(/,/).filter((warning) => {
  397. return !/^\s*1[0-9][0-9]/.test(warning);
  398. });
  399. if (!warnings.length) {
  400. delete headers.warning;
  401. } else {
  402. headers.warning = warnings.join(",").trim();
  403. }
  404. }
  405. return headers;
  406. }
  407. responseHeaders() {
  408. const headers = this._copyWithoutHopByHopHeaders(this._resHeaders);
  409. const age = this.age();
  410. if (age > 3600 * 24 && !this._hasExplicitExpiration() && this.maxAge() > 3600 * 24) {
  411. headers.warning = (headers.warning ? `${headers.warning}, ` : "") + '113 - "rfc7234 5.5.4"';
  412. }
  413. headers.age = `${Math.round(age)}`;
  414. headers.date = new Date(this.now()).toUTCString();
  415. return headers;
  416. }
  417. /**
  418. * Value of the Date response header or current time if Date was invalid
  419. * @return timestamp
  420. */
  421. date() {
  422. const serverDate = Date.parse(this._resHeaders.date);
  423. if (isFinite(serverDate)) {
  424. return serverDate;
  425. }
  426. return this._responseTime;
  427. }
  428. /**
  429. * Value of the Age header, in seconds, updated for the current time.
  430. * May be fractional.
  431. *
  432. * @return Number
  433. */
  434. age() {
  435. let age = this._ageValue();
  436. const residentTime = (this.now() - this._responseTime) / 1e3;
  437. return age + residentTime;
  438. }
  439. _ageValue() {
  440. return toNumberOrZero(this._resHeaders.age);
  441. }
  442. /**
  443. * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.
  444. *
  445. * For an up-to-date value, see `timeToLive()`.
  446. *
  447. * @return Number
  448. */
  449. maxAge() {
  450. if (!this.storable() || this._rescc["no-cache"]) {
  451. return 0;
  452. }
  453. if (this._isShared && (this._resHeaders["set-cookie"] && !this._rescc.public && !this._rescc.immutable)) {
  454. return 0;
  455. }
  456. if (this._resHeaders.vary === "*") {
  457. return 0;
  458. }
  459. if (this._isShared) {
  460. if (this._rescc["proxy-revalidate"]) {
  461. return 0;
  462. }
  463. if (this._rescc["s-maxage"]) {
  464. return toNumberOrZero(this._rescc["s-maxage"]);
  465. }
  466. }
  467. if (this._rescc["max-age"]) {
  468. return toNumberOrZero(this._rescc["max-age"]);
  469. }
  470. const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;
  471. const serverDate = this.date();
  472. if (this._resHeaders.expires) {
  473. const expires = Date.parse(this._resHeaders.expires);
  474. if (Number.isNaN(expires) || expires < serverDate) {
  475. return 0;
  476. }
  477. return Math.max(defaultMinTtl, (expires - serverDate) / 1e3);
  478. }
  479. if (this._resHeaders["last-modified"]) {
  480. const lastModified = Date.parse(this._resHeaders["last-modified"]);
  481. if (isFinite(lastModified) && serverDate > lastModified) {
  482. return Math.max(
  483. defaultMinTtl,
  484. (serverDate - lastModified) / 1e3 * this._cacheHeuristic
  485. );
  486. }
  487. }
  488. return defaultMinTtl;
  489. }
  490. timeToLive() {
  491. const age = this.maxAge() - this.age();
  492. const staleIfErrorAge = age + toNumberOrZero(this._rescc["stale-if-error"]);
  493. const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc["stale-while-revalidate"]);
  494. return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1e3;
  495. }
  496. stale() {
  497. return this.maxAge() <= this.age();
  498. }
  499. _useStaleIfError() {
  500. return this.maxAge() + toNumberOrZero(this._rescc["stale-if-error"]) > this.age();
  501. }
  502. useStaleWhileRevalidate() {
  503. return this.maxAge() + toNumberOrZero(this._rescc["stale-while-revalidate"]) > this.age();
  504. }
  505. static fromObject(obj) {
  506. return new this(void 0, void 0, { _fromObject: obj });
  507. }
  508. _fromObject(obj) {
  509. if (this._responseTime)
  510. throw Error("Reinitialized");
  511. if (!obj || obj.v !== 1)
  512. throw Error("Invalid serialization");
  513. this._responseTime = obj.t;
  514. this._isShared = obj.sh;
  515. this._cacheHeuristic = obj.ch;
  516. this._immutableMinTtl = obj.imm !== void 0 ? obj.imm : 24 * 3600 * 1e3;
  517. this._status = obj.st;
  518. this._resHeaders = obj.resh;
  519. this._rescc = obj.rescc;
  520. this._method = obj.m;
  521. this._url = obj.u;
  522. this._host = obj.h;
  523. this._noAuthorization = obj.a;
  524. this._reqHeaders = obj.reqh;
  525. this._reqcc = obj.reqcc;
  526. }
  527. toObject() {
  528. return {
  529. v: 1,
  530. t: this._responseTime,
  531. sh: this._isShared,
  532. ch: this._cacheHeuristic,
  533. imm: this._immutableMinTtl,
  534. st: this._status,
  535. resh: this._resHeaders,
  536. rescc: this._rescc,
  537. m: this._method,
  538. u: this._url,
  539. h: this._host,
  540. a: this._noAuthorization,
  541. reqh: this._reqHeaders,
  542. reqcc: this._reqcc
  543. };
  544. }
  545. /**
  546. * Headers for sending to the origin server to revalidate stale response.
  547. * Allows server to return 304 to allow reuse of the previous response.
  548. *
  549. * Hop by hop headers are always stripped.
  550. * Revalidation headers may be added or removed, depending on request.
  551. */
  552. revalidationHeaders(incomingReq) {
  553. this._assertRequestHasHeaders(incomingReq);
  554. const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);
  555. delete headers["if-range"];
  556. if (!this._requestMatches(incomingReq, true) || !this.storable()) {
  557. delete headers["if-none-match"];
  558. delete headers["if-modified-since"];
  559. return headers;
  560. }
  561. if (this._resHeaders.etag) {
  562. headers["if-none-match"] = headers["if-none-match"] ? `${headers["if-none-match"]}, ${this._resHeaders.etag}` : this._resHeaders.etag;
  563. }
  564. const forbidsWeakValidators = headers["accept-ranges"] || headers["if-match"] || headers["if-unmodified-since"] || this._method && this._method != "GET";
  565. if (forbidsWeakValidators) {
  566. delete headers["if-modified-since"];
  567. if (headers["if-none-match"]) {
  568. const etags = headers["if-none-match"].split(/,/).filter((etag) => {
  569. return !/^\s*W\//.test(etag);
  570. });
  571. if (!etags.length) {
  572. delete headers["if-none-match"];
  573. } else {
  574. headers["if-none-match"] = etags.join(",").trim();
  575. }
  576. }
  577. } else if (this._resHeaders["last-modified"] && !headers["if-modified-since"]) {
  578. headers["if-modified-since"] = this._resHeaders["last-modified"];
  579. }
  580. return headers;
  581. }
  582. /**
  583. * Creates new CachePolicy with information combined from the previews response,
  584. * and the new revalidation response.
  585. *
  586. * Returns {policy, modified} where modified is a boolean indicating
  587. * whether the response body has been modified, and old cached body can't be used.
  588. *
  589. * @return {Object} {policy: CachePolicy, modified: Boolean}
  590. */
  591. revalidatedPolicy(request, response) {
  592. this._assertRequestHasHeaders(request);
  593. if (this._useStaleIfError() && isErrorResponse(response)) {
  594. return {
  595. modified: false,
  596. matches: false,
  597. policy: this
  598. };
  599. }
  600. if (!response || !response.headers) {
  601. throw Error("Response headers missing");
  602. }
  603. let matches = false;
  604. if (response.status !== void 0 && response.status != 304) {
  605. matches = false;
  606. } else if (response.headers.etag && !/^\s*W\//.test(response.headers.etag)) {
  607. matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//, "") === response.headers.etag;
  608. } else if (this._resHeaders.etag && response.headers.etag) {
  609. matches = this._resHeaders.etag.replace(/^\s*W\//, "") === response.headers.etag.replace(/^\s*W\//, "");
  610. } else if (this._resHeaders["last-modified"]) {
  611. matches = this._resHeaders["last-modified"] === response.headers["last-modified"];
  612. } else {
  613. if (!this._resHeaders.etag && !this._resHeaders["last-modified"] && !response.headers.etag && !response.headers["last-modified"]) {
  614. matches = true;
  615. }
  616. }
  617. if (!matches) {
  618. return {
  619. policy: new this.constructor(request, response),
  620. // Client receiving 304 without body, even if it's invalid/mismatched has no option
  621. // but to reuse a cached body. We don't have a good way to tell clients to do
  622. // error recovery in such case.
  623. modified: response.status != 304,
  624. matches: false
  625. };
  626. }
  627. const headers = {};
  628. for (const k in this._resHeaders) {
  629. headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k];
  630. }
  631. const newResponse = Object.assign({}, response, {
  632. status: this._status,
  633. method: this._method,
  634. headers
  635. });
  636. return {
  637. policy: new this.constructor(request, newResponse, {
  638. shared: this._isShared,
  639. cacheHeuristic: this._cacheHeuristic,
  640. immutableMinTimeToLive: this._immutableMinTtl
  641. }),
  642. modified: false,
  643. matches: true
  644. };
  645. }
  646. };
  647. }
  648. });
  649. // node_modules/.pnpm/json-buffer@3.0.1/node_modules/json-buffer/index.js
  650. var require_json_buffer = __commonJS({
  651. "node_modules/.pnpm/json-buffer@3.0.1/node_modules/json-buffer/index.js"(exports) {
  652. exports.stringify = function stringify(o) {
  653. if ("undefined" == typeof o)
  654. return o;
  655. if (o && Buffer.isBuffer(o))
  656. return JSON.stringify(":base64:" + o.toString("base64"));
  657. if (o && o.toJSON)
  658. o = o.toJSON();
  659. if (o && "object" === typeof o) {
  660. var s = "";
  661. var array = Array.isArray(o);
  662. s = array ? "[" : "{";
  663. var first = true;
  664. for (var k in o) {
  665. var ignore = "function" == typeof o[k] || !array && "undefined" === typeof o[k];
  666. if (Object.hasOwnProperty.call(o, k) && !ignore) {
  667. if (!first)
  668. s += ",";
  669. first = false;
  670. if (array) {
  671. if (o[k] == void 0)
  672. s += "null";
  673. else
  674. s += stringify(o[k]);
  675. } else if (o[k] !== void 0) {
  676. s += stringify(k) + ":" + stringify(o[k]);
  677. }
  678. }
  679. }
  680. s += array ? "]" : "}";
  681. return s;
  682. } else if ("string" === typeof o) {
  683. return JSON.stringify(/^:/.test(o) ? ":" + o : o);
  684. } else if ("undefined" === typeof o) {
  685. return "null";
  686. } else
  687. return JSON.stringify(o);
  688. };
  689. exports.parse = function(s) {
  690. return JSON.parse(s, function(key, value) {
  691. if ("string" === typeof value) {
  692. if (/^:base64:/.test(value))
  693. return Buffer.from(value.substring(8), "base64");
  694. else
  695. return /^:/.test(value) ? value.substring(1) : value;
  696. }
  697. return value;
  698. });
  699. };
  700. }
  701. });
  702. // node_modules/.pnpm/keyv@4.5.2/node_modules/keyv/src/index.js
  703. var require_src = __commonJS({
  704. "node_modules/.pnpm/keyv@4.5.2/node_modules/keyv/src/index.js"(exports, module) {
  705. "use strict";
  706. var EventEmitter3 = __require("events");
  707. var JSONB = require_json_buffer();
  708. var loadStore = (options) => {
  709. const adapters = {
  710. redis: "@keyv/redis",
  711. rediss: "@keyv/redis",
  712. mongodb: "@keyv/mongo",
  713. mongo: "@keyv/mongo",
  714. sqlite: "@keyv/sqlite",
  715. postgresql: "@keyv/postgres",
  716. postgres: "@keyv/postgres",
  717. mysql: "@keyv/mysql",
  718. etcd: "@keyv/etcd",
  719. offline: "@keyv/offline",
  720. tiered: "@keyv/tiered"
  721. };
  722. if (options.adapter || options.uri) {
  723. const adapter = options.adapter || /^[^:+]*/.exec(options.uri)[0];
  724. return new (__require(adapters[adapter]))(options);
  725. }
  726. return /* @__PURE__ */ new Map();
  727. };
  728. var iterableAdapters = [
  729. "sqlite",
  730. "postgres",
  731. "mysql",
  732. "mongo",
  733. "redis",
  734. "tiered"
  735. ];
  736. var Keyv2 = class extends EventEmitter3 {
  737. constructor(uri, { emitErrors = true, ...options } = {}) {
  738. super();
  739. this.opts = {
  740. namespace: "keyv",
  741. serialize: JSONB.stringify,
  742. deserialize: JSONB.parse,
  743. ...typeof uri === "string" ? { uri } : uri,
  744. ...options
  745. };
  746. if (!this.opts.store) {
  747. const adapterOptions = { ...this.opts };
  748. this.opts.store = loadStore(adapterOptions);
  749. }
  750. if (this.opts.compression) {
  751. const compression = this.opts.compression;
  752. this.opts.serialize = compression.serialize.bind(compression);
  753. this.opts.deserialize = compression.deserialize.bind(compression);
  754. }
  755. if (typeof this.opts.store.on === "function" && emitErrors) {
  756. this.opts.store.on("error", (error) => this.emit("error", error));
  757. }
  758. this.opts.store.namespace = this.opts.namespace;
  759. const generateIterator = (iterator) => async function* () {
  760. for await (const [key, raw] of typeof iterator === "function" ? iterator(this.opts.store.namespace) : iterator) {
  761. const data = this.opts.deserialize(raw);
  762. if (this.opts.store.namespace && !key.includes(this.opts.store.namespace)) {
  763. continue;
  764. }
  765. if (typeof data.expires === "number" && Date.now() > data.expires) {
  766. this.delete(key);
  767. continue;
  768. }
  769. yield [this._getKeyUnprefix(key), data.value];
  770. }
  771. };
  772. if (typeof this.opts.store[Symbol.iterator] === "function" && this.opts.store instanceof Map) {
  773. this.iterator = generateIterator(this.opts.store);
  774. } else if (typeof this.opts.store.iterator === "function" && this.opts.store.opts && this._checkIterableAdaptar()) {
  775. this.iterator = generateIterator(this.opts.store.iterator.bind(this.opts.store));
  776. }
  777. }
  778. _checkIterableAdaptar() {
  779. return iterableAdapters.includes(this.opts.store.opts.dialect) || iterableAdapters.findIndex((element) => this.opts.store.opts.url.includes(element)) >= 0;
  780. }
  781. _getKeyPrefix(key) {
  782. return `${this.opts.namespace}:${key}`;
  783. }
  784. _getKeyPrefixArray(keys) {
  785. return keys.map((key) => `${this.opts.namespace}:${key}`);
  786. }
  787. _getKeyUnprefix(key) {
  788. return key.split(":").splice(1).join(":");
  789. }
  790. get(key, options) {
  791. const { store } = this.opts;
  792. const isArray = Array.isArray(key);
  793. const keyPrefixed = isArray ? this._getKeyPrefixArray(key) : this._getKeyPrefix(key);
  794. if (isArray && store.getMany === void 0) {
  795. const promises = [];
  796. for (const key2 of keyPrefixed) {
  797. promises.push(
  798. Promise.resolve().then(() => store.get(key2)).then((data) => typeof data === "string" ? this.opts.deserialize(data) : this.opts.compression ? this.opts.deserialize(data) : data).then((data) => {
  799. if (data === void 0 || data === null) {
  800. return void 0;
  801. }
  802. if (typeof data.expires === "number" && Date.now() > data.expires) {
  803. return this.delete(key2).then(() => void 0);
  804. }
  805. return options && options.raw ? data : data.value;
  806. })
  807. );
  808. }
  809. return Promise.allSettled(promises).then((values) => {
  810. const data = [];
  811. for (const value of values) {
  812. data.push(value.value);
  813. }
  814. return data;
  815. });
  816. }
  817. return Promise.resolve().then(() => isArray ? store.getMany(keyPrefixed) : store.get(keyPrefixed)).then((data) => typeof data === "string" ? this.opts.deserialize(data) : this.opts.compression ? this.opts.deserialize(data) : data).then((data) => {
  818. if (data === void 0 || data === null) {
  819. return void 0;
  820. }
  821. if (isArray) {
  822. const result = [];
  823. for (let row of data) {
  824. if (typeof row === "string") {
  825. row = this.opts.deserialize(row);
  826. }
  827. if (row === void 0 || row === null) {
  828. result.push(void 0);
  829. continue;
  830. }
  831. if (typeof row.expires === "number" && Date.now() > row.expires) {
  832. this.delete(key).then(() => void 0);
  833. result.push(void 0);
  834. } else {
  835. result.push(options && options.raw ? row : row.value);
  836. }
  837. }
  838. return result;
  839. }
  840. if (typeof data.expires === "number" && Date.now() > data.expires) {
  841. return this.delete(key).then(() => void 0);
  842. }
  843. return options && options.raw ? data : data.value;
  844. });
  845. }
  846. set(key, value, ttl2) {
  847. const keyPrefixed = this._getKeyPrefix(key);
  848. if (typeof ttl2 === "undefined") {
  849. ttl2 = this.opts.ttl;
  850. }
  851. if (ttl2 === 0) {
  852. ttl2 = void 0;
  853. }
  854. const { store } = this.opts;
  855. return Promise.resolve().then(() => {
  856. const expires = typeof ttl2 === "number" ? Date.now() + ttl2 : null;
  857. if (typeof value === "symbol") {
  858. this.emit("error", "symbol cannot be serialized");
  859. }
  860. value = { value, expires };
  861. return this.opts.serialize(value);
  862. }).then((value2) => store.set(keyPrefixed, value2, ttl2)).then(() => true);
  863. }
  864. delete(key) {
  865. const { store } = this.opts;
  866. if (Array.isArray(key)) {
  867. const keyPrefixed2 = this._getKeyPrefixArray(key);
  868. if (store.deleteMany === void 0) {
  869. const promises = [];
  870. for (const key2 of keyPrefixed2) {
  871. promises.push(store.delete(key2));
  872. }
  873. return Promise.allSettled(promises).then((values) => values.every((x) => x.value === true));
  874. }
  875. return Promise.resolve().then(() => store.deleteMany(keyPrefixed2));
  876. }
  877. const keyPrefixed = this._getKeyPrefix(key);
  878. return Promise.resolve().then(() => store.delete(keyPrefixed));
  879. }
  880. clear() {
  881. const { store } = this.opts;
  882. return Promise.resolve().then(() => store.clear());
  883. }
  884. has(key) {
  885. const keyPrefixed = this._getKeyPrefix(key);
  886. const { store } = this.opts;
  887. return Promise.resolve().then(async () => {
  888. if (typeof store.has === "function") {
  889. return store.has(keyPrefixed);
  890. }
  891. const value = await store.get(keyPrefixed);
  892. return value !== void 0;
  893. });
  894. }
  895. disconnect() {
  896. const { store } = this.opts;
  897. if (typeof store.disconnect === "function") {
  898. return store.disconnect();
  899. }
  900. }
  901. };
  902. module.exports = Keyv2;
  903. }
  904. });
  905. // node_modules/.pnpm/mimic-response@3.1.0/node_modules/mimic-response/index.js
  906. var require_mimic_response = __commonJS({
  907. "node_modules/.pnpm/mimic-response@3.1.0/node_modules/mimic-response/index.js"(exports, module) {
  908. "use strict";
  909. var knownProperties2 = [
  910. "aborted",
  911. "complete",
  912. "headers",
  913. "httpVersion",
  914. "httpVersionMinor",
  915. "httpVersionMajor",
  916. "method",
  917. "rawHeaders",
  918. "rawTrailers",
  919. "setTimeout",
  920. "socket",
  921. "statusCode",
  922. "statusMessage",
  923. "trailers",
  924. "url"
  925. ];
  926. module.exports = (fromStream, toStream) => {
  927. if (toStream._readableState.autoDestroy) {
  928. throw new Error("The second stream must have the `autoDestroy` option set to `false`");
  929. }
  930. const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties2));
  931. const properties = {};
  932. for (const property of fromProperties) {
  933. if (property in toStream) {
  934. continue;
  935. }
  936. properties[property] = {
  937. get() {
  938. const value = fromStream[property];
  939. const isFunction2 = typeof value === "function";
  940. return isFunction2 ? value.bind(fromStream) : value;
  941. },
  942. set(value) {
  943. fromStream[property] = value;
  944. },
  945. enumerable: true,
  946. configurable: false
  947. };
  948. }
  949. Object.defineProperties(toStream, properties);
  950. fromStream.once("aborted", () => {
  951. toStream.destroy();
  952. toStream.emit("aborted");
  953. });
  954. fromStream.once("close", () => {
  955. if (fromStream.complete) {
  956. if (toStream.readable) {
  957. toStream.once("end", () => {
  958. toStream.emit("close");
  959. });
  960. } else {
  961. toStream.emit("close");
  962. }
  963. } else {
  964. toStream.emit("close");
  965. }
  966. });
  967. return toStream;
  968. };
  969. }
  970. });
  971. // node_modules/.pnpm/decompress-response@6.0.0/node_modules/decompress-response/index.js
  972. var require_decompress_response = __commonJS({
  973. "node_modules/.pnpm/decompress-response@6.0.0/node_modules/decompress-response/index.js"(exports, module) {
  974. "use strict";
  975. var { Transform, PassThrough } = __require("stream");
  976. var zlib = __require("zlib");
  977. var mimicResponse2 = require_mimic_response();
  978. module.exports = (response) => {
  979. const contentEncoding = (response.headers["content-encoding"] || "").toLowerCase();
  980. if (!["gzip", "deflate", "br"].includes(contentEncoding)) {
  981. return response;
  982. }
  983. const isBrotli = contentEncoding === "br";
  984. if (isBrotli && typeof zlib.createBrotliDecompress !== "function") {
  985. response.destroy(new Error("Brotli is not supported on Node.js < 12"));
  986. return response;
  987. }
  988. let isEmpty = true;
  989. const checker = new Transform({
  990. transform(data, _encoding, callback) {
  991. isEmpty = false;
  992. callback(null, data);
  993. },
  994. flush(callback) {
  995. callback();
  996. }
  997. });
  998. const finalStream = new PassThrough({
  999. autoDestroy: false,
  1000. destroy(error, callback) {
  1001. response.destroy();
  1002. callback(error);
  1003. }
  1004. });
  1005. const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();
  1006. decompressStream.once("error", (error) => {
  1007. if (isEmpty && !response.readable) {
  1008. finalStream.end();
  1009. return;
  1010. }
  1011. finalStream.destroy(error);
  1012. });
  1013. mimicResponse2(response, finalStream);
  1014. response.pipe(checker).pipe(decompressStream).pipe(finalStream);
  1015. return finalStream;
  1016. };
  1017. }
  1018. });
  1019. // node_modules/.pnpm/quick-lru@5.1.1/node_modules/quick-lru/index.js
  1020. var require_quick_lru = __commonJS({
  1021. "node_modules/.pnpm/quick-lru@5.1.1/node_modules/quick-lru/index.js"(exports, module) {
  1022. "use strict";
  1023. var QuickLRU = class {
  1024. constructor(options = {}) {
  1025. if (!(options.maxSize && options.maxSize > 0)) {
  1026. throw new TypeError("`maxSize` must be a number greater than 0");
  1027. }
  1028. this.maxSize = options.maxSize;
  1029. this.onEviction = options.onEviction;
  1030. this.cache = /* @__PURE__ */ new Map();
  1031. this.oldCache = /* @__PURE__ */ new Map();
  1032. this._size = 0;
  1033. }
  1034. _set(key, value) {
  1035. this.cache.set(key, value);
  1036. this._size++;
  1037. if (this._size >= this.maxSize) {
  1038. this._size = 0;
  1039. if (typeof this.onEviction === "function") {
  1040. for (const [key2, value2] of this.oldCache.entries()) {
  1041. this.onEviction(key2, value2);
  1042. }
  1043. }
  1044. this.oldCache = this.cache;
  1045. this.cache = /* @__PURE__ */ new Map();
  1046. }
  1047. }
  1048. get(key) {
  1049. if (this.cache.has(key)) {
  1050. return this.cache.get(key);
  1051. }
  1052. if (this.oldCache.has(key)) {
  1053. const value = this.oldCache.get(key);
  1054. this.oldCache.delete(key);
  1055. this._set(key, value);
  1056. return value;
  1057. }
  1058. }
  1059. set(key, value) {
  1060. if (this.cache.has(key)) {
  1061. this.cache.set(key, value);
  1062. } else {
  1063. this._set(key, value);
  1064. }
  1065. return this;
  1066. }
  1067. has(key) {
  1068. return this.cache.has(key) || this.oldCache.has(key);
  1069. }
  1070. peek(key) {
  1071. if (this.cache.has(key)) {
  1072. return this.cache.get(key);
  1073. }
  1074. if (this.oldCache.has(key)) {
  1075. return this.oldCache.get(key);
  1076. }
  1077. }
  1078. delete(key) {
  1079. const deleted = this.cache.delete(key);
  1080. if (deleted) {
  1081. this._size--;
  1082. }
  1083. return this.oldCache.delete(key) || deleted;
  1084. }
  1085. clear() {
  1086. this.cache.clear();
  1087. this.oldCache.clear();
  1088. this._size = 0;
  1089. }
  1090. *keys() {
  1091. for (const [key] of this) {
  1092. yield key;
  1093. }
  1094. }
  1095. *values() {
  1096. for (const [, value] of this) {
  1097. yield value;
  1098. }
  1099. }
  1100. *[Symbol.iterator]() {
  1101. for (const item of this.cache) {
  1102. yield item;
  1103. }
  1104. for (const item of this.oldCache) {
  1105. const [key] = item;
  1106. if (!this.cache.has(key)) {
  1107. yield item;
  1108. }
  1109. }
  1110. }
  1111. get size() {
  1112. let oldCacheSize = 0;
  1113. for (const key of this.oldCache.keys()) {
  1114. if (!this.cache.has(key)) {
  1115. oldCacheSize++;
  1116. }
  1117. }
  1118. return Math.min(this._size + oldCacheSize, this.maxSize);
  1119. }
  1120. };
  1121. module.exports = QuickLRU;
  1122. }
  1123. });
  1124. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/delay-async-destroy.js
  1125. var require_delay_async_destroy = __commonJS({
  1126. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/delay-async-destroy.js"(exports, module) {
  1127. "use strict";
  1128. module.exports = (stream2) => {
  1129. if (stream2.listenerCount("error") !== 0) {
  1130. return stream2;
  1131. }
  1132. stream2.__destroy = stream2._destroy;
  1133. stream2._destroy = (...args) => {
  1134. const callback = args.pop();
  1135. stream2.__destroy(...args, async (error) => {
  1136. await Promise.resolve();
  1137. callback(error);
  1138. });
  1139. };
  1140. const onError = (error) => {
  1141. Promise.resolve().then(() => {
  1142. stream2.emit("error", error);
  1143. });
  1144. };
  1145. stream2.once("error", onError);
  1146. Promise.resolve().then(() => {
  1147. stream2.off("error", onError);
  1148. });
  1149. return stream2;
  1150. };
  1151. }
  1152. });
  1153. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/agent.js
  1154. var require_agent = __commonJS({
  1155. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/agent.js"(exports, module) {
  1156. "use strict";
  1157. var { URL: URL4 } = __require("url");
  1158. var EventEmitter3 = __require("events");
  1159. var tls = __require("tls");
  1160. var http22 = __require("http2");
  1161. var QuickLRU = require_quick_lru();
  1162. var delayAsyncDestroy = require_delay_async_destroy();
  1163. var kCurrentStreamCount = Symbol("currentStreamCount");
  1164. var kRequest = Symbol("request");
  1165. var kOriginSet = Symbol("cachedOriginSet");
  1166. var kGracefullyClosing = Symbol("gracefullyClosing");
  1167. var kLength = Symbol("length");
  1168. var nameKeys = [
  1169. // Not an Agent option actually
  1170. "createConnection",
  1171. // `http2.connect()` options
  1172. "maxDeflateDynamicTableSize",
  1173. "maxSettings",
  1174. "maxSessionMemory",
  1175. "maxHeaderListPairs",
  1176. "maxOutstandingPings",
  1177. "maxReservedRemoteStreams",
  1178. "maxSendHeaderBlockLength",
  1179. "paddingStrategy",
  1180. "peerMaxConcurrentStreams",
  1181. "settings",
  1182. // `tls.connect()` source options
  1183. "family",
  1184. "localAddress",
  1185. "rejectUnauthorized",
  1186. // `tls.connect()` secure context options
  1187. "pskCallback",
  1188. "minDHSize",
  1189. // `tls.connect()` destination options
  1190. // - `servername` is automatically validated, skip it
  1191. // - `host` and `port` just describe the destination server,
  1192. "path",
  1193. "socket",
  1194. // `tls.createSecureContext()` options
  1195. "ca",
  1196. "cert",
  1197. "sigalgs",
  1198. "ciphers",
  1199. "clientCertEngine",
  1200. "crl",
  1201. "dhparam",
  1202. "ecdhCurve",
  1203. "honorCipherOrder",
  1204. "key",
  1205. "privateKeyEngine",
  1206. "privateKeyIdentifier",
  1207. "maxVersion",
  1208. "minVersion",
  1209. "pfx",
  1210. "secureOptions",
  1211. "secureProtocol",
  1212. "sessionIdContext",
  1213. "ticketKeys"
  1214. ];
  1215. var getSortedIndex = (array, value, compare) => {
  1216. let low = 0;
  1217. let high = array.length;
  1218. while (low < high) {
  1219. const mid = low + high >>> 1;
  1220. if (compare(array[mid], value)) {
  1221. low = mid + 1;
  1222. } else {
  1223. high = mid;
  1224. }
  1225. }
  1226. return low;
  1227. };
  1228. var compareSessions = (a, b) => a.remoteSettings.maxConcurrentStreams > b.remoteSettings.maxConcurrentStreams;
  1229. var closeCoveredSessions = (where, session) => {
  1230. for (let index = 0; index < where.length; index++) {
  1231. const coveredSession = where[index];
  1232. if (
  1233. // Unfortunately `.every()` returns true for an empty array
  1234. coveredSession[kOriginSet].length > 0 && coveredSession[kOriginSet].length < session[kOriginSet].length && coveredSession[kOriginSet].every((origin) => session[kOriginSet].includes(origin)) && coveredSession[kCurrentStreamCount] + session[kCurrentStreamCount] <= session.remoteSettings.maxConcurrentStreams
  1235. ) {
  1236. gracefullyClose(coveredSession);
  1237. }
  1238. }
  1239. };
  1240. var closeSessionIfCovered = (where, coveredSession) => {
  1241. for (let index = 0; index < where.length; index++) {
  1242. const session = where[index];
  1243. if (coveredSession[kOriginSet].length > 0 && coveredSession[kOriginSet].length < session[kOriginSet].length && coveredSession[kOriginSet].every((origin) => session[kOriginSet].includes(origin)) && coveredSession[kCurrentStreamCount] + session[kCurrentStreamCount] <= session.remoteSettings.maxConcurrentStreams) {
  1244. gracefullyClose(coveredSession);
  1245. return true;
  1246. }
  1247. }
  1248. return false;
  1249. };
  1250. var gracefullyClose = (session) => {
  1251. session[kGracefullyClosing] = true;
  1252. if (session[kCurrentStreamCount] === 0) {
  1253. session.close();
  1254. }
  1255. };
  1256. var Agent = class extends EventEmitter3 {
  1257. constructor({ timeout = 0, maxSessions = Number.POSITIVE_INFINITY, maxEmptySessions = 10, maxCachedTlsSessions = 100 } = {}) {
  1258. super();
  1259. this.sessions = {};
  1260. this.queue = {};
  1261. this.timeout = timeout;
  1262. this.maxSessions = maxSessions;
  1263. this.maxEmptySessions = maxEmptySessions;
  1264. this._emptySessionCount = 0;
  1265. this._sessionCount = 0;
  1266. this.settings = {
  1267. enablePush: false,
  1268. initialWindowSize: 1024 * 1024 * 32
  1269. // 32MB, see https://github.com/nodejs/node/issues/38426
  1270. };
  1271. this.tlsSessionCache = new QuickLRU({ maxSize: maxCachedTlsSessions });
  1272. }
  1273. get protocol() {
  1274. return "https:";
  1275. }
  1276. normalizeOptions(options) {
  1277. let normalized = "";
  1278. for (let index = 0; index < nameKeys.length; index++) {
  1279. const key = nameKeys[index];
  1280. normalized += ":";
  1281. if (options && options[key] !== void 0) {
  1282. normalized += options[key];
  1283. }
  1284. }
  1285. return normalized;
  1286. }
  1287. _processQueue() {
  1288. if (this._sessionCount >= this.maxSessions) {
  1289. this.closeEmptySessions(this.maxSessions - this._sessionCount + 1);
  1290. return;
  1291. }
  1292. for (const normalizedOptions in this.queue) {
  1293. for (const normalizedOrigin in this.queue[normalizedOptions]) {
  1294. const item = this.queue[normalizedOptions][normalizedOrigin];
  1295. if (!item.completed) {
  1296. item.completed = true;
  1297. item();
  1298. }
  1299. }
  1300. }
  1301. }
  1302. _isBetterSession(thisStreamCount, thatStreamCount) {
  1303. return thisStreamCount > thatStreamCount;
  1304. }
  1305. _accept(session, listeners, normalizedOrigin, options) {
  1306. let index = 0;
  1307. while (index < listeners.length && session[kCurrentStreamCount] < session.remoteSettings.maxConcurrentStreams) {
  1308. listeners[index].resolve(session);
  1309. index++;
  1310. }
  1311. listeners.splice(0, index);
  1312. if (listeners.length > 0) {
  1313. this.getSession(normalizedOrigin, options, listeners);
  1314. listeners.length = 0;
  1315. }
  1316. }
  1317. getSession(origin, options, listeners) {
  1318. return new Promise((resolve, reject) => {
  1319. if (Array.isArray(listeners) && listeners.length > 0) {
  1320. listeners = [...listeners];
  1321. resolve();
  1322. } else {
  1323. listeners = [{ resolve, reject }];
  1324. }
  1325. try {
  1326. if (typeof origin === "string") {
  1327. origin = new URL4(origin);
  1328. } else if (!(origin instanceof URL4)) {
  1329. throw new TypeError("The `origin` argument needs to be a string or an URL object");
  1330. }
  1331. if (options) {
  1332. const { servername } = options;
  1333. const { hostname } = origin;
  1334. if (servername && hostname !== servername) {
  1335. throw new Error(`Origin ${hostname} differs from servername ${servername}`);
  1336. }
  1337. }
  1338. } catch (error) {
  1339. for (let index = 0; index < listeners.length; index++) {
  1340. listeners[index].reject(error);
  1341. }
  1342. return;
  1343. }
  1344. const normalizedOptions = this.normalizeOptions(options);
  1345. const normalizedOrigin = origin.origin;
  1346. if (normalizedOptions in this.sessions) {
  1347. const sessions = this.sessions[normalizedOptions];
  1348. let maxConcurrentStreams = -1;
  1349. let currentStreamsCount = -1;
  1350. let optimalSession;
  1351. for (let index = 0; index < sessions.length; index++) {
  1352. const session = sessions[index];
  1353. const sessionMaxConcurrentStreams = session.remoteSettings.maxConcurrentStreams;
  1354. if (sessionMaxConcurrentStreams < maxConcurrentStreams) {
  1355. break;
  1356. }
  1357. if (!session[kOriginSet].includes(normalizedOrigin)) {
  1358. continue;
  1359. }
  1360. const sessionCurrentStreamsCount = session[kCurrentStreamCount];
  1361. if (sessionCurrentStreamsCount >= sessionMaxConcurrentStreams || session[kGracefullyClosing] || session.destroyed) {
  1362. continue;
  1363. }
  1364. if (!optimalSession) {
  1365. maxConcurrentStreams = sessionMaxConcurrentStreams;
  1366. }
  1367. if (this._isBetterSession(sessionCurrentStreamsCount, currentStreamsCount)) {
  1368. optimalSession = session;
  1369. currentStreamsCount = sessionCurrentStreamsCount;
  1370. }
  1371. }
  1372. if (optimalSession) {
  1373. this._accept(optimalSession, listeners, normalizedOrigin, options);
  1374. return;
  1375. }
  1376. }
  1377. if (normalizedOptions in this.queue) {
  1378. if (normalizedOrigin in this.queue[normalizedOptions]) {
  1379. this.queue[normalizedOptions][normalizedOrigin].listeners.push(...listeners);
  1380. return;
  1381. }
  1382. } else {
  1383. this.queue[normalizedOptions] = {
  1384. [kLength]: 0
  1385. };
  1386. }
  1387. const removeFromQueue = () => {
  1388. if (normalizedOptions in this.queue && this.queue[normalizedOptions][normalizedOrigin] === entry) {
  1389. delete this.queue[normalizedOptions][normalizedOrigin];
  1390. if (--this.queue[normalizedOptions][kLength] === 0) {
  1391. delete this.queue[normalizedOptions];
  1392. }
  1393. }
  1394. };
  1395. const entry = async () => {
  1396. this._sessionCount++;
  1397. const name = `${normalizedOrigin}:${normalizedOptions}`;
  1398. let receivedSettings = false;
  1399. let socket;
  1400. try {
  1401. const computedOptions = { ...options };
  1402. if (computedOptions.settings === void 0) {
  1403. computedOptions.settings = this.settings;
  1404. }
  1405. if (computedOptions.session === void 0) {
  1406. computedOptions.session = this.tlsSessionCache.get(name);
  1407. }
  1408. const createConnection = computedOptions.createConnection || this.createConnection;
  1409. socket = await createConnection.call(this, origin, computedOptions);
  1410. computedOptions.createConnection = () => socket;
  1411. const session = http22.connect(origin, computedOptions);
  1412. session[kCurrentStreamCount] = 0;
  1413. session[kGracefullyClosing] = false;
  1414. const getOriginSet = () => {
  1415. const { socket: socket2 } = session;
  1416. let originSet;
  1417. if (socket2.servername === false) {
  1418. socket2.servername = socket2.remoteAddress;
  1419. originSet = session.originSet;
  1420. socket2.servername = false;
  1421. } else {
  1422. originSet = session.originSet;
  1423. }
  1424. return originSet;
  1425. };
  1426. const isFree = () => session[kCurrentStreamCount] < session.remoteSettings.maxConcurrentStreams;
  1427. session.socket.once("session", (tlsSession) => {
  1428. this.tlsSessionCache.set(name, tlsSession);
  1429. });
  1430. session.once("error", (error) => {
  1431. for (let index = 0; index < listeners.length; index++) {
  1432. listeners[index].reject(error);
  1433. }
  1434. this.tlsSessionCache.delete(name);
  1435. });
  1436. session.setTimeout(this.timeout, () => {
  1437. session.destroy();
  1438. });
  1439. session.once("close", () => {
  1440. this._sessionCount--;
  1441. if (receivedSettings) {
  1442. this._emptySessionCount--;
  1443. const where = this.sessions[normalizedOptions];
  1444. if (where.length === 1) {
  1445. delete this.sessions[normalizedOptions];
  1446. } else {
  1447. where.splice(where.indexOf(session), 1);
  1448. }
  1449. } else {
  1450. removeFromQueue();
  1451. const error = new Error("Session closed without receiving a SETTINGS frame");
  1452. error.code = "HTTP2WRAPPER_NOSETTINGS";
  1453. for (let index = 0; index < listeners.length; index++) {
  1454. listeners[index].reject(error);
  1455. }
  1456. }
  1457. this._processQueue();
  1458. });
  1459. const processListeners = () => {
  1460. const queue = this.queue[normalizedOptions];
  1461. if (!queue) {
  1462. return;
  1463. }
  1464. const originSet = session[kOriginSet];
  1465. for (let index = 0; index < originSet.length; index++) {
  1466. const origin2 = originSet[index];
  1467. if (origin2 in queue) {
  1468. const { listeners: listeners2, completed } = queue[origin2];
  1469. let index2 = 0;
  1470. while (index2 < listeners2.length && isFree()) {
  1471. listeners2[index2].resolve(session);
  1472. index2++;
  1473. }
  1474. queue[origin2].listeners.splice(0, index2);
  1475. if (queue[origin2].listeners.length === 0 && !completed) {
  1476. delete queue[origin2];
  1477. if (--queue[kLength] === 0) {
  1478. delete this.queue[normalizedOptions];
  1479. break;
  1480. }
  1481. }
  1482. if (!isFree()) {
  1483. break;
  1484. }
  1485. }
  1486. }
  1487. };
  1488. session.on("origin", () => {
  1489. session[kOriginSet] = getOriginSet() || [];
  1490. session[kGracefullyClosing] = false;
  1491. closeSessionIfCovered(this.sessions[normalizedOptions], session);
  1492. if (session[kGracefullyClosing] || !isFree()) {
  1493. return;
  1494. }
  1495. processListeners();
  1496. if (!isFree()) {
  1497. return;
  1498. }
  1499. closeCoveredSessions(this.sessions[normalizedOptions], session);
  1500. });
  1501. session.once("remoteSettings", () => {
  1502. if (entry.destroyed) {
  1503. const error = new Error("Agent has been destroyed");
  1504. for (let index = 0; index < listeners.length; index++) {
  1505. listeners[index].reject(error);
  1506. }
  1507. session.destroy();
  1508. return;
  1509. }
  1510. if (session.setLocalWindowSize) {
  1511. session.setLocalWindowSize(1024 * 1024 * 4);
  1512. }
  1513. session[kOriginSet] = getOriginSet() || [];
  1514. if (session.socket.encrypted) {
  1515. const mainOrigin = session[kOriginSet][0];
  1516. if (mainOrigin !== normalizedOrigin) {
  1517. const error = new Error(`Requested origin ${normalizedOrigin} does not match server ${mainOrigin}`);
  1518. for (let index = 0; index < listeners.length; index++) {
  1519. listeners[index].reject(error);
  1520. }
  1521. session.destroy();
  1522. return;
  1523. }
  1524. }
  1525. removeFromQueue();
  1526. {
  1527. const where = this.sessions;
  1528. if (normalizedOptions in where) {
  1529. const sessions = where[normalizedOptions];
  1530. sessions.splice(getSortedIndex(sessions, session, compareSessions), 0, session);
  1531. } else {
  1532. where[normalizedOptions] = [session];
  1533. }
  1534. }
  1535. receivedSettings = true;
  1536. this._emptySessionCount++;
  1537. this.emit("session", session);
  1538. this._accept(session, listeners, normalizedOrigin, options);
  1539. if (session[kCurrentStreamCount] === 0 && this._emptySessionCount > this.maxEmptySessions) {
  1540. this.closeEmptySessions(this._emptySessionCount - this.maxEmptySessions);
  1541. }
  1542. session.on("remoteSettings", () => {
  1543. if (!isFree()) {
  1544. return;
  1545. }
  1546. processListeners();
  1547. if (!isFree()) {
  1548. return;
  1549. }
  1550. closeCoveredSessions(this.sessions[normalizedOptions], session);
  1551. });
  1552. });
  1553. session[kRequest] = session.request;
  1554. session.request = (headers, streamOptions) => {
  1555. if (session[kGracefullyClosing]) {
  1556. throw new Error("The session is gracefully closing. No new streams are allowed.");
  1557. }
  1558. const stream2 = session[kRequest](headers, streamOptions);
  1559. session.ref();
  1560. if (session[kCurrentStreamCount]++ === 0) {
  1561. this._emptySessionCount--;
  1562. }
  1563. stream2.once("close", () => {
  1564. if (--session[kCurrentStreamCount] === 0) {
  1565. this._emptySessionCount++;
  1566. session.unref();
  1567. if (this._emptySessionCount > this.maxEmptySessions || session[kGracefullyClosing]) {
  1568. session.close();
  1569. return;
  1570. }
  1571. }
  1572. if (session.destroyed || session.closed) {
  1573. return;
  1574. }
  1575. if (isFree() && !closeSessionIfCovered(this.sessions[normalizedOptions], session)) {
  1576. closeCoveredSessions(this.sessions[normalizedOptions], session);
  1577. processListeners();
  1578. if (session[kCurrentStreamCount] === 0) {
  1579. this._processQueue();
  1580. }
  1581. }
  1582. });
  1583. return stream2;
  1584. };
  1585. } catch (error) {
  1586. removeFromQueue();
  1587. this._sessionCount--;
  1588. for (let index = 0; index < listeners.length; index++) {
  1589. listeners[index].reject(error);
  1590. }
  1591. }
  1592. };
  1593. entry.listeners = listeners;
  1594. entry.completed = false;
  1595. entry.destroyed = false;
  1596. this.queue[normalizedOptions][normalizedOrigin] = entry;
  1597. this.queue[normalizedOptions][kLength]++;
  1598. this._processQueue();
  1599. });
  1600. }
  1601. request(origin, options, headers, streamOptions) {
  1602. return new Promise((resolve, reject) => {
  1603. this.getSession(origin, options, [{
  1604. reject,
  1605. resolve: (session) => {
  1606. try {
  1607. const stream2 = session.request(headers, streamOptions);
  1608. delayAsyncDestroy(stream2);
  1609. resolve(stream2);
  1610. } catch (error) {
  1611. reject(error);
  1612. }
  1613. }
  1614. }]);
  1615. });
  1616. }
  1617. async createConnection(origin, options) {
  1618. return Agent.connect(origin, options);
  1619. }
  1620. static connect(origin, options) {
  1621. options.ALPNProtocols = ["h2"];
  1622. const port = origin.port || 443;
  1623. const host = origin.hostname;
  1624. if (typeof options.servername === "undefined") {
  1625. options.servername = host;
  1626. }
  1627. const socket = tls.connect(port, host, options);
  1628. if (options.socket) {
  1629. socket._peername = {
  1630. family: void 0,
  1631. address: void 0,
  1632. port
  1633. };
  1634. }
  1635. return socket;
  1636. }
  1637. closeEmptySessions(maxCount = Number.POSITIVE_INFINITY) {
  1638. let closedCount = 0;
  1639. const { sessions } = this;
  1640. for (const key in sessions) {
  1641. const thisSessions = sessions[key];
  1642. for (let index = 0; index < thisSessions.length; index++) {
  1643. const session = thisSessions[index];
  1644. if (session[kCurrentStreamCount] === 0) {
  1645. closedCount++;
  1646. session.close();
  1647. if (closedCount >= maxCount) {
  1648. return closedCount;
  1649. }
  1650. }
  1651. }
  1652. }
  1653. return closedCount;
  1654. }
  1655. destroy(reason) {
  1656. const { sessions, queue } = this;
  1657. for (const key in sessions) {
  1658. const thisSessions = sessions[key];
  1659. for (let index = 0; index < thisSessions.length; index++) {
  1660. thisSessions[index].destroy(reason);
  1661. }
  1662. }
  1663. for (const normalizedOptions in queue) {
  1664. const entries2 = queue[normalizedOptions];
  1665. for (const normalizedOrigin in entries2) {
  1666. entries2[normalizedOrigin].destroyed = true;
  1667. }
  1668. }
  1669. this.queue = {};
  1670. this.tlsSessionCache.clear();
  1671. }
  1672. get emptySessionCount() {
  1673. return this._emptySessionCount;
  1674. }
  1675. get pendingSessionCount() {
  1676. return this._sessionCount - this._emptySessionCount;
  1677. }
  1678. get sessionCount() {
  1679. return this._sessionCount;
  1680. }
  1681. };
  1682. Agent.kCurrentStreamCount = kCurrentStreamCount;
  1683. Agent.kGracefullyClosing = kGracefullyClosing;
  1684. module.exports = {
  1685. Agent,
  1686. globalAgent: new Agent()
  1687. };
  1688. }
  1689. });
  1690. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/incoming-message.js
  1691. var require_incoming_message = __commonJS({
  1692. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/incoming-message.js"(exports, module) {
  1693. "use strict";
  1694. var { Readable } = __require("stream");
  1695. var IncomingMessage = class extends Readable {
  1696. constructor(socket, highWaterMark) {
  1697. super({
  1698. emitClose: false,
  1699. autoDestroy: true,
  1700. highWaterMark
  1701. });
  1702. this.statusCode = null;
  1703. this.statusMessage = "";
  1704. this.httpVersion = "2.0";
  1705. this.httpVersionMajor = 2;
  1706. this.httpVersionMinor = 0;
  1707. this.headers = {};
  1708. this.trailers = {};
  1709. this.req = null;
  1710. this.aborted = false;
  1711. this.complete = false;
  1712. this.upgrade = null;
  1713. this.rawHeaders = [];
  1714. this.rawTrailers = [];
  1715. this.socket = socket;
  1716. this._dumped = false;
  1717. }
  1718. get connection() {
  1719. return this.socket;
  1720. }
  1721. set connection(value) {
  1722. this.socket = value;
  1723. }
  1724. _destroy(error, callback) {
  1725. if (!this.readableEnded) {
  1726. this.aborted = true;
  1727. }
  1728. callback();
  1729. this.req._request.destroy(error);
  1730. }
  1731. setTimeout(ms, callback) {
  1732. this.req.setTimeout(ms, callback);
  1733. return this;
  1734. }
  1735. _dump() {
  1736. if (!this._dumped) {
  1737. this._dumped = true;
  1738. this.removeAllListeners("data");
  1739. this.resume();
  1740. }
  1741. }
  1742. _read() {
  1743. if (this.req) {
  1744. this.req._request.resume();
  1745. }
  1746. }
  1747. };
  1748. module.exports = IncomingMessage;
  1749. }
  1750. });
  1751. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/proxy-events.js
  1752. var require_proxy_events = __commonJS({
  1753. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/proxy-events.js"(exports, module) {
  1754. "use strict";
  1755. module.exports = (from, to, events) => {
  1756. for (const event of events) {
  1757. from.on(event, (...args) => to.emit(event, ...args));
  1758. }
  1759. };
  1760. }
  1761. });
  1762. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/errors.js
  1763. var require_errors = __commonJS({
  1764. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/errors.js"(exports, module) {
  1765. "use strict";
  1766. var makeError = (Base, key, getMessage) => {
  1767. module.exports[key] = class NodeError extends Base {
  1768. constructor(...args) {
  1769. super(typeof getMessage === "string" ? getMessage : getMessage(args));
  1770. this.name = `${super.name} [${key}]`;
  1771. this.code = key;
  1772. }
  1773. };
  1774. };
  1775. makeError(TypeError, "ERR_INVALID_ARG_TYPE", (args) => {
  1776. const type = args[0].includes(".") ? "property" : "argument";
  1777. let valid = args[1];
  1778. const isManyTypes = Array.isArray(valid);
  1779. if (isManyTypes) {
  1780. valid = `${valid.slice(0, -1).join(", ")} or ${valid.slice(-1)}`;
  1781. }
  1782. return `The "${args[0]}" ${type} must be ${isManyTypes ? "one of" : "of"} type ${valid}. Received ${typeof args[2]}`;
  1783. });
  1784. makeError(
  1785. TypeError,
  1786. "ERR_INVALID_PROTOCOL",
  1787. (args) => `Protocol "${args[0]}" not supported. Expected "${args[1]}"`
  1788. );
  1789. makeError(
  1790. Error,
  1791. "ERR_HTTP_HEADERS_SENT",
  1792. (args) => `Cannot ${args[0]} headers after they are sent to the client`
  1793. );
  1794. makeError(
  1795. TypeError,
  1796. "ERR_INVALID_HTTP_TOKEN",
  1797. (args) => `${args[0]} must be a valid HTTP token [${args[1]}]`
  1798. );
  1799. makeError(
  1800. TypeError,
  1801. "ERR_HTTP_INVALID_HEADER_VALUE",
  1802. (args) => `Invalid value "${args[0]} for header "${args[1]}"`
  1803. );
  1804. makeError(
  1805. TypeError,
  1806. "ERR_INVALID_CHAR",
  1807. (args) => `Invalid character in ${args[0]} [${args[1]}]`
  1808. );
  1809. makeError(
  1810. Error,
  1811. "ERR_HTTP2_NO_SOCKET_MANIPULATION",
  1812. "HTTP/2 sockets should not be directly manipulated (e.g. read and written)"
  1813. );
  1814. }
  1815. });
  1816. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/is-request-pseudo-header.js
  1817. var require_is_request_pseudo_header = __commonJS({
  1818. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/is-request-pseudo-header.js"(exports, module) {
  1819. "use strict";
  1820. module.exports = (header) => {
  1821. switch (header) {
  1822. case ":method":
  1823. case ":scheme":
  1824. case ":authority":
  1825. case ":path":
  1826. return true;
  1827. default:
  1828. return false;
  1829. }
  1830. };
  1831. }
  1832. });
  1833. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/validate-header-name.js
  1834. var require_validate_header_name = __commonJS({
  1835. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/validate-header-name.js"(exports, module) {
  1836. "use strict";
  1837. var { ERR_INVALID_HTTP_TOKEN } = require_errors();
  1838. var isRequestPseudoHeader = require_is_request_pseudo_header();
  1839. var isValidHttpToken = /^[\^`\-\w!#$%&*+.|~]+$/;
  1840. module.exports = (name) => {
  1841. if (typeof name !== "string" || !isValidHttpToken.test(name) && !isRequestPseudoHeader(name)) {
  1842. throw new ERR_INVALID_HTTP_TOKEN("Header name", name);
  1843. }
  1844. };
  1845. }
  1846. });
  1847. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/validate-header-value.js
  1848. var require_validate_header_value = __commonJS({
  1849. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/validate-header-value.js"(exports, module) {
  1850. "use strict";
  1851. var {
  1852. ERR_HTTP_INVALID_HEADER_VALUE,
  1853. ERR_INVALID_CHAR
  1854. } = require_errors();
  1855. var isInvalidHeaderValue = /[^\t\u0020-\u007E\u0080-\u00FF]/;
  1856. module.exports = (name, value) => {
  1857. if (typeof value === "undefined") {
  1858. throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name);
  1859. }
  1860. if (isInvalidHeaderValue.test(value)) {
  1861. throw new ERR_INVALID_CHAR("header content", name);
  1862. }
  1863. };
  1864. }
  1865. });
  1866. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/proxy-socket-handler.js
  1867. var require_proxy_socket_handler = __commonJS({
  1868. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/proxy-socket-handler.js"(exports, module) {
  1869. "use strict";
  1870. var { ERR_HTTP2_NO_SOCKET_MANIPULATION } = require_errors();
  1871. var proxySocketHandler = {
  1872. has(stream2, property) {
  1873. const reference = stream2.session === void 0 ? stream2 : stream2.session.socket;
  1874. return property in stream2 || property in reference;
  1875. },
  1876. get(stream2, property) {
  1877. switch (property) {
  1878. case "on":
  1879. case "once":
  1880. case "end":
  1881. case "emit":
  1882. case "destroy":
  1883. return stream2[property].bind(stream2);
  1884. case "writable":
  1885. case "destroyed":
  1886. return stream2[property];
  1887. case "readable":
  1888. if (stream2.destroyed) {
  1889. return false;
  1890. }
  1891. return stream2.readable;
  1892. case "setTimeout": {
  1893. const { session } = stream2;
  1894. if (session !== void 0) {
  1895. return session.setTimeout.bind(session);
  1896. }
  1897. return stream2.setTimeout.bind(stream2);
  1898. }
  1899. case "write":
  1900. case "read":
  1901. case "pause":
  1902. case "resume":
  1903. throw new ERR_HTTP2_NO_SOCKET_MANIPULATION();
  1904. default: {
  1905. const reference = stream2.session === void 0 ? stream2 : stream2.session.socket;
  1906. const value = reference[property];
  1907. return typeof value === "function" ? value.bind(reference) : value;
  1908. }
  1909. }
  1910. },
  1911. getPrototypeOf(stream2) {
  1912. if (stream2.session !== void 0) {
  1913. return Reflect.getPrototypeOf(stream2.session.socket);
  1914. }
  1915. return Reflect.getPrototypeOf(stream2);
  1916. },
  1917. set(stream2, property, value) {
  1918. switch (property) {
  1919. case "writable":
  1920. case "readable":
  1921. case "destroyed":
  1922. case "on":
  1923. case "once":
  1924. case "end":
  1925. case "emit":
  1926. case "destroy":
  1927. stream2[property] = value;
  1928. return true;
  1929. case "setTimeout": {
  1930. const { session } = stream2;
  1931. if (session === void 0) {
  1932. stream2.setTimeout = value;
  1933. } else {
  1934. session.setTimeout = value;
  1935. }
  1936. return true;
  1937. }
  1938. case "write":
  1939. case "read":
  1940. case "pause":
  1941. case "resume":
  1942. throw new ERR_HTTP2_NO_SOCKET_MANIPULATION();
  1943. default: {
  1944. const reference = stream2.session === void 0 ? stream2 : stream2.session.socket;
  1945. reference[property] = value;
  1946. return true;
  1947. }
  1948. }
  1949. }
  1950. };
  1951. module.exports = proxySocketHandler;
  1952. }
  1953. });
  1954. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/client-request.js
  1955. var require_client_request = __commonJS({
  1956. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/client-request.js"(exports, module) {
  1957. "use strict";
  1958. var { URL: URL4, urlToHttpOptions } = __require("url");
  1959. var http22 = __require("http2");
  1960. var { Writable } = __require("stream");
  1961. var { Agent, globalAgent } = require_agent();
  1962. var IncomingMessage = require_incoming_message();
  1963. var proxyEvents2 = require_proxy_events();
  1964. var {
  1965. ERR_INVALID_ARG_TYPE,
  1966. ERR_INVALID_PROTOCOL,
  1967. ERR_HTTP_HEADERS_SENT
  1968. } = require_errors();
  1969. var validateHeaderName = require_validate_header_name();
  1970. var validateHeaderValue = require_validate_header_value();
  1971. var proxySocketHandler = require_proxy_socket_handler();
  1972. var {
  1973. HTTP2_HEADER_STATUS,
  1974. HTTP2_HEADER_METHOD,
  1975. HTTP2_HEADER_PATH,
  1976. HTTP2_HEADER_AUTHORITY,
  1977. HTTP2_METHOD_CONNECT
  1978. } = http22.constants;
  1979. var kHeaders = Symbol("headers");
  1980. var kOrigin = Symbol("origin");
  1981. var kSession = Symbol("session");
  1982. var kOptions = Symbol("options");
  1983. var kFlushedHeaders = Symbol("flushedHeaders");
  1984. var kJobs = Symbol("jobs");
  1985. var kPendingAgentPromise = Symbol("pendingAgentPromise");
  1986. var ClientRequest = class extends Writable {
  1987. constructor(input, options, callback) {
  1988. super({
  1989. autoDestroy: false,
  1990. emitClose: false
  1991. });
  1992. if (typeof input === "string") {
  1993. input = urlToHttpOptions(new URL4(input));
  1994. } else if (input instanceof URL4) {
  1995. input = urlToHttpOptions(input);
  1996. } else {
  1997. input = { ...input };
  1998. }
  1999. if (typeof options === "function" || options === void 0) {
  2000. callback = options;
  2001. options = input;
  2002. } else {
  2003. options = Object.assign(input, options);
  2004. }
  2005. if (options.h2session) {
  2006. this[kSession] = options.h2session;
  2007. if (this[kSession].destroyed) {
  2008. throw new Error("The session has been closed already");
  2009. }
  2010. this.protocol = this[kSession].socket.encrypted ? "https:" : "http:";
  2011. } else if (options.agent === false) {
  2012. this.agent = new Agent({ maxEmptySessions: 0 });
  2013. } else if (typeof options.agent === "undefined" || options.agent === null) {
  2014. this.agent = globalAgent;
  2015. } else if (typeof options.agent.request === "function") {
  2016. this.agent = options.agent;
  2017. } else {
  2018. throw new ERR_INVALID_ARG_TYPE("options.agent", ["http2wrapper.Agent-like Object", "undefined", "false"], options.agent);
  2019. }
  2020. if (this.agent) {
  2021. this.protocol = this.agent.protocol;
  2022. }
  2023. if (options.protocol && options.protocol !== this.protocol) {
  2024. throw new ERR_INVALID_PROTOCOL(options.protocol, this.protocol);
  2025. }
  2026. if (!options.port) {
  2027. options.port = options.defaultPort || this.agent && this.agent.defaultPort || 443;
  2028. }
  2029. options.host = options.hostname || options.host || "localhost";
  2030. delete options.hostname;
  2031. const { timeout } = options;
  2032. options.timeout = void 0;
  2033. this[kHeaders] = /* @__PURE__ */ Object.create(null);
  2034. this[kJobs] = [];
  2035. this[kPendingAgentPromise] = void 0;
  2036. this.socket = null;
  2037. this.connection = null;
  2038. this.method = options.method || "GET";
  2039. if (!(this.method === "CONNECT" && (options.path === "/" || options.path === void 0))) {
  2040. this.path = options.path;
  2041. }
  2042. this.res = null;
  2043. this.aborted = false;
  2044. this.reusedSocket = false;
  2045. const { headers } = options;
  2046. if (headers) {
  2047. for (const header in headers) {
  2048. this.setHeader(header, headers[header]);
  2049. }
  2050. }
  2051. if (options.auth && !("authorization" in this[kHeaders])) {
  2052. this[kHeaders].authorization = "Basic " + Buffer.from(options.auth).toString("base64");
  2053. }
  2054. options.session = options.tlsSession;
  2055. options.path = options.socketPath;
  2056. this[kOptions] = options;
  2057. this[kOrigin] = new URL4(`${this.protocol}//${options.servername || options.host}:${options.port}`);
  2058. const reuseSocket = options._reuseSocket;
  2059. if (reuseSocket) {
  2060. options.createConnection = (...args) => {
  2061. if (reuseSocket.destroyed) {
  2062. return this.agent.createConnection(...args);
  2063. }
  2064. return reuseSocket;
  2065. };
  2066. this.agent.getSession(this[kOrigin], this[kOptions]).catch(() => {
  2067. });
  2068. }
  2069. if (timeout) {
  2070. this.setTimeout(timeout);
  2071. }
  2072. if (callback) {
  2073. this.once("response", callback);
  2074. }
  2075. this[kFlushedHeaders] = false;
  2076. }
  2077. get method() {
  2078. return this[kHeaders][HTTP2_HEADER_METHOD];
  2079. }
  2080. set method(value) {
  2081. if (value) {
  2082. this[kHeaders][HTTP2_HEADER_METHOD] = value.toUpperCase();
  2083. }
  2084. }
  2085. get path() {
  2086. const header = this.method === "CONNECT" ? HTTP2_HEADER_AUTHORITY : HTTP2_HEADER_PATH;
  2087. return this[kHeaders][header];
  2088. }
  2089. set path(value) {
  2090. if (value) {
  2091. const header = this.method === "CONNECT" ? HTTP2_HEADER_AUTHORITY : HTTP2_HEADER_PATH;
  2092. this[kHeaders][header] = value;
  2093. }
  2094. }
  2095. get host() {
  2096. return this[kOrigin].hostname;
  2097. }
  2098. set host(_value) {
  2099. }
  2100. get _mustNotHaveABody() {
  2101. return this.method === "GET" || this.method === "HEAD" || this.method === "DELETE";
  2102. }
  2103. _write(chunk, encoding, callback) {
  2104. if (this._mustNotHaveABody) {
  2105. callback(new Error("The GET, HEAD and DELETE methods must NOT have a body"));
  2106. return;
  2107. }
  2108. this.flushHeaders();
  2109. const callWrite = () => this._request.write(chunk, encoding, callback);
  2110. if (this._request) {
  2111. callWrite();
  2112. } else {
  2113. this[kJobs].push(callWrite);
  2114. }
  2115. }
  2116. _final(callback) {
  2117. this.flushHeaders();
  2118. const callEnd = () => {
  2119. if (this._mustNotHaveABody || this.method === "CONNECT") {
  2120. callback();
  2121. return;
  2122. }
  2123. this._request.end(callback);
  2124. };
  2125. if (this._request) {
  2126. callEnd();
  2127. } else {
  2128. this[kJobs].push(callEnd);
  2129. }
  2130. }
  2131. abort() {
  2132. if (this.res && this.res.complete) {
  2133. return;
  2134. }
  2135. if (!this.aborted) {
  2136. process.nextTick(() => this.emit("abort"));
  2137. }
  2138. this.aborted = true;
  2139. this.destroy();
  2140. }
  2141. async _destroy(error, callback) {
  2142. if (this.res) {
  2143. this.res._dump();
  2144. }
  2145. if (this._request) {
  2146. this._request.destroy();
  2147. } else {
  2148. process.nextTick(() => {
  2149. this.emit("close");
  2150. });
  2151. }
  2152. try {
  2153. await this[kPendingAgentPromise];
  2154. } catch (internalError) {
  2155. if (this.aborted) {
  2156. error = internalError;
  2157. }
  2158. }
  2159. callback(error);
  2160. }
  2161. async flushHeaders() {
  2162. if (this[kFlushedHeaders] || this.destroyed) {
  2163. return;
  2164. }
  2165. this[kFlushedHeaders] = true;
  2166. const isConnectMethod = this.method === HTTP2_METHOD_CONNECT;
  2167. const onStream = (stream2) => {
  2168. this._request = stream2;
  2169. if (this.destroyed) {
  2170. stream2.destroy();
  2171. return;
  2172. }
  2173. if (!isConnectMethod) {
  2174. proxyEvents2(stream2, this, ["timeout", "continue"]);
  2175. }
  2176. stream2.once("error", (error) => {
  2177. this.destroy(error);
  2178. });
  2179. stream2.once("aborted", () => {
  2180. const { res } = this;
  2181. if (res) {
  2182. res.aborted = true;
  2183. res.emit("aborted");
  2184. res.destroy();
  2185. } else {
  2186. this.destroy(new Error("The server aborted the HTTP/2 stream"));
  2187. }
  2188. });
  2189. const onResponse = (headers, flags, rawHeaders) => {
  2190. const response = new IncomingMessage(this.socket, stream2.readableHighWaterMark);
  2191. this.res = response;
  2192. response.url = `${this[kOrigin].origin}${this.path}`;
  2193. response.req = this;
  2194. response.statusCode = headers[HTTP2_HEADER_STATUS];
  2195. response.headers = headers;
  2196. response.rawHeaders = rawHeaders;
  2197. response.once("end", () => {
  2198. response.complete = true;
  2199. response.socket = null;
  2200. response.connection = null;
  2201. });
  2202. if (isConnectMethod) {
  2203. response.upgrade = true;
  2204. if (this.emit("connect", response, stream2, Buffer.alloc(0))) {
  2205. this.emit("close");
  2206. } else {
  2207. stream2.destroy();
  2208. }
  2209. } else {
  2210. stream2.on("data", (chunk) => {
  2211. if (!response._dumped && !response.push(chunk)) {
  2212. stream2.pause();
  2213. }
  2214. });
  2215. stream2.once("end", () => {
  2216. if (!this.aborted) {
  2217. response.push(null);
  2218. }
  2219. });
  2220. if (!this.emit("response", response)) {
  2221. response._dump();
  2222. }
  2223. }
  2224. };
  2225. stream2.once("response", onResponse);
  2226. stream2.once("headers", (headers) => this.emit("information", { statusCode: headers[HTTP2_HEADER_STATUS] }));
  2227. stream2.once("trailers", (trailers, flags, rawTrailers) => {
  2228. const { res } = this;
  2229. if (res === null) {
  2230. onResponse(trailers, flags, rawTrailers);
  2231. return;
  2232. }
  2233. res.trailers = trailers;
  2234. res.rawTrailers = rawTrailers;
  2235. });
  2236. stream2.once("close", () => {
  2237. const { aborted, res } = this;
  2238. if (res) {
  2239. if (aborted) {
  2240. res.aborted = true;
  2241. res.emit("aborted");
  2242. res.destroy();
  2243. }
  2244. const finish = () => {
  2245. res.emit("close");
  2246. this.destroy();
  2247. this.emit("close");
  2248. };
  2249. if (res.readable) {
  2250. res.once("end", finish);
  2251. } else {
  2252. finish();
  2253. }
  2254. return;
  2255. }
  2256. if (!this.destroyed) {
  2257. this.destroy(new Error("The HTTP/2 stream has been early terminated"));
  2258. this.emit("close");
  2259. return;
  2260. }
  2261. this.destroy();
  2262. this.emit("close");
  2263. });
  2264. this.socket = new Proxy(stream2, proxySocketHandler);
  2265. for (const job of this[kJobs]) {
  2266. job();
  2267. }
  2268. this[kJobs].length = 0;
  2269. this.emit("socket", this.socket);
  2270. };
  2271. if (!(HTTP2_HEADER_AUTHORITY in this[kHeaders]) && !isConnectMethod) {
  2272. this[kHeaders][HTTP2_HEADER_AUTHORITY] = this[kOrigin].host;
  2273. }
  2274. if (this[kSession]) {
  2275. try {
  2276. onStream(this[kSession].request(this[kHeaders]));
  2277. } catch (error) {
  2278. this.destroy(error);
  2279. }
  2280. } else {
  2281. this.reusedSocket = true;
  2282. try {
  2283. const promise = this.agent.request(this[kOrigin], this[kOptions], this[kHeaders]);
  2284. this[kPendingAgentPromise] = promise;
  2285. onStream(await promise);
  2286. this[kPendingAgentPromise] = false;
  2287. } catch (error) {
  2288. this[kPendingAgentPromise] = false;
  2289. this.destroy(error);
  2290. }
  2291. }
  2292. }
  2293. get connection() {
  2294. return this.socket;
  2295. }
  2296. set connection(value) {
  2297. this.socket = value;
  2298. }
  2299. getHeaderNames() {
  2300. return Object.keys(this[kHeaders]);
  2301. }
  2302. hasHeader(name) {
  2303. if (typeof name !== "string") {
  2304. throw new ERR_INVALID_ARG_TYPE("name", "string", name);
  2305. }
  2306. return Boolean(this[kHeaders][name.toLowerCase()]);
  2307. }
  2308. getHeader(name) {
  2309. if (typeof name !== "string") {
  2310. throw new ERR_INVALID_ARG_TYPE("name", "string", name);
  2311. }
  2312. return this[kHeaders][name.toLowerCase()];
  2313. }
  2314. get headersSent() {
  2315. return this[kFlushedHeaders];
  2316. }
  2317. removeHeader(name) {
  2318. if (typeof name !== "string") {
  2319. throw new ERR_INVALID_ARG_TYPE("name", "string", name);
  2320. }
  2321. if (this.headersSent) {
  2322. throw new ERR_HTTP_HEADERS_SENT("remove");
  2323. }
  2324. delete this[kHeaders][name.toLowerCase()];
  2325. }
  2326. setHeader(name, value) {
  2327. if (this.headersSent) {
  2328. throw new ERR_HTTP_HEADERS_SENT("set");
  2329. }
  2330. validateHeaderName(name);
  2331. validateHeaderValue(name, value);
  2332. const lowercased = name.toLowerCase();
  2333. if (lowercased === "connection") {
  2334. if (value.toLowerCase() === "keep-alive") {
  2335. return;
  2336. }
  2337. throw new Error(`Invalid 'connection' header: ${value}`);
  2338. }
  2339. if (lowercased === "host" && this.method === "CONNECT") {
  2340. this[kHeaders][HTTP2_HEADER_AUTHORITY] = value;
  2341. } else {
  2342. this[kHeaders][lowercased] = value;
  2343. }
  2344. }
  2345. setNoDelay() {
  2346. }
  2347. setSocketKeepAlive() {
  2348. }
  2349. setTimeout(ms, callback) {
  2350. const applyTimeout = () => this._request.setTimeout(ms, callback);
  2351. if (this._request) {
  2352. applyTimeout();
  2353. } else {
  2354. this[kJobs].push(applyTimeout);
  2355. }
  2356. return this;
  2357. }
  2358. get maxHeadersCount() {
  2359. if (!this.destroyed && this._request) {
  2360. return this._request.session.localSettings.maxHeaderListSize;
  2361. }
  2362. return void 0;
  2363. }
  2364. set maxHeadersCount(_value) {
  2365. }
  2366. };
  2367. module.exports = ClientRequest;
  2368. }
  2369. });
  2370. // node_modules/.pnpm/resolve-alpn@1.2.1/node_modules/resolve-alpn/index.js
  2371. var require_resolve_alpn = __commonJS({
  2372. "node_modules/.pnpm/resolve-alpn@1.2.1/node_modules/resolve-alpn/index.js"(exports, module) {
  2373. "use strict";
  2374. var tls = __require("tls");
  2375. module.exports = (options = {}, connect = tls.connect) => new Promise((resolve, reject) => {
  2376. let timeout = false;
  2377. let socket;
  2378. const callback = async () => {
  2379. await socketPromise;
  2380. socket.off("timeout", onTimeout);
  2381. socket.off("error", reject);
  2382. if (options.resolveSocket) {
  2383. resolve({ alpnProtocol: socket.alpnProtocol, socket, timeout });
  2384. if (timeout) {
  2385. await Promise.resolve();
  2386. socket.emit("timeout");
  2387. }
  2388. } else {
  2389. socket.destroy();
  2390. resolve({ alpnProtocol: socket.alpnProtocol, timeout });
  2391. }
  2392. };
  2393. const onTimeout = async () => {
  2394. timeout = true;
  2395. callback();
  2396. };
  2397. const socketPromise = (async () => {
  2398. try {
  2399. socket = await connect(options, callback);
  2400. socket.on("error", reject);
  2401. socket.once("timeout", onTimeout);
  2402. } catch (error) {
  2403. reject(error);
  2404. }
  2405. })();
  2406. });
  2407. }
  2408. });
  2409. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/calculate-server-name.js
  2410. var require_calculate_server_name = __commonJS({
  2411. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/calculate-server-name.js"(exports, module) {
  2412. "use strict";
  2413. var { isIP } = __require("net");
  2414. var assert2 = __require("assert");
  2415. var getHost = (host) => {
  2416. if (host[0] === "[") {
  2417. const idx2 = host.indexOf("]");
  2418. assert2(idx2 !== -1);
  2419. return host.slice(1, idx2);
  2420. }
  2421. const idx = host.indexOf(":");
  2422. if (idx === -1) {
  2423. return host;
  2424. }
  2425. return host.slice(0, idx);
  2426. };
  2427. module.exports = (host) => {
  2428. const servername = getHost(host);
  2429. if (isIP(servername)) {
  2430. return "";
  2431. }
  2432. return servername;
  2433. };
  2434. }
  2435. });
  2436. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/auto.js
  2437. var require_auto = __commonJS({
  2438. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/auto.js"(exports, module) {
  2439. "use strict";
  2440. var { URL: URL4, urlToHttpOptions } = __require("url");
  2441. var http3 = __require("http");
  2442. var https2 = __require("https");
  2443. var resolveALPN = require_resolve_alpn();
  2444. var QuickLRU = require_quick_lru();
  2445. var { Agent, globalAgent } = require_agent();
  2446. var Http2ClientRequest = require_client_request();
  2447. var calculateServerName = require_calculate_server_name();
  2448. var delayAsyncDestroy = require_delay_async_destroy();
  2449. var cache = new QuickLRU({ maxSize: 100 });
  2450. var queue = /* @__PURE__ */ new Map();
  2451. var installSocket = (agent2, socket, options) => {
  2452. socket._httpMessage = { shouldKeepAlive: true };
  2453. const onFree = () => {
  2454. agent2.emit("free", socket, options);
  2455. };
  2456. socket.on("free", onFree);
  2457. const onClose = () => {
  2458. agent2.removeSocket(socket, options);
  2459. };
  2460. socket.on("close", onClose);
  2461. const onTimeout = () => {
  2462. const { freeSockets } = agent2;
  2463. for (const sockets of Object.values(freeSockets)) {
  2464. if (sockets.includes(socket)) {
  2465. socket.destroy();
  2466. return;
  2467. }
  2468. }
  2469. };
  2470. socket.on("timeout", onTimeout);
  2471. const onRemove = () => {
  2472. agent2.removeSocket(socket, options);
  2473. socket.off("close", onClose);
  2474. socket.off("free", onFree);
  2475. socket.off("timeout", onTimeout);
  2476. socket.off("agentRemove", onRemove);
  2477. };
  2478. socket.on("agentRemove", onRemove);
  2479. agent2.emit("free", socket, options);
  2480. };
  2481. var createResolveProtocol = (cache2, queue2 = /* @__PURE__ */ new Map(), connect = void 0) => {
  2482. return async (options) => {
  2483. const name = `${options.host}:${options.port}:${options.ALPNProtocols.sort()}`;
  2484. if (!cache2.has(name)) {
  2485. if (queue2.has(name)) {
  2486. const result = await queue2.get(name);
  2487. return { alpnProtocol: result.alpnProtocol };
  2488. }
  2489. const { path } = options;
  2490. options.path = options.socketPath;
  2491. const resultPromise = resolveALPN(options, connect);
  2492. queue2.set(name, resultPromise);
  2493. try {
  2494. const result = await resultPromise;
  2495. cache2.set(name, result.alpnProtocol);
  2496. queue2.delete(name);
  2497. options.path = path;
  2498. return result;
  2499. } catch (error) {
  2500. queue2.delete(name);
  2501. options.path = path;
  2502. throw error;
  2503. }
  2504. }
  2505. return { alpnProtocol: cache2.get(name) };
  2506. };
  2507. };
  2508. var defaultResolveProtocol = createResolveProtocol(cache, queue);
  2509. module.exports = async (input, options, callback) => {
  2510. if (typeof input === "string") {
  2511. input = urlToHttpOptions(new URL4(input));
  2512. } else if (input instanceof URL4) {
  2513. input = urlToHttpOptions(input);
  2514. } else {
  2515. input = { ...input };
  2516. }
  2517. if (typeof options === "function" || options === void 0) {
  2518. callback = options;
  2519. options = input;
  2520. } else {
  2521. options = Object.assign(input, options);
  2522. }
  2523. options.ALPNProtocols = options.ALPNProtocols || ["h2", "http/1.1"];
  2524. if (!Array.isArray(options.ALPNProtocols) || options.ALPNProtocols.length === 0) {
  2525. throw new Error("The `ALPNProtocols` option must be an Array with at least one entry");
  2526. }
  2527. options.protocol = options.protocol || "https:";
  2528. const isHttps = options.protocol === "https:";
  2529. options.host = options.hostname || options.host || "localhost";
  2530. options.session = options.tlsSession;
  2531. options.servername = options.servername || calculateServerName(options.headers && options.headers.host || options.host);
  2532. options.port = options.port || (isHttps ? 443 : 80);
  2533. options._defaultAgent = isHttps ? https2.globalAgent : http3.globalAgent;
  2534. const resolveProtocol = options.resolveProtocol || defaultResolveProtocol;
  2535. let { agent: agent2 } = options;
  2536. if (agent2 !== void 0 && agent2 !== false && agent2.constructor.name !== "Object") {
  2537. throw new Error("The `options.agent` can be only an object `http`, `https` or `http2` properties");
  2538. }
  2539. if (isHttps) {
  2540. options.resolveSocket = true;
  2541. let { socket, alpnProtocol, timeout } = await resolveProtocol(options);
  2542. if (timeout) {
  2543. if (socket) {
  2544. socket.destroy();
  2545. }
  2546. const error = new Error(`Timed out resolving ALPN: ${options.timeout} ms`);
  2547. error.code = "ETIMEDOUT";
  2548. error.ms = options.timeout;
  2549. throw error;
  2550. }
  2551. if (socket && options.createConnection) {
  2552. socket.destroy();
  2553. socket = void 0;
  2554. }
  2555. delete options.resolveSocket;
  2556. const isHttp2 = alpnProtocol === "h2";
  2557. if (agent2) {
  2558. agent2 = isHttp2 ? agent2.http2 : agent2.https;
  2559. options.agent = agent2;
  2560. }
  2561. if (agent2 === void 0) {
  2562. agent2 = isHttp2 ? globalAgent : https2.globalAgent;
  2563. }
  2564. if (socket) {
  2565. if (agent2 === false) {
  2566. socket.destroy();
  2567. } else {
  2568. const defaultCreateConnection = (isHttp2 ? Agent : https2.Agent).prototype.createConnection;
  2569. if (agent2.createConnection === defaultCreateConnection) {
  2570. if (isHttp2) {
  2571. options._reuseSocket = socket;
  2572. } else {
  2573. installSocket(agent2, socket, options);
  2574. }
  2575. } else {
  2576. socket.destroy();
  2577. }
  2578. }
  2579. }
  2580. if (isHttp2) {
  2581. return delayAsyncDestroy(new Http2ClientRequest(options, callback));
  2582. }
  2583. } else if (agent2) {
  2584. options.agent = agent2.http;
  2585. }
  2586. return delayAsyncDestroy(http3.request(options, callback));
  2587. };
  2588. module.exports.protocolCache = cache;
  2589. module.exports.resolveProtocol = defaultResolveProtocol;
  2590. module.exports.createResolveProtocol = createResolveProtocol;
  2591. }
  2592. });
  2593. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/js-stream-socket.js
  2594. var require_js_stream_socket = __commonJS({
  2595. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/js-stream-socket.js"(exports, module) {
  2596. "use strict";
  2597. var stream2 = __require("stream");
  2598. var tls = __require("tls");
  2599. var JSStreamSocket = new tls.TLSSocket(new stream2.PassThrough())._handle._parentWrap.constructor;
  2600. module.exports = JSStreamSocket;
  2601. }
  2602. });
  2603. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/unexpected-status-code-error.js
  2604. var require_unexpected_status_code_error = __commonJS({
  2605. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/unexpected-status-code-error.js"(exports, module) {
  2606. "use strict";
  2607. var UnexpectedStatusCodeError = class extends Error {
  2608. constructor(statusCode, statusMessage = "") {
  2609. super(`The proxy server rejected the request with status code ${statusCode} (${statusMessage || "empty status message"})`);
  2610. this.statusCode = statusCode;
  2611. this.statusMessage = statusMessage;
  2612. }
  2613. };
  2614. module.exports = UnexpectedStatusCodeError;
  2615. }
  2616. });
  2617. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/check-type.js
  2618. var require_check_type = __commonJS({
  2619. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/utils/check-type.js"(exports, module) {
  2620. "use strict";
  2621. var checkType = (name, value, types2) => {
  2622. const valid = types2.some((type) => {
  2623. const typeofType = typeof type;
  2624. if (typeofType === "string") {
  2625. return typeof value === type;
  2626. }
  2627. return value instanceof type;
  2628. });
  2629. if (!valid) {
  2630. const names = types2.map((type) => typeof type === "string" ? type : type.name);
  2631. throw new TypeError(`Expected '${name}' to be a type of ${names.join(" or ")}, got ${typeof value}`);
  2632. }
  2633. };
  2634. module.exports = checkType;
  2635. }
  2636. });
  2637. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/initialize.js
  2638. var require_initialize = __commonJS({
  2639. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/initialize.js"(exports, module) {
  2640. "use strict";
  2641. var { URL: URL4 } = __require("url");
  2642. var checkType = require_check_type();
  2643. module.exports = (self, proxyOptions) => {
  2644. checkType("proxyOptions", proxyOptions, ["object"]);
  2645. checkType("proxyOptions.headers", proxyOptions.headers, ["object", "undefined"]);
  2646. checkType("proxyOptions.raw", proxyOptions.raw, ["boolean", "undefined"]);
  2647. checkType("proxyOptions.url", proxyOptions.url, [URL4, "string"]);
  2648. const url = new URL4(proxyOptions.url);
  2649. self.proxyOptions = {
  2650. raw: true,
  2651. ...proxyOptions,
  2652. headers: { ...proxyOptions.headers },
  2653. url
  2654. };
  2655. };
  2656. }
  2657. });
  2658. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/get-auth-headers.js
  2659. var require_get_auth_headers = __commonJS({
  2660. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/get-auth-headers.js"(exports, module) {
  2661. "use strict";
  2662. module.exports = (self) => {
  2663. const { username, password } = self.proxyOptions.url;
  2664. if (username || password) {
  2665. const data = `${username}:${password}`;
  2666. const authorization = `Basic ${Buffer.from(data).toString("base64")}`;
  2667. return {
  2668. "proxy-authorization": authorization,
  2669. authorization
  2670. };
  2671. }
  2672. return {};
  2673. };
  2674. }
  2675. });
  2676. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/h1-over-h2.js
  2677. var require_h1_over_h2 = __commonJS({
  2678. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/h1-over-h2.js"(exports, module) {
  2679. "use strict";
  2680. var tls = __require("tls");
  2681. var http3 = __require("http");
  2682. var https2 = __require("https");
  2683. var JSStreamSocket = require_js_stream_socket();
  2684. var { globalAgent } = require_agent();
  2685. var UnexpectedStatusCodeError = require_unexpected_status_code_error();
  2686. var initialize = require_initialize();
  2687. var getAuthorizationHeaders = require_get_auth_headers();
  2688. var createConnection = (self, options, callback) => {
  2689. (async () => {
  2690. try {
  2691. const { proxyOptions } = self;
  2692. const { url, headers, raw } = proxyOptions;
  2693. const stream2 = await globalAgent.request(url, proxyOptions, {
  2694. ...getAuthorizationHeaders(self),
  2695. ...headers,
  2696. ":method": "CONNECT",
  2697. ":authority": `${options.host}:${options.port}`
  2698. });
  2699. stream2.once("error", callback);
  2700. stream2.once("response", (headers2) => {
  2701. const statusCode = headers2[":status"];
  2702. if (statusCode !== 200) {
  2703. callback(new UnexpectedStatusCodeError(statusCode, ""));
  2704. return;
  2705. }
  2706. const encrypted = self instanceof https2.Agent;
  2707. if (raw && encrypted) {
  2708. options.socket = stream2;
  2709. const secureStream = tls.connect(options);
  2710. secureStream.once("close", () => {
  2711. stream2.destroy();
  2712. });
  2713. callback(null, secureStream);
  2714. return;
  2715. }
  2716. const socket = new JSStreamSocket(stream2);
  2717. socket.encrypted = false;
  2718. socket._handle.getpeername = (out) => {
  2719. out.family = void 0;
  2720. out.address = void 0;
  2721. out.port = void 0;
  2722. };
  2723. callback(null, socket);
  2724. });
  2725. } catch (error) {
  2726. callback(error);
  2727. }
  2728. })();
  2729. };
  2730. var HttpOverHttp2 = class extends http3.Agent {
  2731. constructor(options) {
  2732. super(options);
  2733. initialize(this, options.proxyOptions);
  2734. }
  2735. createConnection(options, callback) {
  2736. createConnection(this, options, callback);
  2737. }
  2738. };
  2739. var HttpsOverHttp2 = class extends https2.Agent {
  2740. constructor(options) {
  2741. super(options);
  2742. initialize(this, options.proxyOptions);
  2743. }
  2744. createConnection(options, callback) {
  2745. createConnection(this, options, callback);
  2746. }
  2747. };
  2748. module.exports = {
  2749. HttpOverHttp2,
  2750. HttpsOverHttp2
  2751. };
  2752. }
  2753. });
  2754. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/h2-over-hx.js
  2755. var require_h2_over_hx = __commonJS({
  2756. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/h2-over-hx.js"(exports, module) {
  2757. "use strict";
  2758. var { Agent } = require_agent();
  2759. var JSStreamSocket = require_js_stream_socket();
  2760. var UnexpectedStatusCodeError = require_unexpected_status_code_error();
  2761. var initialize = require_initialize();
  2762. var Http2OverHttpX = class extends Agent {
  2763. constructor(options) {
  2764. super(options);
  2765. initialize(this, options.proxyOptions);
  2766. }
  2767. async createConnection(origin, options) {
  2768. const authority = `${origin.hostname}:${origin.port || 443}`;
  2769. const [stream2, statusCode, statusMessage] = await this._getProxyStream(authority);
  2770. if (statusCode !== 200) {
  2771. throw new UnexpectedStatusCodeError(statusCode, statusMessage);
  2772. }
  2773. if (this.proxyOptions.raw) {
  2774. options.socket = stream2;
  2775. } else {
  2776. const socket = new JSStreamSocket(stream2);
  2777. socket.encrypted = false;
  2778. socket._handle.getpeername = (out) => {
  2779. out.family = void 0;
  2780. out.address = void 0;
  2781. out.port = void 0;
  2782. };
  2783. return socket;
  2784. }
  2785. return super.createConnection(origin, options);
  2786. }
  2787. };
  2788. module.exports = Http2OverHttpX;
  2789. }
  2790. });
  2791. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/h2-over-h2.js
  2792. var require_h2_over_h2 = __commonJS({
  2793. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/h2-over-h2.js"(exports, module) {
  2794. "use strict";
  2795. var { globalAgent } = require_agent();
  2796. var Http2OverHttpX = require_h2_over_hx();
  2797. var getAuthorizationHeaders = require_get_auth_headers();
  2798. var getStatusCode = (stream2) => new Promise((resolve, reject) => {
  2799. stream2.once("error", reject);
  2800. stream2.once("response", (headers) => {
  2801. stream2.off("error", reject);
  2802. resolve(headers[":status"]);
  2803. });
  2804. });
  2805. var Http2OverHttp2 = class extends Http2OverHttpX {
  2806. async _getProxyStream(authority) {
  2807. const { proxyOptions } = this;
  2808. const headers = {
  2809. ...getAuthorizationHeaders(this),
  2810. ...proxyOptions.headers,
  2811. ":method": "CONNECT",
  2812. ":authority": authority
  2813. };
  2814. const stream2 = await globalAgent.request(proxyOptions.url, proxyOptions, headers);
  2815. const statusCode = await getStatusCode(stream2);
  2816. return [stream2, statusCode, ""];
  2817. }
  2818. };
  2819. module.exports = Http2OverHttp2;
  2820. }
  2821. });
  2822. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/h2-over-h1.js
  2823. var require_h2_over_h1 = __commonJS({
  2824. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/proxies/h2-over-h1.js"(exports, module) {
  2825. "use strict";
  2826. var http3 = __require("http");
  2827. var https2 = __require("https");
  2828. var Http2OverHttpX = require_h2_over_hx();
  2829. var getAuthorizationHeaders = require_get_auth_headers();
  2830. var getStream2 = (request) => new Promise((resolve, reject) => {
  2831. const onConnect = (response, socket, head) => {
  2832. socket.unshift(head);
  2833. request.off("error", reject);
  2834. resolve([socket, response.statusCode, response.statusMessage]);
  2835. };
  2836. request.once("error", reject);
  2837. request.once("connect", onConnect);
  2838. });
  2839. var Http2OverHttp = class extends Http2OverHttpX {
  2840. async _getProxyStream(authority) {
  2841. const { proxyOptions } = this;
  2842. const { url, headers } = this.proxyOptions;
  2843. const network = url.protocol === "https:" ? https2 : http3;
  2844. const request = network.request({
  2845. ...proxyOptions,
  2846. hostname: url.hostname,
  2847. port: url.port,
  2848. path: authority,
  2849. headers: {
  2850. ...getAuthorizationHeaders(this),
  2851. ...headers,
  2852. host: authority
  2853. },
  2854. method: "CONNECT"
  2855. }).end();
  2856. return getStream2(request);
  2857. }
  2858. };
  2859. module.exports = {
  2860. Http2OverHttp,
  2861. Http2OverHttps: Http2OverHttp
  2862. };
  2863. }
  2864. });
  2865. // node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/index.js
  2866. var require_source2 = __commonJS({
  2867. "node_modules/.pnpm/http2-wrapper@2.2.0/node_modules/http2-wrapper/source/index.js"(exports, module) {
  2868. "use strict";
  2869. var http22 = __require("http2");
  2870. var {
  2871. Agent,
  2872. globalAgent
  2873. } = require_agent();
  2874. var ClientRequest = require_client_request();
  2875. var IncomingMessage = require_incoming_message();
  2876. var auto = require_auto();
  2877. var {
  2878. HttpOverHttp2,
  2879. HttpsOverHttp2
  2880. } = require_h1_over_h2();
  2881. var Http2OverHttp2 = require_h2_over_h2();
  2882. var {
  2883. Http2OverHttp,
  2884. Http2OverHttps
  2885. } = require_h2_over_h1();
  2886. var validateHeaderName = require_validate_header_name();
  2887. var validateHeaderValue = require_validate_header_value();
  2888. var request = (url, options, callback) => new ClientRequest(url, options, callback);
  2889. var get = (url, options, callback) => {
  2890. const req = new ClientRequest(url, options, callback);
  2891. req.end();
  2892. return req;
  2893. };
  2894. module.exports = {
  2895. ...http22,
  2896. ClientRequest,
  2897. IncomingMessage,
  2898. Agent,
  2899. globalAgent,
  2900. request,
  2901. get,
  2902. auto,
  2903. proxies: {
  2904. HttpOverHttp2,
  2905. HttpsOverHttp2,
  2906. Http2OverHttp2,
  2907. Http2OverHttp,
  2908. Http2OverHttps
  2909. },
  2910. validateHeaderName,
  2911. validateHeaderValue
  2912. };
  2913. }
  2914. });
  2915. // src/index.ts
  2916. import { Agent as HttpAgent } from "http";
  2917. import { Agent as HttpsAgent } from "https";
  2918. // node_modules/.pnpm/@sindresorhus+is@5.3.0/node_modules/@sindresorhus/is/dist/index.js
  2919. var typedArrayTypeNames = [
  2920. "Int8Array",
  2921. "Uint8Array",
  2922. "Uint8ClampedArray",
  2923. "Int16Array",
  2924. "Uint16Array",
  2925. "Int32Array",
  2926. "Uint32Array",
  2927. "Float32Array",
  2928. "Float64Array",
  2929. "BigInt64Array",
  2930. "BigUint64Array"
  2931. ];
  2932. function isTypedArrayName(name) {
  2933. return typedArrayTypeNames.includes(name);
  2934. }
  2935. var objectTypeNames = [
  2936. "Function",
  2937. "Generator",
  2938. "AsyncGenerator",
  2939. "GeneratorFunction",
  2940. "AsyncGeneratorFunction",
  2941. "AsyncFunction",
  2942. "Observable",
  2943. "Array",
  2944. "Buffer",
  2945. "Blob",
  2946. "Object",
  2947. "RegExp",
  2948. "Date",
  2949. "Error",
  2950. "Map",
  2951. "Set",
  2952. "WeakMap",
  2953. "WeakSet",
  2954. "WeakRef",
  2955. "ArrayBuffer",
  2956. "SharedArrayBuffer",
  2957. "DataView",
  2958. "Promise",
  2959. "URL",
  2960. "FormData",
  2961. "URLSearchParams",
  2962. "HTMLElement",
  2963. "NaN",
  2964. ...typedArrayTypeNames
  2965. ];
  2966. function isObjectTypeName(name) {
  2967. return objectTypeNames.includes(name);
  2968. }
  2969. var primitiveTypeNames = [
  2970. "null",
  2971. "undefined",
  2972. "string",
  2973. "number",
  2974. "bigint",
  2975. "boolean",
  2976. "symbol"
  2977. ];
  2978. function isPrimitiveTypeName(name) {
  2979. return primitiveTypeNames.includes(name);
  2980. }
  2981. function isOfType(type) {
  2982. return (value) => typeof value === type;
  2983. }
  2984. var { toString } = Object.prototype;
  2985. var getObjectType = (value) => {
  2986. const objectTypeName = toString.call(value).slice(8, -1);
  2987. if (/HTML\w+Element/.test(objectTypeName) && is.domElement(value)) {
  2988. return "HTMLElement";
  2989. }
  2990. if (isObjectTypeName(objectTypeName)) {
  2991. return objectTypeName;
  2992. }
  2993. return void 0;
  2994. };
  2995. var isObjectOfType = (type) => (value) => getObjectType(value) === type;
  2996. function is(value) {
  2997. if (value === null) {
  2998. return "null";
  2999. }
  3000. switch (typeof value) {
  3001. case "undefined":
  3002. return "undefined";
  3003. case "string":
  3004. return "string";
  3005. case "number":
  3006. return Number.isNaN(value) ? "NaN" : "number";
  3007. case "boolean":
  3008. return "boolean";
  3009. case "function":
  3010. return "Function";
  3011. case "bigint":
  3012. return "bigint";
  3013. case "symbol":
  3014. return "symbol";
  3015. default:
  3016. }
  3017. if (is.observable(value)) {
  3018. return "Observable";
  3019. }
  3020. if (is.array(value)) {
  3021. return "Array";
  3022. }
  3023. if (is.buffer(value)) {
  3024. return "Buffer";
  3025. }
  3026. const tagType = getObjectType(value);
  3027. if (tagType) {
  3028. return tagType;
  3029. }
  3030. if (value instanceof String || value instanceof Boolean || value instanceof Number) {
  3031. throw new TypeError("Please don't use object wrappers for primitive types");
  3032. }
  3033. return "Object";
  3034. }
  3035. is.undefined = isOfType("undefined");
  3036. is.string = isOfType("string");
  3037. var isNumberType = isOfType("number");
  3038. is.number = (value) => isNumberType(value) && !is.nan(value);
  3039. is.bigint = isOfType("bigint");
  3040. is.function_ = isOfType("function");
  3041. is.null_ = (value) => value === null;
  3042. is.class_ = (value) => is.function_(value) && value.toString().startsWith("class ");
  3043. is.boolean = (value) => value === true || value === false;
  3044. is.symbol = isOfType("symbol");
  3045. is.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value));
  3046. is.array = (value, assertion) => {
  3047. if (!Array.isArray(value)) {
  3048. return false;
  3049. }
  3050. if (!is.function_(assertion)) {
  3051. return true;
  3052. }
  3053. return value.every((element) => assertion(element));
  3054. };
  3055. is.buffer = (value) => {
  3056. var _a, _b;
  3057. return ((_b = (_a = value == null ? void 0 : value.constructor) == null ? void 0 : _a.isBuffer) == null ? void 0 : _b.call(_a, value)) ?? false;
  3058. };
  3059. is.blob = (value) => isObjectOfType("Blob")(value);
  3060. is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value);
  3061. is.object = (value) => !is.null_(value) && (typeof value === "object" || is.function_(value));
  3062. is.iterable = (value) => is.function_(value == null ? void 0 : value[Symbol.iterator]);
  3063. is.asyncIterable = (value) => is.function_(value == null ? void 0 : value[Symbol.asyncIterator]);
  3064. is.generator = (value) => is.iterable(value) && is.function_(value == null ? void 0 : value.next) && is.function_(value == null ? void 0 : value.throw);
  3065. is.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw);
  3066. is.nativePromise = (value) => isObjectOfType("Promise")(value);
  3067. var hasPromiseApi = (value) => is.function_(value == null ? void 0 : value.then) && is.function_(value == null ? void 0 : value.catch);
  3068. is.promise = (value) => is.nativePromise(value) || hasPromiseApi(value);
  3069. is.generatorFunction = isObjectOfType("GeneratorFunction");
  3070. is.asyncGeneratorFunction = (value) => getObjectType(value) === "AsyncGeneratorFunction";
  3071. is.asyncFunction = (value) => getObjectType(value) === "AsyncFunction";
  3072. is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty("prototype");
  3073. is.regExp = isObjectOfType("RegExp");
  3074. is.date = isObjectOfType("Date");
  3075. is.error = isObjectOfType("Error");
  3076. is.map = (value) => isObjectOfType("Map")(value);
  3077. is.set = (value) => isObjectOfType("Set")(value);
  3078. is.weakMap = (value) => isObjectOfType("WeakMap")(value);
  3079. is.weakSet = (value) => isObjectOfType("WeakSet")(value);
  3080. is.weakRef = (value) => isObjectOfType("WeakRef")(value);
  3081. is.int8Array = isObjectOfType("Int8Array");
  3082. is.uint8Array = isObjectOfType("Uint8Array");
  3083. is.uint8ClampedArray = isObjectOfType("Uint8ClampedArray");
  3084. is.int16Array = isObjectOfType("Int16Array");
  3085. is.uint16Array = isObjectOfType("Uint16Array");
  3086. is.int32Array = isObjectOfType("Int32Array");
  3087. is.uint32Array = isObjectOfType("Uint32Array");
  3088. is.float32Array = isObjectOfType("Float32Array");
  3089. is.float64Array = isObjectOfType("Float64Array");
  3090. is.bigInt64Array = isObjectOfType("BigInt64Array");
  3091. is.bigUint64Array = isObjectOfType("BigUint64Array");
  3092. is.arrayBuffer = isObjectOfType("ArrayBuffer");
  3093. is.sharedArrayBuffer = isObjectOfType("SharedArrayBuffer");
  3094. is.dataView = isObjectOfType("DataView");
  3095. is.enumCase = (value, targetEnum) => Object.values(targetEnum).includes(value);
  3096. is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype;
  3097. is.urlInstance = (value) => isObjectOfType("URL")(value);
  3098. is.urlString = (value) => {
  3099. if (!is.string(value)) {
  3100. return false;
  3101. }
  3102. try {
  3103. new URL(value);
  3104. return true;
  3105. } catch {
  3106. return false;
  3107. }
  3108. };
  3109. is.truthy = (value) => Boolean(value);
  3110. is.falsy = (value) => !value;
  3111. is.nan = (value) => Number.isNaN(value);
  3112. is.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value);
  3113. is.integer = (value) => Number.isInteger(value);
  3114. is.safeInteger = (value) => Number.isSafeInteger(value);
  3115. is.plainObject = (value) => {
  3116. if (typeof value !== "object" || value === null) {
  3117. return false;
  3118. }
  3119. const prototype = Object.getPrototypeOf(value);
  3120. return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
  3121. };
  3122. is.typedArray = (value) => isTypedArrayName(getObjectType(value));
  3123. var isValidLength = (value) => is.safeInteger(value) && value >= 0;
  3124. is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length);
  3125. is.inRange = (value, range) => {
  3126. if (is.number(range)) {
  3127. return value >= Math.min(0, range) && value <= Math.max(range, 0);
  3128. }
  3129. if (is.array(range) && range.length === 2) {
  3130. return value >= Math.min(...range) && value <= Math.max(...range);
  3131. }
  3132. throw new TypeError(`Invalid range: ${JSON.stringify(range)}`);
  3133. };
  3134. var NODE_TYPE_ELEMENT = 1;
  3135. var DOM_PROPERTIES_TO_CHECK = [
  3136. "innerHTML",
  3137. "ownerDocument",
  3138. "style",
  3139. "attributes",
  3140. "nodeValue"
  3141. ];
  3142. is.domElement = (value) => is.object(value) && value.nodeType === NODE_TYPE_ELEMENT && is.string(value.nodeName) && !is.plainObject(value) && DOM_PROPERTIES_TO_CHECK.every((property) => property in value);
  3143. is.observable = (value) => {
  3144. var _a, _b;
  3145. if (!value) {
  3146. return false;
  3147. }
  3148. if (value === ((_a = value[Symbol.observable]) == null ? void 0 : _a.call(value))) {
  3149. return true;
  3150. }
  3151. if (value === ((_b = value["@@observable"]) == null ? void 0 : _b.call(value))) {
  3152. return true;
  3153. }
  3154. return false;
  3155. };
  3156. is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value);
  3157. is.infinite = (value) => value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY;
  3158. var isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder;
  3159. is.evenInteger = isAbsoluteMod2(0);
  3160. is.oddInteger = isAbsoluteMod2(1);
  3161. is.emptyArray = (value) => is.array(value) && value.length === 0;
  3162. is.nonEmptyArray = (value) => is.array(value) && value.length > 0;
  3163. is.emptyString = (value) => is.string(value) && value.length === 0;
  3164. var isWhiteSpaceString = (value) => is.string(value) && !/\S/.test(value);
  3165. is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value);
  3166. is.nonEmptyString = (value) => is.string(value) && value.length > 0;
  3167. is.nonEmptyStringAndNotWhitespace = (value) => is.string(value) && !is.emptyStringOrWhitespace(value);
  3168. is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0;
  3169. is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0;
  3170. is.emptySet = (value) => is.set(value) && value.size === 0;
  3171. is.nonEmptySet = (value) => is.set(value) && value.size > 0;
  3172. is.emptyMap = (value) => is.map(value) && value.size === 0;
  3173. is.nonEmptyMap = (value) => is.map(value) && value.size > 0;
  3174. is.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value);
  3175. is.formData = (value) => isObjectOfType("FormData")(value);
  3176. is.urlSearchParams = (value) => isObjectOfType("URLSearchParams")(value);
  3177. var predicateOnArray = (method, predicate, values) => {
  3178. if (!is.function_(predicate)) {
  3179. throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);
  3180. }
  3181. if (values.length === 0) {
  3182. throw new TypeError("Invalid number of values");
  3183. }
  3184. return method.call(values, predicate);
  3185. };
  3186. is.any = (predicate, ...values) => {
  3187. const predicates = is.array(predicate) ? predicate : [predicate];
  3188. return predicates.some((singlePredicate) => predicateOnArray(Array.prototype.some, singlePredicate, values));
  3189. };
  3190. is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values);
  3191. var assertType = (condition, description, value, options = {}) => {
  3192. if (!condition) {
  3193. const { multipleValues } = options;
  3194. const valuesMessage = multipleValues ? `received values of types ${[
  3195. ...new Set(value.map((singleValue) => `\`${is(singleValue)}\``))
  3196. ].join(", ")}` : `received value of type \`${is(value)}\``;
  3197. throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`);
  3198. }
  3199. };
  3200. var assert = {
  3201. // Unknowns.
  3202. undefined: (value) => assertType(is.undefined(value), "undefined", value),
  3203. string: (value) => assertType(is.string(value), "string", value),
  3204. number: (value) => assertType(is.number(value), "number", value),
  3205. bigint: (value) => assertType(is.bigint(value), "bigint", value),
  3206. // eslint-disable-next-line @typescript-eslint/ban-types
  3207. function_: (value) => assertType(is.function_(value), "Function", value),
  3208. null_: (value) => assertType(is.null_(value), "null", value),
  3209. class_: (value) => assertType(is.class_(value), "Class", value),
  3210. boolean: (value) => assertType(is.boolean(value), "boolean", value),
  3211. symbol: (value) => assertType(is.symbol(value), "symbol", value),
  3212. numericString: (value) => assertType(is.numericString(value), "string with a number", value),
  3213. array: (value, assertion) => {
  3214. const assert2 = assertType;
  3215. assert2(is.array(value), "Array", value);
  3216. if (assertion) {
  3217. value.forEach(assertion);
  3218. }
  3219. },
  3220. buffer: (value) => assertType(is.buffer(value), "Buffer", value),
  3221. blob: (value) => assertType(is.blob(value), "Blob", value),
  3222. nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined", value),
  3223. object: (value) => assertType(is.object(value), "Object", value),
  3224. iterable: (value) => assertType(is.iterable(value), "Iterable", value),
  3225. asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable", value),
  3226. generator: (value) => assertType(is.generator(value), "Generator", value),
  3227. asyncGenerator: (value) => assertType(is.asyncGenerator(value), "AsyncGenerator", value),
  3228. nativePromise: (value) => assertType(is.nativePromise(value), "native Promise", value),
  3229. promise: (value) => assertType(is.promise(value), "Promise", value),
  3230. generatorFunction: (value) => assertType(is.generatorFunction(value), "GeneratorFunction", value),
  3231. asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), "AsyncGeneratorFunction", value),
  3232. // eslint-disable-next-line @typescript-eslint/ban-types
  3233. asyncFunction: (value) => assertType(is.asyncFunction(value), "AsyncFunction", value),
  3234. // eslint-disable-next-line @typescript-eslint/ban-types
  3235. boundFunction: (value) => assertType(is.boundFunction(value), "Function", value),
  3236. regExp: (value) => assertType(is.regExp(value), "RegExp", value),
  3237. date: (value) => assertType(is.date(value), "Date", value),
  3238. error: (value) => assertType(is.error(value), "Error", value),
  3239. map: (value) => assertType(is.map(value), "Map", value),
  3240. set: (value) => assertType(is.set(value), "Set", value),
  3241. weakMap: (value) => assertType(is.weakMap(value), "WeakMap", value),
  3242. weakSet: (value) => assertType(is.weakSet(value), "WeakSet", value),
  3243. weakRef: (value) => assertType(is.weakRef(value), "WeakRef", value),
  3244. int8Array: (value) => assertType(is.int8Array(value), "Int8Array", value),
  3245. uint8Array: (value) => assertType(is.uint8Array(value), "Uint8Array", value),
  3246. uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), "Uint8ClampedArray", value),
  3247. int16Array: (value) => assertType(is.int16Array(value), "Int16Array", value),
  3248. uint16Array: (value) => assertType(is.uint16Array(value), "Uint16Array", value),
  3249. int32Array: (value) => assertType(is.int32Array(value), "Int32Array", value),
  3250. uint32Array: (value) => assertType(is.uint32Array(value), "Uint32Array", value),
  3251. float32Array: (value) => assertType(is.float32Array(value), "Float32Array", value),
  3252. float64Array: (value) => assertType(is.float64Array(value), "Float64Array", value),
  3253. bigInt64Array: (value) => assertType(is.bigInt64Array(value), "BigInt64Array", value),
  3254. bigUint64Array: (value) => assertType(is.bigUint64Array(value), "BigUint64Array", value),
  3255. arrayBuffer: (value) => assertType(is.arrayBuffer(value), "ArrayBuffer", value),
  3256. sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), "SharedArrayBuffer", value),
  3257. dataView: (value) => assertType(is.dataView(value), "DataView", value),
  3258. enumCase: (value, targetEnum) => assertType(is.enumCase(value, targetEnum), "EnumCase", value),
  3259. urlInstance: (value) => assertType(is.urlInstance(value), "URL", value),
  3260. urlString: (value) => assertType(is.urlString(value), "string with a URL", value),
  3261. truthy: (value) => assertType(is.truthy(value), "truthy", value),
  3262. falsy: (value) => assertType(is.falsy(value), "falsy", value),
  3263. nan: (value) => assertType(is.nan(value), "NaN", value),
  3264. primitive: (value) => assertType(is.primitive(value), "primitive", value),
  3265. integer: (value) => assertType(is.integer(value), "integer", value),
  3266. safeInteger: (value) => assertType(is.safeInteger(value), "integer", value),
  3267. plainObject: (value) => assertType(is.plainObject(value), "plain object", value),
  3268. typedArray: (value) => assertType(is.typedArray(value), "TypedArray", value),
  3269. arrayLike: (value) => assertType(is.arrayLike(value), "array-like", value),
  3270. domElement: (value) => assertType(is.domElement(value), "HTMLElement", value),
  3271. observable: (value) => assertType(is.observable(value), "Observable", value),
  3272. nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream", value),
  3273. infinite: (value) => assertType(is.infinite(value), "infinite number", value),
  3274. emptyArray: (value) => assertType(is.emptyArray(value), "empty array", value),
  3275. nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), "non-empty array", value),
  3276. emptyString: (value) => assertType(is.emptyString(value), "empty string", value),
  3277. emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), "empty string or whitespace", value),
  3278. nonEmptyString: (value) => assertType(is.nonEmptyString(value), "non-empty string", value),
  3279. nonEmptyStringAndNotWhitespace: (value) => assertType(is.nonEmptyStringAndNotWhitespace(value), "non-empty string and not whitespace", value),
  3280. emptyObject: (value) => assertType(is.emptyObject(value), "empty object", value),
  3281. nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), "non-empty object", value),
  3282. emptySet: (value) => assertType(is.emptySet(value), "empty set", value),
  3283. nonEmptySet: (value) => assertType(is.nonEmptySet(value), "non-empty set", value),
  3284. emptyMap: (value) => assertType(is.emptyMap(value), "empty map", value),
  3285. nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), "non-empty map", value),
  3286. propertyKey: (value) => assertType(is.propertyKey(value), "PropertyKey", value),
  3287. formData: (value) => assertType(is.formData(value), "FormData", value),
  3288. urlSearchParams: (value) => assertType(is.urlSearchParams(value), "URLSearchParams", value),
  3289. // Numbers.
  3290. evenInteger: (value) => assertType(is.evenInteger(value), "even integer", value),
  3291. oddInteger: (value) => assertType(is.oddInteger(value), "odd integer", value),
  3292. // Two arguments.
  3293. directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), "T", instance),
  3294. inRange: (value, range) => assertType(is.inRange(value, range), "in range", value),
  3295. // Variadic functions.
  3296. any: (predicate, ...values) => assertType(is.any(predicate, ...values), "predicate returns truthy for any value", values, { multipleValues: true }),
  3297. all: (predicate, ...values) => assertType(is.all(predicate, ...values), "predicate returns truthy for all values", values, { multipleValues: true })
  3298. };
  3299. Object.defineProperties(is, {
  3300. class: {
  3301. value: is.class_
  3302. },
  3303. function: {
  3304. value: is.function_
  3305. },
  3306. null: {
  3307. value: is.null_
  3308. }
  3309. });
  3310. Object.defineProperties(assert, {
  3311. class: {
  3312. value: assert.class_
  3313. },
  3314. function: {
  3315. value: assert.function_
  3316. },
  3317. null: {
  3318. value: assert.null_
  3319. }
  3320. });
  3321. var dist_default = is;
  3322. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/as-promise/index.js
  3323. import { EventEmitter as EventEmitter2 } from "node:events";
  3324. // node_modules/.pnpm/p-cancelable@3.0.0/node_modules/p-cancelable/index.js
  3325. var CancelError = class extends Error {
  3326. constructor(reason) {
  3327. super(reason || "Promise was canceled");
  3328. this.name = "CancelError";
  3329. }
  3330. get isCanceled() {
  3331. return true;
  3332. }
  3333. };
  3334. var PCancelable = class {
  3335. static fn(userFunction) {
  3336. return (...arguments_) => {
  3337. return new PCancelable((resolve, reject, onCancel) => {
  3338. arguments_.push(onCancel);
  3339. userFunction(...arguments_).then(resolve, reject);
  3340. });
  3341. };
  3342. }
  3343. constructor(executor) {
  3344. this._cancelHandlers = [];
  3345. this._isPending = true;
  3346. this._isCanceled = false;
  3347. this._rejectOnCancel = true;
  3348. this._promise = new Promise((resolve, reject) => {
  3349. this._reject = reject;
  3350. const onResolve = (value) => {
  3351. if (!this._isCanceled || !onCancel.shouldReject) {
  3352. this._isPending = false;
  3353. resolve(value);
  3354. }
  3355. };
  3356. const onReject = (error) => {
  3357. this._isPending = false;
  3358. reject(error);
  3359. };
  3360. const onCancel = (handler) => {
  3361. if (!this._isPending) {
  3362. throw new Error("The `onCancel` handler was attached after the promise settled.");
  3363. }
  3364. this._cancelHandlers.push(handler);
  3365. };
  3366. Object.defineProperties(onCancel, {
  3367. shouldReject: {
  3368. get: () => this._rejectOnCancel,
  3369. set: (boolean) => {
  3370. this._rejectOnCancel = boolean;
  3371. }
  3372. }
  3373. });
  3374. executor(onResolve, onReject, onCancel);
  3375. });
  3376. }
  3377. then(onFulfilled, onRejected) {
  3378. return this._promise.then(onFulfilled, onRejected);
  3379. }
  3380. catch(onRejected) {
  3381. return this._promise.catch(onRejected);
  3382. }
  3383. finally(onFinally) {
  3384. return this._promise.finally(onFinally);
  3385. }
  3386. cancel(reason) {
  3387. if (!this._isPending || this._isCanceled) {
  3388. return;
  3389. }
  3390. this._isCanceled = true;
  3391. if (this._cancelHandlers.length > 0) {
  3392. try {
  3393. for (const handler of this._cancelHandlers) {
  3394. handler();
  3395. }
  3396. } catch (error) {
  3397. this._reject(error);
  3398. return;
  3399. }
  3400. }
  3401. if (this._rejectOnCancel) {
  3402. this._reject(new CancelError(reason));
  3403. }
  3404. }
  3405. get isCanceled() {
  3406. return this._isCanceled;
  3407. }
  3408. };
  3409. Object.setPrototypeOf(PCancelable.prototype, Promise.prototype);
  3410. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/errors.js
  3411. function isRequest(x) {
  3412. return dist_default.object(x) && "_onResponse" in x;
  3413. }
  3414. var RequestError = class extends Error {
  3415. constructor(message, error, self) {
  3416. var _a;
  3417. super(message);
  3418. Object.defineProperty(this, "input", {
  3419. enumerable: true,
  3420. configurable: true,
  3421. writable: true,
  3422. value: void 0
  3423. });
  3424. Object.defineProperty(this, "code", {
  3425. enumerable: true,
  3426. configurable: true,
  3427. writable: true,
  3428. value: void 0
  3429. });
  3430. Object.defineProperty(this, "stack", {
  3431. enumerable: true,
  3432. configurable: true,
  3433. writable: true,
  3434. value: void 0
  3435. });
  3436. Object.defineProperty(this, "response", {
  3437. enumerable: true,
  3438. configurable: true,
  3439. writable: true,
  3440. value: void 0
  3441. });
  3442. Object.defineProperty(this, "request", {
  3443. enumerable: true,
  3444. configurable: true,
  3445. writable: true,
  3446. value: void 0
  3447. });
  3448. Object.defineProperty(this, "timings", {
  3449. enumerable: true,
  3450. configurable: true,
  3451. writable: true,
  3452. value: void 0
  3453. });
  3454. Error.captureStackTrace(this, this.constructor);
  3455. this.name = "RequestError";
  3456. this.code = error.code ?? "ERR_GOT_REQUEST_ERROR";
  3457. this.input = error.input;
  3458. if (isRequest(self)) {
  3459. Object.defineProperty(this, "request", {
  3460. enumerable: false,
  3461. value: self
  3462. });
  3463. Object.defineProperty(this, "response", {
  3464. enumerable: false,
  3465. value: self.response
  3466. });
  3467. this.options = self.options;
  3468. } else {
  3469. this.options = self;
  3470. }
  3471. this.timings = (_a = this.request) == null ? void 0 : _a.timings;
  3472. if (dist_default.string(error.stack) && dist_default.string(this.stack)) {
  3473. const indexOfMessage = this.stack.indexOf(this.message) + this.message.length;
  3474. const thisStackTrace = this.stack.slice(indexOfMessage).split("\n").reverse();
  3475. const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message) + error.message.length).split("\n").reverse();
  3476. while (errorStackTrace.length > 0 && errorStackTrace[0] === thisStackTrace[0]) {
  3477. thisStackTrace.shift();
  3478. }
  3479. this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join("\n")}${errorStackTrace.reverse().join("\n")}`;
  3480. }
  3481. }
  3482. };
  3483. var MaxRedirectsError = class extends RequestError {
  3484. constructor(request) {
  3485. super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request);
  3486. this.name = "MaxRedirectsError";
  3487. this.code = "ERR_TOO_MANY_REDIRECTS";
  3488. }
  3489. };
  3490. var HTTPError = class extends RequestError {
  3491. constructor(response) {
  3492. super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, response.request);
  3493. this.name = "HTTPError";
  3494. this.code = "ERR_NON_2XX_3XX_RESPONSE";
  3495. }
  3496. };
  3497. var CacheError = class extends RequestError {
  3498. constructor(error, request) {
  3499. super(error.message, error, request);
  3500. this.name = "CacheError";
  3501. this.code = this.code === "ERR_GOT_REQUEST_ERROR" ? "ERR_CACHE_ACCESS" : this.code;
  3502. }
  3503. };
  3504. var UploadError = class extends RequestError {
  3505. constructor(error, request) {
  3506. super(error.message, error, request);
  3507. this.name = "UploadError";
  3508. this.code = this.code === "ERR_GOT_REQUEST_ERROR" ? "ERR_UPLOAD" : this.code;
  3509. }
  3510. };
  3511. var TimeoutError = class extends RequestError {
  3512. constructor(error, timings, request) {
  3513. super(error.message, error, request);
  3514. Object.defineProperty(this, "timings", {
  3515. enumerable: true,
  3516. configurable: true,
  3517. writable: true,
  3518. value: void 0
  3519. });
  3520. Object.defineProperty(this, "event", {
  3521. enumerable: true,
  3522. configurable: true,
  3523. writable: true,
  3524. value: void 0
  3525. });
  3526. this.name = "TimeoutError";
  3527. this.event = error.event;
  3528. this.timings = timings;
  3529. }
  3530. };
  3531. var ReadError = class extends RequestError {
  3532. constructor(error, request) {
  3533. super(error.message, error, request);
  3534. this.name = "ReadError";
  3535. this.code = this.code === "ERR_GOT_REQUEST_ERROR" ? "ERR_READING_RESPONSE_STREAM" : this.code;
  3536. }
  3537. };
  3538. var RetryError = class extends RequestError {
  3539. constructor(request) {
  3540. super("Retrying", {}, request);
  3541. this.name = "RetryError";
  3542. this.code = "ERR_RETRYING";
  3543. }
  3544. };
  3545. var AbortError = class extends RequestError {
  3546. constructor(request) {
  3547. super("This operation was aborted.", {}, request);
  3548. this.code = "ERR_ABORTED";
  3549. this.name = "AbortError";
  3550. }
  3551. };
  3552. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/index.js
  3553. import process3 from "node:process";
  3554. import { Buffer as Buffer3 } from "node:buffer";
  3555. import { Duplex } from "node:stream";
  3556. import { URL as URL3, URLSearchParams as URLSearchParams2 } from "node:url";
  3557. import http2, { ServerResponse } from "node:http";
  3558. // node_modules/.pnpm/@szmarczak+http-timer@5.0.1/node_modules/@szmarczak/http-timer/dist/source/index.js
  3559. var import_defer_to_connect = __toESM(require_source(), 1);
  3560. import { errorMonitor } from "events";
  3561. import { types } from "util";
  3562. var timer = (request) => {
  3563. if (request.timings) {
  3564. return request.timings;
  3565. }
  3566. const timings = {
  3567. start: Date.now(),
  3568. socket: void 0,
  3569. lookup: void 0,
  3570. connect: void 0,
  3571. secureConnect: void 0,
  3572. upload: void 0,
  3573. response: void 0,
  3574. end: void 0,
  3575. error: void 0,
  3576. abort: void 0,
  3577. phases: {
  3578. wait: void 0,
  3579. dns: void 0,
  3580. tcp: void 0,
  3581. tls: void 0,
  3582. request: void 0,
  3583. firstByte: void 0,
  3584. download: void 0,
  3585. total: void 0
  3586. }
  3587. };
  3588. request.timings = timings;
  3589. const handleError = (origin) => {
  3590. origin.once(errorMonitor, () => {
  3591. timings.error = Date.now();
  3592. timings.phases.total = timings.error - timings.start;
  3593. });
  3594. };
  3595. handleError(request);
  3596. const onAbort = () => {
  3597. timings.abort = Date.now();
  3598. timings.phases.total = timings.abort - timings.start;
  3599. };
  3600. request.prependOnceListener("abort", onAbort);
  3601. const onSocket = (socket) => {
  3602. timings.socket = Date.now();
  3603. timings.phases.wait = timings.socket - timings.start;
  3604. if (types.isProxy(socket)) {
  3605. return;
  3606. }
  3607. const lookupListener = () => {
  3608. timings.lookup = Date.now();
  3609. timings.phases.dns = timings.lookup - timings.socket;
  3610. };
  3611. socket.prependOnceListener("lookup", lookupListener);
  3612. (0, import_defer_to_connect.default)(socket, {
  3613. connect: () => {
  3614. timings.connect = Date.now();
  3615. if (timings.lookup === void 0) {
  3616. socket.removeListener("lookup", lookupListener);
  3617. timings.lookup = timings.connect;
  3618. timings.phases.dns = timings.lookup - timings.socket;
  3619. }
  3620. timings.phases.tcp = timings.connect - timings.lookup;
  3621. },
  3622. secureConnect: () => {
  3623. timings.secureConnect = Date.now();
  3624. timings.phases.tls = timings.secureConnect - timings.connect;
  3625. }
  3626. });
  3627. };
  3628. if (request.socket) {
  3629. onSocket(request.socket);
  3630. } else {
  3631. request.prependOnceListener("socket", onSocket);
  3632. }
  3633. const onUpload = () => {
  3634. timings.upload = Date.now();
  3635. timings.phases.request = timings.upload - (timings.secureConnect ?? timings.connect);
  3636. };
  3637. if (request.writableFinished) {
  3638. onUpload();
  3639. } else {
  3640. request.prependOnceListener("finish", onUpload);
  3641. }
  3642. request.prependOnceListener("response", (response) => {
  3643. timings.response = Date.now();
  3644. timings.phases.firstByte = timings.response - timings.upload;
  3645. response.timings = timings;
  3646. handleError(response);
  3647. response.prependOnceListener("end", () => {
  3648. request.off("abort", onAbort);
  3649. response.off("aborted", onAbort);
  3650. if (timings.phases.total) {
  3651. return;
  3652. }
  3653. timings.end = Date.now();
  3654. timings.phases.download = timings.end - timings.response;
  3655. timings.phases.total = timings.end - timings.start;
  3656. });
  3657. response.prependOnceListener("aborted", onAbort);
  3658. });
  3659. return timings;
  3660. };
  3661. var source_default = timer;
  3662. // node_modules/.pnpm/cacheable-request@10.2.7/node_modules/cacheable-request/dist/index.js
  3663. import EventEmitter from "node:events";
  3664. import urlLib from "node:url";
  3665. import crypto from "node:crypto";
  3666. import stream, { PassThrough as PassThroughStream } from "node:stream";
  3667. // node_modules/.pnpm/normalize-url@8.0.0/node_modules/normalize-url/index.js
  3668. var DATA_URL_DEFAULT_MIME_TYPE = "text/plain";
  3669. var DATA_URL_DEFAULT_CHARSET = "us-ascii";
  3670. var testParameter = (name, filters) => filters.some((filter) => filter instanceof RegExp ? filter.test(name) : filter === name);
  3671. var supportedProtocols = /* @__PURE__ */ new Set([
  3672. "https:",
  3673. "http:",
  3674. "file:"
  3675. ]);
  3676. var hasCustomProtocol = (urlString) => {
  3677. try {
  3678. const { protocol } = new URL(urlString);
  3679. return protocol.endsWith(":") && !supportedProtocols.has(protocol);
  3680. } catch {
  3681. return false;
  3682. }
  3683. };
  3684. var normalizeDataURL = (urlString, { stripHash }) => {
  3685. var _a;
  3686. const match = /^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(urlString);
  3687. if (!match) {
  3688. throw new Error(`Invalid URL: ${urlString}`);
  3689. }
  3690. let { type, data, hash } = match.groups;
  3691. const mediaType = type.split(";");
  3692. hash = stripHash ? "" : hash;
  3693. let isBase64 = false;
  3694. if (mediaType[mediaType.length - 1] === "base64") {
  3695. mediaType.pop();
  3696. isBase64 = true;
  3697. }
  3698. const mimeType = ((_a = mediaType.shift()) == null ? void 0 : _a.toLowerCase()) ?? "";
  3699. const attributes = mediaType.map((attribute) => {
  3700. let [key, value = ""] = attribute.split("=").map((string) => string.trim());
  3701. if (key === "charset") {
  3702. value = value.toLowerCase();
  3703. if (value === DATA_URL_DEFAULT_CHARSET) {
  3704. return "";
  3705. }
  3706. }
  3707. return `${key}${value ? `=${value}` : ""}`;
  3708. }).filter(Boolean);
  3709. const normalizedMediaType = [
  3710. ...attributes
  3711. ];
  3712. if (isBase64) {
  3713. normalizedMediaType.push("base64");
  3714. }
  3715. if (normalizedMediaType.length > 0 || mimeType && mimeType !== DATA_URL_DEFAULT_MIME_TYPE) {
  3716. normalizedMediaType.unshift(mimeType);
  3717. }
  3718. return `data:${normalizedMediaType.join(";")},${isBase64 ? data.trim() : data}${hash ? `#${hash}` : ""}`;
  3719. };
  3720. function normalizeUrl(urlString, options) {
  3721. options = {
  3722. defaultProtocol: "http",
  3723. normalizeProtocol: true,
  3724. forceHttp: false,
  3725. forceHttps: false,
  3726. stripAuthentication: true,
  3727. stripHash: false,
  3728. stripTextFragment: true,
  3729. stripWWW: true,
  3730. removeQueryParameters: [/^utm_\w+/i],
  3731. removeTrailingSlash: true,
  3732. removeSingleSlash: true,
  3733. removeDirectoryIndex: false,
  3734. removeExplicitPort: false,
  3735. sortQueryParameters: true,
  3736. ...options
  3737. };
  3738. if (typeof options.defaultProtocol === "string" && !options.defaultProtocol.endsWith(":")) {
  3739. options.defaultProtocol = `${options.defaultProtocol}:`;
  3740. }
  3741. urlString = urlString.trim();
  3742. if (/^data:/i.test(urlString)) {
  3743. return normalizeDataURL(urlString, options);
  3744. }
  3745. if (hasCustomProtocol(urlString)) {
  3746. return urlString;
  3747. }
  3748. const hasRelativeProtocol = urlString.startsWith("//");
  3749. const isRelativeUrl = !hasRelativeProtocol && /^\.*\//.test(urlString);
  3750. if (!isRelativeUrl) {
  3751. urlString = urlString.replace(/^(?!(?:\w+:)?\/\/)|^\/\//, options.defaultProtocol);
  3752. }
  3753. const urlObject = new URL(urlString);
  3754. if (options.forceHttp && options.forceHttps) {
  3755. throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");
  3756. }
  3757. if (options.forceHttp && urlObject.protocol === "https:") {
  3758. urlObject.protocol = "http:";
  3759. }
  3760. if (options.forceHttps && urlObject.protocol === "http:") {
  3761. urlObject.protocol = "https:";
  3762. }
  3763. if (options.stripAuthentication) {
  3764. urlObject.username = "";
  3765. urlObject.password = "";
  3766. }
  3767. if (options.stripHash) {
  3768. urlObject.hash = "";
  3769. } else if (options.stripTextFragment) {
  3770. urlObject.hash = urlObject.hash.replace(/#?:~:text.*?$/i, "");
  3771. }
  3772. if (urlObject.pathname) {
  3773. const protocolRegex = /\b[a-z][a-z\d+\-.]{1,50}:\/\//g;
  3774. let lastIndex = 0;
  3775. let result = "";
  3776. for (; ; ) {
  3777. const match = protocolRegex.exec(urlObject.pathname);
  3778. if (!match) {
  3779. break;
  3780. }
  3781. const protocol = match[0];
  3782. const protocolAtIndex = match.index;
  3783. const intermediate = urlObject.pathname.slice(lastIndex, protocolAtIndex);
  3784. result += intermediate.replace(/\/{2,}/g, "/");
  3785. result += protocol;
  3786. lastIndex = protocolAtIndex + protocol.length;
  3787. }
  3788. const remnant = urlObject.pathname.slice(lastIndex, urlObject.pathname.length);
  3789. result += remnant.replace(/\/{2,}/g, "/");
  3790. urlObject.pathname = result;
  3791. }
  3792. if (urlObject.pathname) {
  3793. try {
  3794. urlObject.pathname = decodeURI(urlObject.pathname);
  3795. } catch {
  3796. }
  3797. }
  3798. if (options.removeDirectoryIndex === true) {
  3799. options.removeDirectoryIndex = [/^index\.[a-z]+$/];
  3800. }
  3801. if (Array.isArray(options.removeDirectoryIndex) && options.removeDirectoryIndex.length > 0) {
  3802. let pathComponents = urlObject.pathname.split("/");
  3803. const lastComponent = pathComponents[pathComponents.length - 1];
  3804. if (testParameter(lastComponent, options.removeDirectoryIndex)) {
  3805. pathComponents = pathComponents.slice(0, -1);
  3806. urlObject.pathname = pathComponents.slice(1).join("/") + "/";
  3807. }
  3808. }
  3809. if (urlObject.hostname) {
  3810. urlObject.hostname = urlObject.hostname.replace(/\.$/, "");
  3811. if (options.stripWWW && /^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(urlObject.hostname)) {
  3812. urlObject.hostname = urlObject.hostname.replace(/^www\./, "");
  3813. }
  3814. }
  3815. if (Array.isArray(options.removeQueryParameters)) {
  3816. for (const key of [...urlObject.searchParams.keys()]) {
  3817. if (testParameter(key, options.removeQueryParameters)) {
  3818. urlObject.searchParams.delete(key);
  3819. }
  3820. }
  3821. }
  3822. if (!Array.isArray(options.keepQueryParameters) && options.removeQueryParameters === true) {
  3823. urlObject.search = "";
  3824. }
  3825. if (Array.isArray(options.keepQueryParameters) && options.keepQueryParameters.length > 0) {
  3826. for (const key of [...urlObject.searchParams.keys()]) {
  3827. if (!testParameter(key, options.keepQueryParameters)) {
  3828. urlObject.searchParams.delete(key);
  3829. }
  3830. }
  3831. }
  3832. if (options.sortQueryParameters) {
  3833. urlObject.searchParams.sort();
  3834. try {
  3835. urlObject.search = decodeURIComponent(urlObject.search);
  3836. } catch {
  3837. }
  3838. }
  3839. if (options.removeTrailingSlash) {
  3840. urlObject.pathname = urlObject.pathname.replace(/\/$/, "");
  3841. }
  3842. if (options.removeExplicitPort && urlObject.port) {
  3843. urlObject.port = "";
  3844. }
  3845. const oldUrlString = urlString;
  3846. urlString = urlObject.toString();
  3847. if (!options.removeSingleSlash && urlObject.pathname === "/" && !oldUrlString.endsWith("/") && urlObject.hash === "") {
  3848. urlString = urlString.replace(/\/$/, "");
  3849. }
  3850. if ((options.removeTrailingSlash || urlObject.pathname === "/") && urlObject.hash === "" && options.removeSingleSlash) {
  3851. urlString = urlString.replace(/\/$/, "");
  3852. }
  3853. if (hasRelativeProtocol && !options.normalizeProtocol) {
  3854. urlString = urlString.replace(/^http:\/\//, "//");
  3855. }
  3856. if (options.stripProtocol) {
  3857. urlString = urlString.replace(/^(?:https?:)?\/\//, "");
  3858. }
  3859. return urlString;
  3860. }
  3861. // node_modules/.pnpm/cacheable-request@10.2.7/node_modules/cacheable-request/dist/index.js
  3862. var import_get_stream = __toESM(require_get_stream(), 1);
  3863. var import_http_cache_semantics = __toESM(require_http_cache_semantics(), 1);
  3864. // node_modules/.pnpm/responselike@3.0.0/node_modules/responselike/index.js
  3865. import { Readable as ReadableStream } from "node:stream";
  3866. // node_modules/.pnpm/lowercase-keys@3.0.0/node_modules/lowercase-keys/index.js
  3867. function lowercaseKeys(object) {
  3868. return Object.fromEntries(Object.entries(object).map(([key, value]) => [key.toLowerCase(), value]));
  3869. }
  3870. // node_modules/.pnpm/responselike@3.0.0/node_modules/responselike/index.js
  3871. var Response = class extends ReadableStream {
  3872. statusCode;
  3873. headers;
  3874. body;
  3875. url;
  3876. constructor({ statusCode, headers, body, url }) {
  3877. if (typeof statusCode !== "number") {
  3878. throw new TypeError("Argument `statusCode` should be a number");
  3879. }
  3880. if (typeof headers !== "object") {
  3881. throw new TypeError("Argument `headers` should be an object");
  3882. }
  3883. if (!(body instanceof Uint8Array)) {
  3884. throw new TypeError("Argument `body` should be a buffer");
  3885. }
  3886. if (typeof url !== "string") {
  3887. throw new TypeError("Argument `url` should be a string");
  3888. }
  3889. super({
  3890. read() {
  3891. this.push(body);
  3892. this.push(null);
  3893. }
  3894. });
  3895. this.statusCode = statusCode;
  3896. this.headers = lowercaseKeys(headers);
  3897. this.body = body;
  3898. this.url = url;
  3899. }
  3900. };
  3901. // node_modules/.pnpm/cacheable-request@10.2.7/node_modules/cacheable-request/dist/index.js
  3902. var import_keyv = __toESM(require_src(), 1);
  3903. // node_modules/.pnpm/mimic-response@4.0.0/node_modules/mimic-response/index.js
  3904. var knownProperties = [
  3905. "aborted",
  3906. "complete",
  3907. "headers",
  3908. "httpVersion",
  3909. "httpVersionMinor",
  3910. "httpVersionMajor",
  3911. "method",
  3912. "rawHeaders",
  3913. "rawTrailers",
  3914. "setTimeout",
  3915. "socket",
  3916. "statusCode",
  3917. "statusMessage",
  3918. "trailers",
  3919. "url"
  3920. ];
  3921. function mimicResponse(fromStream, toStream) {
  3922. if (toStream._readableState.autoDestroy) {
  3923. throw new Error("The second stream must have the `autoDestroy` option set to `false`");
  3924. }
  3925. const fromProperties = /* @__PURE__ */ new Set([...Object.keys(fromStream), ...knownProperties]);
  3926. const properties = {};
  3927. for (const property of fromProperties) {
  3928. if (property in toStream) {
  3929. continue;
  3930. }
  3931. properties[property] = {
  3932. get() {
  3933. const value = fromStream[property];
  3934. const isFunction2 = typeof value === "function";
  3935. return isFunction2 ? value.bind(fromStream) : value;
  3936. },
  3937. set(value) {
  3938. fromStream[property] = value;
  3939. },
  3940. enumerable: true,
  3941. configurable: false
  3942. };
  3943. }
  3944. Object.defineProperties(toStream, properties);
  3945. fromStream.once("aborted", () => {
  3946. toStream.destroy();
  3947. toStream.emit("aborted");
  3948. });
  3949. fromStream.once("close", () => {
  3950. if (fromStream.complete) {
  3951. if (toStream.readable) {
  3952. toStream.once("end", () => {
  3953. toStream.emit("close");
  3954. });
  3955. } else {
  3956. toStream.emit("close");
  3957. }
  3958. } else {
  3959. toStream.emit("close");
  3960. }
  3961. });
  3962. return toStream;
  3963. }
  3964. // node_modules/.pnpm/cacheable-request@10.2.7/node_modules/cacheable-request/dist/types.js
  3965. var RequestError2 = class extends Error {
  3966. constructor(error) {
  3967. super(error.message);
  3968. Object.assign(this, error);
  3969. }
  3970. };
  3971. var CacheError2 = class extends Error {
  3972. constructor(error) {
  3973. super(error.message);
  3974. Object.assign(this, error);
  3975. }
  3976. };
  3977. // node_modules/.pnpm/cacheable-request@10.2.7/node_modules/cacheable-request/dist/index.js
  3978. var CacheableRequest = class {
  3979. constructor(cacheRequest, cacheAdapter) {
  3980. this.hooks = /* @__PURE__ */ new Map();
  3981. this.request = () => (options, cb) => {
  3982. let url;
  3983. if (typeof options === "string") {
  3984. url = normalizeUrlObject(urlLib.parse(options));
  3985. options = {};
  3986. } else if (options instanceof urlLib.URL) {
  3987. url = normalizeUrlObject(urlLib.parse(options.toString()));
  3988. options = {};
  3989. } else {
  3990. const [pathname, ...searchParts] = (options.path ?? "").split("?");
  3991. const search = searchParts.length > 0 ? `?${searchParts.join("?")}` : "";
  3992. url = normalizeUrlObject({ ...options, pathname, search });
  3993. }
  3994. options = {
  3995. headers: {},
  3996. method: "GET",
  3997. cache: true,
  3998. strictTtl: false,
  3999. automaticFailover: false,
  4000. ...options,
  4001. ...urlObjectToRequestOptions(url)
  4002. };
  4003. options.headers = Object.fromEntries(entries(options.headers).map(([key2, value]) => [key2.toLowerCase(), value]));
  4004. const ee = new EventEmitter();
  4005. const normalizedUrlString = normalizeUrl(urlLib.format(url), {
  4006. stripWWW: false,
  4007. removeTrailingSlash: false,
  4008. stripAuthentication: false
  4009. });
  4010. let key = `${options.method}:${normalizedUrlString}`;
  4011. if (options.body && options.method !== void 0 && ["POST", "PATCH", "PUT"].includes(options.method)) {
  4012. if (options.body instanceof stream.Readable) {
  4013. options.cache = false;
  4014. } else {
  4015. key += `:${crypto.createHash("md5").update(options.body).digest("hex")}`;
  4016. }
  4017. }
  4018. let revalidate = false;
  4019. let madeRequest = false;
  4020. const makeRequest = (options_) => {
  4021. madeRequest = true;
  4022. let requestErrored = false;
  4023. let requestErrorCallback = () => {
  4024. };
  4025. const requestErrorPromise = new Promise((resolve) => {
  4026. requestErrorCallback = () => {
  4027. if (!requestErrored) {
  4028. requestErrored = true;
  4029. resolve();
  4030. }
  4031. };
  4032. });
  4033. const handler = async (response) => {
  4034. if (revalidate) {
  4035. response.status = response.statusCode;
  4036. const revalidatedPolicy = import_http_cache_semantics.default.fromObject(revalidate.cachePolicy).revalidatedPolicy(options_, response);
  4037. if (!revalidatedPolicy.modified) {
  4038. response.resume();
  4039. await new Promise((resolve) => {
  4040. response.once("end", resolve);
  4041. });
  4042. const headers = convertHeaders(revalidatedPolicy.policy.responseHeaders());
  4043. response = new Response({ statusCode: revalidate.statusCode, headers, body: revalidate.body, url: revalidate.url });
  4044. response.cachePolicy = revalidatedPolicy.policy;
  4045. response.fromCache = true;
  4046. }
  4047. }
  4048. if (!response.fromCache) {
  4049. response.cachePolicy = new import_http_cache_semantics.default(options_, response, options_);
  4050. response.fromCache = false;
  4051. }
  4052. let clonedResponse;
  4053. if (options_.cache && response.cachePolicy.storable()) {
  4054. clonedResponse = cloneResponse(response);
  4055. (async () => {
  4056. try {
  4057. const bodyPromise = import_get_stream.default.buffer(response);
  4058. await Promise.race([
  4059. requestErrorPromise,
  4060. new Promise((resolve) => response.once("end", resolve)),
  4061. new Promise((resolve) => response.once("close", resolve))
  4062. // eslint-disable-line no-promise-executor-return
  4063. ]);
  4064. const body = await bodyPromise;
  4065. let value = {
  4066. url: response.url,
  4067. statusCode: response.fromCache ? revalidate.statusCode : response.statusCode,
  4068. body,
  4069. cachePolicy: response.cachePolicy.toObject()
  4070. };
  4071. let ttl2 = options_.strictTtl ? response.cachePolicy.timeToLive() : void 0;
  4072. if (options_.maxTtl) {
  4073. ttl2 = ttl2 ? Math.min(ttl2, options_.maxTtl) : options_.maxTtl;
  4074. }
  4075. if (this.hooks.size > 0) {
  4076. for (const key_ of this.hooks.keys()) {
  4077. value = await this.runHook(key_, value, response);
  4078. }
  4079. }
  4080. await this.cache.set(key, value, ttl2);
  4081. } catch (error) {
  4082. ee.emit("error", new CacheError2(error));
  4083. }
  4084. })();
  4085. } else if (options_.cache && revalidate) {
  4086. (async () => {
  4087. try {
  4088. await this.cache.delete(key);
  4089. } catch (error) {
  4090. ee.emit("error", new CacheError2(error));
  4091. }
  4092. })();
  4093. }
  4094. ee.emit("response", clonedResponse ?? response);
  4095. if (typeof cb === "function") {
  4096. cb(clonedResponse ?? response);
  4097. }
  4098. };
  4099. try {
  4100. const request_ = this.cacheRequest(options_, handler);
  4101. request_.once("error", requestErrorCallback);
  4102. request_.once("abort", requestErrorCallback);
  4103. request_.once("destroy", requestErrorCallback);
  4104. ee.emit("request", request_);
  4105. } catch (error) {
  4106. ee.emit("error", new RequestError2(error));
  4107. }
  4108. };
  4109. (async () => {
  4110. const get = async (options_) => {
  4111. await Promise.resolve();
  4112. const cacheEntry = options_.cache ? await this.cache.get(key) : void 0;
  4113. if (typeof cacheEntry === "undefined" && !options_.forceRefresh) {
  4114. makeRequest(options_);
  4115. return;
  4116. }
  4117. const policy = import_http_cache_semantics.default.fromObject(cacheEntry.cachePolicy);
  4118. if (policy.satisfiesWithoutRevalidation(options_) && !options_.forceRefresh) {
  4119. const headers = convertHeaders(policy.responseHeaders());
  4120. const response = new Response({ statusCode: cacheEntry.statusCode, headers, body: cacheEntry.body, url: cacheEntry.url });
  4121. response.cachePolicy = policy;
  4122. response.fromCache = true;
  4123. ee.emit("response", response);
  4124. if (typeof cb === "function") {
  4125. cb(response);
  4126. }
  4127. } else if (policy.satisfiesWithoutRevalidation(options_) && Date.now() >= policy.timeToLive() && options_.forceRefresh) {
  4128. await this.cache.delete(key);
  4129. options_.headers = policy.revalidationHeaders(options_);
  4130. makeRequest(options_);
  4131. } else {
  4132. revalidate = cacheEntry;
  4133. options_.headers = policy.revalidationHeaders(options_);
  4134. makeRequest(options_);
  4135. }
  4136. };
  4137. const errorHandler = (error) => ee.emit("error", new CacheError2(error));
  4138. if (this.cache instanceof import_keyv.default) {
  4139. const cachek = this.cache;
  4140. cachek.once("error", errorHandler);
  4141. ee.on("error", () => cachek.removeListener("error", errorHandler));
  4142. ee.on("response", () => cachek.removeListener("error", errorHandler));
  4143. }
  4144. try {
  4145. await get(options);
  4146. } catch (error) {
  4147. if (options.automaticFailover && !madeRequest) {
  4148. makeRequest(options);
  4149. }
  4150. ee.emit("error", new CacheError2(error));
  4151. }
  4152. })();
  4153. return ee;
  4154. };
  4155. this.addHook = (name, fn) => {
  4156. if (!this.hooks.has(name)) {
  4157. this.hooks.set(name, fn);
  4158. }
  4159. };
  4160. this.removeHook = (name) => this.hooks.delete(name);
  4161. this.getHook = (name) => this.hooks.get(name);
  4162. this.runHook = async (name, ...args) => {
  4163. var _a;
  4164. return (_a = this.hooks.get(name)) == null ? void 0 : _a(...args);
  4165. };
  4166. if (cacheAdapter instanceof import_keyv.default) {
  4167. this.cache = cacheAdapter;
  4168. } else if (typeof cacheAdapter === "string") {
  4169. this.cache = new import_keyv.default({
  4170. uri: cacheAdapter,
  4171. namespace: "cacheable-request"
  4172. });
  4173. } else {
  4174. this.cache = new import_keyv.default({
  4175. store: cacheAdapter,
  4176. namespace: "cacheable-request"
  4177. });
  4178. }
  4179. this.request = this.request.bind(this);
  4180. this.cacheRequest = cacheRequest;
  4181. }
  4182. };
  4183. var entries = Object.entries;
  4184. var cloneResponse = (response) => {
  4185. const clone = new PassThroughStream({ autoDestroy: false });
  4186. mimicResponse(response, clone);
  4187. return response.pipe(clone);
  4188. };
  4189. var urlObjectToRequestOptions = (url) => {
  4190. const options = { ...url };
  4191. options.path = `${url.pathname || "/"}${url.search || ""}`;
  4192. delete options.pathname;
  4193. delete options.search;
  4194. return options;
  4195. };
  4196. var normalizeUrlObject = (url) => (
  4197. // If url was parsed by url.parse or new URL:
  4198. // - hostname will be set
  4199. // - host will be hostname[:port]
  4200. // - port will be set if it was explicit in the parsed string
  4201. // Otherwise, url was from request options:
  4202. // - hostname or host may be set
  4203. // - host shall not have port encoded
  4204. {
  4205. protocol: url.protocol,
  4206. auth: url.auth,
  4207. hostname: url.hostname || url.host || "localhost",
  4208. port: url.port,
  4209. pathname: url.pathname,
  4210. search: url.search
  4211. }
  4212. );
  4213. var convertHeaders = (headers) => {
  4214. const result = [];
  4215. for (const name of Object.keys(headers)) {
  4216. result[name.toLowerCase()] = headers[name];
  4217. }
  4218. return result;
  4219. };
  4220. var dist_default2 = CacheableRequest;
  4221. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/index.js
  4222. var import_decompress_response = __toESM(require_decompress_response(), 1);
  4223. var import_get_stream2 = __toESM(require_get_stream(), 1);
  4224. // node_modules/.pnpm/form-data-encoder@2.1.4/node_modules/form-data-encoder/lib/util/isFunction.js
  4225. var isFunction = (value) => typeof value === "function";
  4226. // node_modules/.pnpm/form-data-encoder@2.1.4/node_modules/form-data-encoder/lib/util/getStreamIterator.js
  4227. var isAsyncIterable = (value) => isFunction(value[Symbol.asyncIterator]);
  4228. async function* readStream(readable) {
  4229. const reader = readable.getReader();
  4230. while (true) {
  4231. const { done, value } = await reader.read();
  4232. if (done) {
  4233. break;
  4234. }
  4235. yield value;
  4236. }
  4237. }
  4238. var getStreamIterator = (source) => {
  4239. if (isAsyncIterable(source)) {
  4240. return source;
  4241. }
  4242. if (isFunction(source.getReader)) {
  4243. return readStream(source);
  4244. }
  4245. throw new TypeError("Unsupported data source: Expected either ReadableStream or async iterable.");
  4246. };
  4247. // node_modules/.pnpm/form-data-encoder@2.1.4/node_modules/form-data-encoder/lib/util/createBoundary.js
  4248. var alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
  4249. function createBoundary() {
  4250. let size = 16;
  4251. let res = "";
  4252. while (size--) {
  4253. res += alphabet[Math.random() * alphabet.length << 0];
  4254. }
  4255. return res;
  4256. }
  4257. // node_modules/.pnpm/form-data-encoder@2.1.4/node_modules/form-data-encoder/lib/util/normalizeValue.js
  4258. var normalizeValue = (value) => String(value).replace(/\r|\n/g, (match, i, str) => {
  4259. if (match === "\r" && str[i + 1] !== "\n" || match === "\n" && str[i - 1] !== "\r") {
  4260. return "\r\n";
  4261. }
  4262. return match;
  4263. });
  4264. // node_modules/.pnpm/form-data-encoder@2.1.4/node_modules/form-data-encoder/lib/util/isPlainObject.js
  4265. var getType = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
  4266. function isPlainObject(value) {
  4267. if (getType(value) !== "object") {
  4268. return false;
  4269. }
  4270. const pp = Object.getPrototypeOf(value);
  4271. if (pp === null || pp === void 0) {
  4272. return true;
  4273. }
  4274. const Ctor = pp.constructor && pp.constructor.toString();
  4275. return Ctor === Object.toString();
  4276. }
  4277. // node_modules/.pnpm/form-data-encoder@2.1.4/node_modules/form-data-encoder/lib/util/proxyHeaders.js
  4278. function getProperty(target, prop) {
  4279. if (typeof prop === "string") {
  4280. for (const [name, value] of Object.entries(target)) {
  4281. if (prop.toLowerCase() === name.toLowerCase()) {
  4282. return value;
  4283. }
  4284. }
  4285. }
  4286. return void 0;
  4287. }
  4288. var proxyHeaders = (object) => new Proxy(object, {
  4289. get: (target, prop) => getProperty(target, prop),
  4290. has: (target, prop) => getProperty(target, prop) !== void 0
  4291. });
  4292. // node_modules/.pnpm/form-data-encoder@2.1.4/node_modules/form-data-encoder/lib/util/isFormData.js
  4293. var isFormData = (value) => Boolean(value && isFunction(value.constructor) && value[Symbol.toStringTag] === "FormData" && isFunction(value.append) && isFunction(value.getAll) && isFunction(value.entries) && isFunction(value[Symbol.iterator]));
  4294. // node_modules/.pnpm/form-data-encoder@2.1.4/node_modules/form-data-encoder/lib/util/escapeName.js
  4295. var escapeName = (name) => String(name).replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/"/g, "%22");
  4296. // node_modules/.pnpm/form-data-encoder@2.1.4/node_modules/form-data-encoder/lib/util/isFile.js
  4297. var isFile = (value) => Boolean(value && typeof value === "object" && isFunction(value.constructor) && value[Symbol.toStringTag] === "File" && isFunction(value.stream) && value.name != null);
  4298. // node_modules/.pnpm/form-data-encoder@2.1.4/node_modules/form-data-encoder/lib/FormDataEncoder.js
  4299. var __classPrivateFieldSet = function(receiver, state, value, kind, f) {
  4300. if (kind === "m")
  4301. throw new TypeError("Private method is not writable");
  4302. if (kind === "a" && !f)
  4303. throw new TypeError("Private accessor was defined without a setter");
  4304. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
  4305. throw new TypeError("Cannot write private member to an object whose class did not declare it");
  4306. return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
  4307. };
  4308. var __classPrivateFieldGet = function(receiver, state, kind, f) {
  4309. if (kind === "a" && !f)
  4310. throw new TypeError("Private accessor was defined without a getter");
  4311. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
  4312. throw new TypeError("Cannot read private member from an object whose class did not declare it");
  4313. return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
  4314. };
  4315. var _FormDataEncoder_instances;
  4316. var _FormDataEncoder_CRLF;
  4317. var _FormDataEncoder_CRLF_BYTES;
  4318. var _FormDataEncoder_CRLF_BYTES_LENGTH;
  4319. var _FormDataEncoder_DASHES;
  4320. var _FormDataEncoder_encoder;
  4321. var _FormDataEncoder_footer;
  4322. var _FormDataEncoder_form;
  4323. var _FormDataEncoder_options;
  4324. var _FormDataEncoder_getFieldHeader;
  4325. var _FormDataEncoder_getContentLength;
  4326. var defaultOptions = {
  4327. enableAdditionalHeaders: false
  4328. };
  4329. var readonlyProp = { writable: false, configurable: false };
  4330. var FormDataEncoder = class {
  4331. constructor(form, boundaryOrOptions, options) {
  4332. _FormDataEncoder_instances.add(this);
  4333. _FormDataEncoder_CRLF.set(this, "\r\n");
  4334. _FormDataEncoder_CRLF_BYTES.set(this, void 0);
  4335. _FormDataEncoder_CRLF_BYTES_LENGTH.set(this, void 0);
  4336. _FormDataEncoder_DASHES.set(this, "-".repeat(2));
  4337. _FormDataEncoder_encoder.set(this, new TextEncoder());
  4338. _FormDataEncoder_footer.set(this, void 0);
  4339. _FormDataEncoder_form.set(this, void 0);
  4340. _FormDataEncoder_options.set(this, void 0);
  4341. if (!isFormData(form)) {
  4342. throw new TypeError("Expected first argument to be a FormData instance.");
  4343. }
  4344. let boundary;
  4345. if (isPlainObject(boundaryOrOptions)) {
  4346. options = boundaryOrOptions;
  4347. } else {
  4348. boundary = boundaryOrOptions;
  4349. }
  4350. if (!boundary) {
  4351. boundary = createBoundary();
  4352. }
  4353. if (typeof boundary !== "string") {
  4354. throw new TypeError("Expected boundary argument to be a string.");
  4355. }
  4356. if (options && !isPlainObject(options)) {
  4357. throw new TypeError("Expected options argument to be an object.");
  4358. }
  4359. __classPrivateFieldSet(this, _FormDataEncoder_form, Array.from(form.entries()), "f");
  4360. __classPrivateFieldSet(this, _FormDataEncoder_options, { ...defaultOptions, ...options }, "f");
  4361. __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES, __classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")), "f");
  4362. __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, __classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f").byteLength, "f");
  4363. this.boundary = `form-data-boundary-${boundary}`;
  4364. this.contentType = `multipart/form-data; boundary=${this.boundary}`;
  4365. __classPrivateFieldSet(this, _FormDataEncoder_footer, __classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${__classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`), "f");
  4366. const headers = {
  4367. "Content-Type": this.contentType
  4368. };
  4369. const contentLength = __classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getContentLength).call(this);
  4370. if (contentLength) {
  4371. this.contentLength = contentLength;
  4372. headers["Content-Length"] = contentLength;
  4373. }
  4374. this.headers = proxyHeaders(Object.freeze(headers));
  4375. Object.defineProperties(this, {
  4376. boundary: readonlyProp,
  4377. contentType: readonlyProp,
  4378. contentLength: readonlyProp,
  4379. headers: readonlyProp
  4380. });
  4381. }
  4382. getContentLength() {
  4383. return this.contentLength == null ? void 0 : Number(this.contentLength);
  4384. }
  4385. *values() {
  4386. for (const [name, raw] of __classPrivateFieldGet(this, _FormDataEncoder_form, "f")) {
  4387. const value = isFile(raw) ? raw : __classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(normalizeValue(raw));
  4388. yield __classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value);
  4389. yield value;
  4390. yield __classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f");
  4391. }
  4392. yield __classPrivateFieldGet(this, _FormDataEncoder_footer, "f");
  4393. }
  4394. async *encode() {
  4395. for (const part of this.values()) {
  4396. if (isFile(part)) {
  4397. yield* getStreamIterator(part.stream());
  4398. } else {
  4399. yield part;
  4400. }
  4401. }
  4402. }
  4403. [(_FormDataEncoder_CRLF = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_CRLF_BYTES = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_CRLF_BYTES_LENGTH = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_DASHES = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_encoder = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_footer = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_form = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_options = /* @__PURE__ */ new WeakMap(), _FormDataEncoder_instances = /* @__PURE__ */ new WeakSet(), _FormDataEncoder_getFieldHeader = function _FormDataEncoder_getFieldHeader2(name, value) {
  4404. let header = "";
  4405. header += `${__classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`;
  4406. header += `Content-Disposition: form-data; name="${escapeName(name)}"`;
  4407. if (isFile(value)) {
  4408. header += `; filename="${escapeName(value.name)}"${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`;
  4409. header += `Content-Type: ${value.type || "application/octet-stream"}`;
  4410. }
  4411. const size = isFile(value) ? value.size : value.byteLength;
  4412. if (__classPrivateFieldGet(this, _FormDataEncoder_options, "f").enableAdditionalHeaders === true && size != null && !isNaN(size)) {
  4413. header += `${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}Content-Length: ${isFile(value) ? value.size : value.byteLength}`;
  4414. }
  4415. return __classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${header}${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`);
  4416. }, _FormDataEncoder_getContentLength = function _FormDataEncoder_getContentLength2() {
  4417. let length = 0;
  4418. for (const [name, raw] of __classPrivateFieldGet(this, _FormDataEncoder_form, "f")) {
  4419. const value = isFile(raw) ? raw : __classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(normalizeValue(raw));
  4420. const size = isFile(value) ? value.size : value.byteLength;
  4421. if (size == null || isNaN(size)) {
  4422. return void 0;
  4423. }
  4424. length += __classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value).byteLength;
  4425. length += size;
  4426. length += __classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, "f");
  4427. }
  4428. return String(length + __classPrivateFieldGet(this, _FormDataEncoder_footer, "f").byteLength);
  4429. }, Symbol.iterator)]() {
  4430. return this.values();
  4431. }
  4432. [Symbol.asyncIterator]() {
  4433. return this.encode();
  4434. }
  4435. };
  4436. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/utils/get-body-size.js
  4437. import { Buffer as Buffer2 } from "node:buffer";
  4438. import { promisify } from "node:util";
  4439. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/utils/is-form-data.js
  4440. function isFormData2(body) {
  4441. return dist_default.nodeStream(body) && dist_default.function_(body.getBoundary);
  4442. }
  4443. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/utils/get-body-size.js
  4444. async function getBodySize(body, headers) {
  4445. if (headers && "content-length" in headers) {
  4446. return Number(headers["content-length"]);
  4447. }
  4448. if (!body) {
  4449. return 0;
  4450. }
  4451. if (dist_default.string(body)) {
  4452. return Buffer2.byteLength(body);
  4453. }
  4454. if (dist_default.buffer(body)) {
  4455. return body.length;
  4456. }
  4457. if (isFormData2(body)) {
  4458. return promisify(body.getLength.bind(body))();
  4459. }
  4460. return void 0;
  4461. }
  4462. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/utils/proxy-events.js
  4463. function proxyEvents(from, to, events) {
  4464. const eventFunctions = {};
  4465. for (const event of events) {
  4466. const eventFunction = (...args) => {
  4467. to.emit(event, ...args);
  4468. };
  4469. eventFunctions[event] = eventFunction;
  4470. from.on(event, eventFunction);
  4471. }
  4472. return () => {
  4473. for (const [event, eventFunction] of Object.entries(eventFunctions)) {
  4474. from.off(event, eventFunction);
  4475. }
  4476. };
  4477. }
  4478. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/timed-out.js
  4479. import net from "node:net";
  4480. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/utils/unhandle.js
  4481. function unhandle() {
  4482. const handlers = [];
  4483. return {
  4484. once(origin, event, fn) {
  4485. origin.once(event, fn);
  4486. handlers.push({ origin, event, fn });
  4487. },
  4488. unhandleAll() {
  4489. for (const handler of handlers) {
  4490. const { origin, event, fn } = handler;
  4491. origin.removeListener(event, fn);
  4492. }
  4493. handlers.length = 0;
  4494. }
  4495. };
  4496. }
  4497. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/timed-out.js
  4498. var reentry = Symbol("reentry");
  4499. var noop = () => {
  4500. };
  4501. var TimeoutError2 = class extends Error {
  4502. constructor(threshold, event) {
  4503. super(`Timeout awaiting '${event}' for ${threshold}ms`);
  4504. Object.defineProperty(this, "event", {
  4505. enumerable: true,
  4506. configurable: true,
  4507. writable: true,
  4508. value: event
  4509. });
  4510. Object.defineProperty(this, "code", {
  4511. enumerable: true,
  4512. configurable: true,
  4513. writable: true,
  4514. value: void 0
  4515. });
  4516. this.name = "TimeoutError";
  4517. this.code = "ETIMEDOUT";
  4518. }
  4519. };
  4520. function timedOut(request, delays, options) {
  4521. if (reentry in request) {
  4522. return noop;
  4523. }
  4524. request[reentry] = true;
  4525. const cancelers = [];
  4526. const { once, unhandleAll } = unhandle();
  4527. const addTimeout = (delay2, callback, event) => {
  4528. var _a;
  4529. const timeout = setTimeout(callback, delay2, delay2, event);
  4530. (_a = timeout.unref) == null ? void 0 : _a.call(timeout);
  4531. const cancel = () => {
  4532. clearTimeout(timeout);
  4533. };
  4534. cancelers.push(cancel);
  4535. return cancel;
  4536. };
  4537. const { host, hostname } = options;
  4538. const timeoutHandler = (delay2, event) => {
  4539. request.destroy(new TimeoutError2(delay2, event));
  4540. };
  4541. const cancelTimeouts = () => {
  4542. for (const cancel of cancelers) {
  4543. cancel();
  4544. }
  4545. unhandleAll();
  4546. };
  4547. request.once("error", (error) => {
  4548. cancelTimeouts();
  4549. if (request.listenerCount("error") === 0) {
  4550. throw error;
  4551. }
  4552. });
  4553. if (typeof delays.request !== "undefined") {
  4554. const cancelTimeout = addTimeout(delays.request, timeoutHandler, "request");
  4555. once(request, "response", (response) => {
  4556. once(response, "end", cancelTimeout);
  4557. });
  4558. }
  4559. if (typeof delays.socket !== "undefined") {
  4560. const { socket } = delays;
  4561. const socketTimeoutHandler = () => {
  4562. timeoutHandler(socket, "socket");
  4563. };
  4564. request.setTimeout(socket, socketTimeoutHandler);
  4565. cancelers.push(() => {
  4566. request.removeListener("timeout", socketTimeoutHandler);
  4567. });
  4568. }
  4569. const hasLookup = typeof delays.lookup !== "undefined";
  4570. const hasConnect = typeof delays.connect !== "undefined";
  4571. const hasSecureConnect = typeof delays.secureConnect !== "undefined";
  4572. const hasSend = typeof delays.send !== "undefined";
  4573. if (hasLookup || hasConnect || hasSecureConnect || hasSend) {
  4574. once(request, "socket", (socket) => {
  4575. const { socketPath } = request;
  4576. if (socket.connecting) {
  4577. const hasPath = Boolean(socketPath ?? net.isIP(hostname ?? host ?? "") !== 0);
  4578. if (hasLookup && !hasPath && typeof socket.address().address === "undefined") {
  4579. const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, "lookup");
  4580. once(socket, "lookup", cancelTimeout);
  4581. }
  4582. if (hasConnect) {
  4583. const timeConnect = () => addTimeout(delays.connect, timeoutHandler, "connect");
  4584. if (hasPath) {
  4585. once(socket, "connect", timeConnect());
  4586. } else {
  4587. once(socket, "lookup", (error) => {
  4588. if (error === null) {
  4589. once(socket, "connect", timeConnect());
  4590. }
  4591. });
  4592. }
  4593. }
  4594. if (hasSecureConnect && options.protocol === "https:") {
  4595. once(socket, "connect", () => {
  4596. const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, "secureConnect");
  4597. once(socket, "secureConnect", cancelTimeout);
  4598. });
  4599. }
  4600. }
  4601. if (hasSend) {
  4602. const timeRequest = () => addTimeout(delays.send, timeoutHandler, "send");
  4603. if (socket.connecting) {
  4604. once(socket, "connect", () => {
  4605. once(request, "upload-complete", timeRequest());
  4606. });
  4607. } else {
  4608. once(request, "upload-complete", timeRequest());
  4609. }
  4610. }
  4611. });
  4612. }
  4613. if (typeof delays.response !== "undefined") {
  4614. once(request, "upload-complete", () => {
  4615. const cancelTimeout = addTimeout(delays.response, timeoutHandler, "response");
  4616. once(request, "response", cancelTimeout);
  4617. });
  4618. }
  4619. if (typeof delays.read !== "undefined") {
  4620. once(request, "response", (response) => {
  4621. const cancelTimeout = addTimeout(delays.read, timeoutHandler, "read");
  4622. once(response, "end", cancelTimeout);
  4623. });
  4624. }
  4625. return cancelTimeouts;
  4626. }
  4627. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/utils/url-to-options.js
  4628. function urlToOptions(url) {
  4629. url = url;
  4630. const options = {
  4631. protocol: url.protocol,
  4632. hostname: dist_default.string(url.hostname) && url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname,
  4633. host: url.host,
  4634. hash: url.hash,
  4635. search: url.search,
  4636. pathname: url.pathname,
  4637. href: url.href,
  4638. path: `${url.pathname || ""}${url.search || ""}`
  4639. };
  4640. if (dist_default.string(url.port) && url.port.length > 0) {
  4641. options.port = Number(url.port);
  4642. }
  4643. if (url.username || url.password) {
  4644. options.auth = `${url.username || ""}:${url.password || ""}`;
  4645. }
  4646. return options;
  4647. }
  4648. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/utils/weakable-map.js
  4649. var WeakableMap = class {
  4650. constructor() {
  4651. Object.defineProperty(this, "weakMap", {
  4652. enumerable: true,
  4653. configurable: true,
  4654. writable: true,
  4655. value: void 0
  4656. });
  4657. Object.defineProperty(this, "map", {
  4658. enumerable: true,
  4659. configurable: true,
  4660. writable: true,
  4661. value: void 0
  4662. });
  4663. this.weakMap = /* @__PURE__ */ new WeakMap();
  4664. this.map = /* @__PURE__ */ new Map();
  4665. }
  4666. set(key, value) {
  4667. if (typeof key === "object") {
  4668. this.weakMap.set(key, value);
  4669. } else {
  4670. this.map.set(key, value);
  4671. }
  4672. }
  4673. get(key) {
  4674. if (typeof key === "object") {
  4675. return this.weakMap.get(key);
  4676. }
  4677. return this.map.get(key);
  4678. }
  4679. has(key) {
  4680. if (typeof key === "object") {
  4681. return this.weakMap.has(key);
  4682. }
  4683. return this.map.has(key);
  4684. }
  4685. };
  4686. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/calculate-retry-delay.js
  4687. var calculateRetryDelay = ({ attemptCount, retryOptions, error, retryAfter, computedValue }) => {
  4688. if (error.name === "RetryError") {
  4689. return 1;
  4690. }
  4691. if (attemptCount > retryOptions.limit) {
  4692. return 0;
  4693. }
  4694. const hasMethod = retryOptions.methods.includes(error.options.method);
  4695. const hasErrorCode = retryOptions.errorCodes.includes(error.code);
  4696. const hasStatusCode = error.response && retryOptions.statusCodes.includes(error.response.statusCode);
  4697. if (!hasMethod || !hasErrorCode && !hasStatusCode) {
  4698. return 0;
  4699. }
  4700. if (error.response) {
  4701. if (retryAfter) {
  4702. if (retryAfter > computedValue) {
  4703. return 0;
  4704. }
  4705. return retryAfter;
  4706. }
  4707. if (error.response.statusCode === 413) {
  4708. return 0;
  4709. }
  4710. }
  4711. const noise = Math.random() * retryOptions.noise;
  4712. return Math.min(2 ** (attemptCount - 1) * 1e3, retryOptions.backoffLimit) + noise;
  4713. };
  4714. var calculate_retry_delay_default = calculateRetryDelay;
  4715. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/options.js
  4716. import process2 from "node:process";
  4717. import { promisify as promisify3, inspect } from "node:util";
  4718. import { URL as URL2, URLSearchParams } from "node:url";
  4719. import { checkServerIdentity } from "node:tls";
  4720. import http from "node:http";
  4721. import https from "node:https";
  4722. // node_modules/.pnpm/cacheable-lookup@7.0.0/node_modules/cacheable-lookup/source/index.js
  4723. import {
  4724. V4MAPPED,
  4725. ADDRCONFIG,
  4726. ALL,
  4727. promises as dnsPromises,
  4728. lookup as dnsLookup
  4729. } from "node:dns";
  4730. import { promisify as promisify2 } from "node:util";
  4731. import os from "node:os";
  4732. var { Resolver: AsyncResolver } = dnsPromises;
  4733. var kCacheableLookupCreateConnection = Symbol("cacheableLookupCreateConnection");
  4734. var kCacheableLookupInstance = Symbol("cacheableLookupInstance");
  4735. var kExpires = Symbol("expires");
  4736. var supportsALL = typeof ALL === "number";
  4737. var verifyAgent = (agent2) => {
  4738. if (!(agent2 && typeof agent2.createConnection === "function")) {
  4739. throw new Error("Expected an Agent instance as the first argument");
  4740. }
  4741. };
  4742. var map4to6 = (entries2) => {
  4743. for (const entry of entries2) {
  4744. if (entry.family === 6) {
  4745. continue;
  4746. }
  4747. entry.address = `::ffff:${entry.address}`;
  4748. entry.family = 6;
  4749. }
  4750. };
  4751. var getIfaceInfo = () => {
  4752. let has4 = false;
  4753. let has6 = false;
  4754. for (const device of Object.values(os.networkInterfaces())) {
  4755. for (const iface of device) {
  4756. if (iface.internal) {
  4757. continue;
  4758. }
  4759. if (iface.family === "IPv6") {
  4760. has6 = true;
  4761. } else {
  4762. has4 = true;
  4763. }
  4764. if (has4 && has6) {
  4765. return { has4, has6 };
  4766. }
  4767. }
  4768. }
  4769. return { has4, has6 };
  4770. };
  4771. var isIterable = (map) => {
  4772. return Symbol.iterator in map;
  4773. };
  4774. var ignoreNoResultErrors = (dnsPromise) => {
  4775. return dnsPromise.catch((error) => {
  4776. if (error.code === "ENODATA" || error.code === "ENOTFOUND" || error.code === "ENOENT") {
  4777. return [];
  4778. }
  4779. throw error;
  4780. });
  4781. };
  4782. var ttl = { ttl: true };
  4783. var all = { all: true };
  4784. var all4 = { all: true, family: 4 };
  4785. var all6 = { all: true, family: 6 };
  4786. var CacheableLookup = class {
  4787. constructor({
  4788. cache = /* @__PURE__ */ new Map(),
  4789. maxTtl = Infinity,
  4790. fallbackDuration = 3600,
  4791. errorTtl = 0.15,
  4792. resolver = new AsyncResolver(),
  4793. lookup = dnsLookup
  4794. } = {}) {
  4795. this.maxTtl = maxTtl;
  4796. this.errorTtl = errorTtl;
  4797. this._cache = cache;
  4798. this._resolver = resolver;
  4799. this._dnsLookup = lookup && promisify2(lookup);
  4800. this.stats = {
  4801. cache: 0,
  4802. query: 0
  4803. };
  4804. if (this._resolver instanceof AsyncResolver) {
  4805. this._resolve4 = this._resolver.resolve4.bind(this._resolver);
  4806. this._resolve6 = this._resolver.resolve6.bind(this._resolver);
  4807. } else {
  4808. this._resolve4 = promisify2(this._resolver.resolve4.bind(this._resolver));
  4809. this._resolve6 = promisify2(this._resolver.resolve6.bind(this._resolver));
  4810. }
  4811. this._iface = getIfaceInfo();
  4812. this._pending = {};
  4813. this._nextRemovalTime = false;
  4814. this._hostnamesToFallback = /* @__PURE__ */ new Set();
  4815. this.fallbackDuration = fallbackDuration;
  4816. if (fallbackDuration > 0) {
  4817. const interval = setInterval(() => {
  4818. this._hostnamesToFallback.clear();
  4819. }, fallbackDuration * 1e3);
  4820. if (interval.unref) {
  4821. interval.unref();
  4822. }
  4823. this._fallbackInterval = interval;
  4824. }
  4825. this.lookup = this.lookup.bind(this);
  4826. this.lookupAsync = this.lookupAsync.bind(this);
  4827. }
  4828. set servers(servers) {
  4829. this.clear();
  4830. this._resolver.setServers(servers);
  4831. }
  4832. get servers() {
  4833. return this._resolver.getServers();
  4834. }
  4835. lookup(hostname, options, callback) {
  4836. if (typeof options === "function") {
  4837. callback = options;
  4838. options = {};
  4839. } else if (typeof options === "number") {
  4840. options = {
  4841. family: options
  4842. };
  4843. }
  4844. if (!callback) {
  4845. throw new Error("Callback must be a function.");
  4846. }
  4847. this.lookupAsync(hostname, options).then((result) => {
  4848. if (options.all) {
  4849. callback(null, result);
  4850. } else {
  4851. callback(null, result.address, result.family, result.expires, result.ttl, result.source);
  4852. }
  4853. }, callback);
  4854. }
  4855. async lookupAsync(hostname, options = {}) {
  4856. if (typeof options === "number") {
  4857. options = {
  4858. family: options
  4859. };
  4860. }
  4861. let cached = await this.query(hostname);
  4862. if (options.family === 6) {
  4863. const filtered = cached.filter((entry) => entry.family === 6);
  4864. if (options.hints & V4MAPPED) {
  4865. if (supportsALL && options.hints & ALL || filtered.length === 0) {
  4866. map4to6(cached);
  4867. } else {
  4868. cached = filtered;
  4869. }
  4870. } else {
  4871. cached = filtered;
  4872. }
  4873. } else if (options.family === 4) {
  4874. cached = cached.filter((entry) => entry.family === 4);
  4875. }
  4876. if (options.hints & ADDRCONFIG) {
  4877. const { _iface } = this;
  4878. cached = cached.filter((entry) => entry.family === 6 ? _iface.has6 : _iface.has4);
  4879. }
  4880. if (cached.length === 0) {
  4881. const error = new Error(`cacheableLookup ENOTFOUND ${hostname}`);
  4882. error.code = "ENOTFOUND";
  4883. error.hostname = hostname;
  4884. throw error;
  4885. }
  4886. if (options.all) {
  4887. return cached;
  4888. }
  4889. return cached[0];
  4890. }
  4891. async query(hostname) {
  4892. let source = "cache";
  4893. let cached = await this._cache.get(hostname);
  4894. if (cached) {
  4895. this.stats.cache++;
  4896. }
  4897. if (!cached) {
  4898. const pending = this._pending[hostname];
  4899. if (pending) {
  4900. this.stats.cache++;
  4901. cached = await pending;
  4902. } else {
  4903. source = "query";
  4904. const newPromise = this.queryAndCache(hostname);
  4905. this._pending[hostname] = newPromise;
  4906. this.stats.query++;
  4907. try {
  4908. cached = await newPromise;
  4909. } finally {
  4910. delete this._pending[hostname];
  4911. }
  4912. }
  4913. }
  4914. cached = cached.map((entry) => {
  4915. return { ...entry, source };
  4916. });
  4917. return cached;
  4918. }
  4919. async _resolve(hostname) {
  4920. const [A, AAAA] = await Promise.all([
  4921. ignoreNoResultErrors(this._resolve4(hostname, ttl)),
  4922. ignoreNoResultErrors(this._resolve6(hostname, ttl))
  4923. ]);
  4924. let aTtl = 0;
  4925. let aaaaTtl = 0;
  4926. let cacheTtl = 0;
  4927. const now = Date.now();
  4928. for (const entry of A) {
  4929. entry.family = 4;
  4930. entry.expires = now + entry.ttl * 1e3;
  4931. aTtl = Math.max(aTtl, entry.ttl);
  4932. }
  4933. for (const entry of AAAA) {
  4934. entry.family = 6;
  4935. entry.expires = now + entry.ttl * 1e3;
  4936. aaaaTtl = Math.max(aaaaTtl, entry.ttl);
  4937. }
  4938. if (A.length > 0) {
  4939. if (AAAA.length > 0) {
  4940. cacheTtl = Math.min(aTtl, aaaaTtl);
  4941. } else {
  4942. cacheTtl = aTtl;
  4943. }
  4944. } else {
  4945. cacheTtl = aaaaTtl;
  4946. }
  4947. return {
  4948. entries: [
  4949. ...A,
  4950. ...AAAA
  4951. ],
  4952. cacheTtl
  4953. };
  4954. }
  4955. async _lookup(hostname) {
  4956. try {
  4957. const [A, AAAA] = await Promise.all([
  4958. // Passing {all: true} doesn't return all IPv4 and IPv6 entries.
  4959. // See https://github.com/szmarczak/cacheable-lookup/issues/42
  4960. ignoreNoResultErrors(this._dnsLookup(hostname, all4)),
  4961. ignoreNoResultErrors(this._dnsLookup(hostname, all6))
  4962. ]);
  4963. return {
  4964. entries: [
  4965. ...A,
  4966. ...AAAA
  4967. ],
  4968. cacheTtl: 0
  4969. };
  4970. } catch {
  4971. return {
  4972. entries: [],
  4973. cacheTtl: 0
  4974. };
  4975. }
  4976. }
  4977. async _set(hostname, data, cacheTtl) {
  4978. if (this.maxTtl > 0 && cacheTtl > 0) {
  4979. cacheTtl = Math.min(cacheTtl, this.maxTtl) * 1e3;
  4980. data[kExpires] = Date.now() + cacheTtl;
  4981. try {
  4982. await this._cache.set(hostname, data, cacheTtl);
  4983. } catch (error) {
  4984. this.lookupAsync = async () => {
  4985. const cacheError = new Error("Cache Error. Please recreate the CacheableLookup instance.");
  4986. cacheError.cause = error;
  4987. throw cacheError;
  4988. };
  4989. }
  4990. if (isIterable(this._cache)) {
  4991. this._tick(cacheTtl);
  4992. }
  4993. }
  4994. }
  4995. async queryAndCache(hostname) {
  4996. if (this._hostnamesToFallback.has(hostname)) {
  4997. return this._dnsLookup(hostname, all);
  4998. }
  4999. let query = await this._resolve(hostname);
  5000. if (query.entries.length === 0 && this._dnsLookup) {
  5001. query = await this._lookup(hostname);
  5002. if (query.entries.length !== 0 && this.fallbackDuration > 0) {
  5003. this._hostnamesToFallback.add(hostname);
  5004. }
  5005. }
  5006. const cacheTtl = query.entries.length === 0 ? this.errorTtl : query.cacheTtl;
  5007. await this._set(hostname, query.entries, cacheTtl);
  5008. return query.entries;
  5009. }
  5010. _tick(ms) {
  5011. const nextRemovalTime = this._nextRemovalTime;
  5012. if (!nextRemovalTime || ms < nextRemovalTime) {
  5013. clearTimeout(this._removalTimeout);
  5014. this._nextRemovalTime = ms;
  5015. this._removalTimeout = setTimeout(() => {
  5016. this._nextRemovalTime = false;
  5017. let nextExpiry = Infinity;
  5018. const now = Date.now();
  5019. for (const [hostname, entries2] of this._cache) {
  5020. const expires = entries2[kExpires];
  5021. if (now >= expires) {
  5022. this._cache.delete(hostname);
  5023. } else if (expires < nextExpiry) {
  5024. nextExpiry = expires;
  5025. }
  5026. }
  5027. if (nextExpiry !== Infinity) {
  5028. this._tick(nextExpiry - now);
  5029. }
  5030. }, ms);
  5031. if (this._removalTimeout.unref) {
  5032. this._removalTimeout.unref();
  5033. }
  5034. }
  5035. }
  5036. install(agent2) {
  5037. verifyAgent(agent2);
  5038. if (kCacheableLookupCreateConnection in agent2) {
  5039. throw new Error("CacheableLookup has been already installed");
  5040. }
  5041. agent2[kCacheableLookupCreateConnection] = agent2.createConnection;
  5042. agent2[kCacheableLookupInstance] = this;
  5043. agent2.createConnection = (options, callback) => {
  5044. if (!("lookup" in options)) {
  5045. options.lookup = this.lookup;
  5046. }
  5047. return agent2[kCacheableLookupCreateConnection](options, callback);
  5048. };
  5049. }
  5050. uninstall(agent2) {
  5051. verifyAgent(agent2);
  5052. if (agent2[kCacheableLookupCreateConnection]) {
  5053. if (agent2[kCacheableLookupInstance] !== this) {
  5054. throw new Error("The agent is not owned by this CacheableLookup instance");
  5055. }
  5056. agent2.createConnection = agent2[kCacheableLookupCreateConnection];
  5057. delete agent2[kCacheableLookupCreateConnection];
  5058. delete agent2[kCacheableLookupInstance];
  5059. }
  5060. }
  5061. updateInterfaceInfo() {
  5062. const { _iface } = this;
  5063. this._iface = getIfaceInfo();
  5064. if (_iface.has4 && !this._iface.has4 || _iface.has6 && !this._iface.has6) {
  5065. this._cache.clear();
  5066. }
  5067. }
  5068. clear(hostname) {
  5069. if (hostname) {
  5070. this._cache.delete(hostname);
  5071. return;
  5072. }
  5073. this._cache.clear();
  5074. }
  5075. };
  5076. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/options.js
  5077. var import_http2_wrapper = __toESM(require_source2(), 1);
  5078. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/parse-link-header.js
  5079. function parseLinkHeader(link) {
  5080. const parsed = [];
  5081. const items = link.split(",");
  5082. for (const item of items) {
  5083. const [rawUriReference, ...rawLinkParameters] = item.split(";");
  5084. const trimmedUriReference = rawUriReference.trim();
  5085. if (trimmedUriReference[0] !== "<" || trimmedUriReference[trimmedUriReference.length - 1] !== ">") {
  5086. throw new Error(`Invalid format of the Link header reference: ${trimmedUriReference}`);
  5087. }
  5088. const reference = trimmedUriReference.slice(1, -1);
  5089. const parameters = {};
  5090. if (rawLinkParameters.length === 0) {
  5091. throw new Error(`Unexpected end of Link header parameters: ${rawLinkParameters.join(";")}`);
  5092. }
  5093. for (const rawParameter of rawLinkParameters) {
  5094. const trimmedRawParameter = rawParameter.trim();
  5095. const center = trimmedRawParameter.indexOf("=");
  5096. if (center === -1) {
  5097. throw new Error(`Failed to parse Link header: ${link}`);
  5098. }
  5099. const name = trimmedRawParameter.slice(0, center).trim();
  5100. const value = trimmedRawParameter.slice(center + 1).trim();
  5101. parameters[name] = value;
  5102. }
  5103. parsed.push({
  5104. reference,
  5105. parameters
  5106. });
  5107. }
  5108. return parsed;
  5109. }
  5110. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/options.js
  5111. var [major, minor] = process2.versions.node.split(".").map(Number);
  5112. function validateSearchParameters(searchParameters) {
  5113. for (const key in searchParameters) {
  5114. const value = searchParameters[key];
  5115. assert.any([dist_default.string, dist_default.number, dist_default.boolean, dist_default.null_, dist_default.undefined], value);
  5116. }
  5117. }
  5118. var globalCache = /* @__PURE__ */ new Map();
  5119. var globalDnsCache;
  5120. var getGlobalDnsCache = () => {
  5121. if (globalDnsCache) {
  5122. return globalDnsCache;
  5123. }
  5124. globalDnsCache = new CacheableLookup();
  5125. return globalDnsCache;
  5126. };
  5127. var defaultInternals = {
  5128. request: void 0,
  5129. agent: {
  5130. http: void 0,
  5131. https: void 0,
  5132. http2: void 0
  5133. },
  5134. h2session: void 0,
  5135. decompress: true,
  5136. timeout: {
  5137. connect: void 0,
  5138. lookup: void 0,
  5139. read: void 0,
  5140. request: void 0,
  5141. response: void 0,
  5142. secureConnect: void 0,
  5143. send: void 0,
  5144. socket: void 0
  5145. },
  5146. prefixUrl: "",
  5147. body: void 0,
  5148. form: void 0,
  5149. json: void 0,
  5150. cookieJar: void 0,
  5151. ignoreInvalidCookies: false,
  5152. searchParams: void 0,
  5153. dnsLookup: void 0,
  5154. dnsCache: void 0,
  5155. context: {},
  5156. hooks: {
  5157. init: [],
  5158. beforeRequest: [],
  5159. beforeError: [],
  5160. beforeRedirect: [],
  5161. beforeRetry: [],
  5162. afterResponse: []
  5163. },
  5164. followRedirect: true,
  5165. maxRedirects: 10,
  5166. cache: void 0,
  5167. throwHttpErrors: true,
  5168. username: "",
  5169. password: "",
  5170. http2: false,
  5171. allowGetBody: false,
  5172. headers: {
  5173. "user-agent": "got (https://github.com/sindresorhus/got)"
  5174. },
  5175. methodRewriting: false,
  5176. dnsLookupIpVersion: void 0,
  5177. parseJson: JSON.parse,
  5178. stringifyJson: JSON.stringify,
  5179. retry: {
  5180. limit: 2,
  5181. methods: [
  5182. "GET",
  5183. "PUT",
  5184. "HEAD",
  5185. "DELETE",
  5186. "OPTIONS",
  5187. "TRACE"
  5188. ],
  5189. statusCodes: [
  5190. 408,
  5191. 413,
  5192. 429,
  5193. 500,
  5194. 502,
  5195. 503,
  5196. 504,
  5197. 521,
  5198. 522,
  5199. 524
  5200. ],
  5201. errorCodes: [
  5202. "ETIMEDOUT",
  5203. "ECONNRESET",
  5204. "EADDRINUSE",
  5205. "ECONNREFUSED",
  5206. "EPIPE",
  5207. "ENOTFOUND",
  5208. "ENETUNREACH",
  5209. "EAI_AGAIN"
  5210. ],
  5211. maxRetryAfter: void 0,
  5212. calculateDelay: ({ computedValue }) => computedValue,
  5213. backoffLimit: Number.POSITIVE_INFINITY,
  5214. noise: 100
  5215. },
  5216. localAddress: void 0,
  5217. method: "GET",
  5218. createConnection: void 0,
  5219. cacheOptions: {
  5220. shared: void 0,
  5221. cacheHeuristic: void 0,
  5222. immutableMinTimeToLive: void 0,
  5223. ignoreCargoCult: void 0
  5224. },
  5225. https: {
  5226. alpnProtocols: void 0,
  5227. rejectUnauthorized: void 0,
  5228. checkServerIdentity: void 0,
  5229. certificateAuthority: void 0,
  5230. key: void 0,
  5231. certificate: void 0,
  5232. passphrase: void 0,
  5233. pfx: void 0,
  5234. ciphers: void 0,
  5235. honorCipherOrder: void 0,
  5236. minVersion: void 0,
  5237. maxVersion: void 0,
  5238. signatureAlgorithms: void 0,
  5239. tlsSessionLifetime: void 0,
  5240. dhparam: void 0,
  5241. ecdhCurve: void 0,
  5242. certificateRevocationLists: void 0
  5243. },
  5244. encoding: void 0,
  5245. resolveBodyOnly: false,
  5246. isStream: false,
  5247. responseType: "text",
  5248. url: void 0,
  5249. pagination: {
  5250. transform(response) {
  5251. if (response.request.options.responseType === "json") {
  5252. return response.body;
  5253. }
  5254. return JSON.parse(response.body);
  5255. },
  5256. paginate({ response }) {
  5257. const rawLinkHeader = response.headers.link;
  5258. if (typeof rawLinkHeader !== "string" || rawLinkHeader.trim() === "") {
  5259. return false;
  5260. }
  5261. const parsed = parseLinkHeader(rawLinkHeader);
  5262. const next = parsed.find((entry) => entry.parameters.rel === "next" || entry.parameters.rel === '"next"');
  5263. if (next) {
  5264. return {
  5265. url: new URL2(next.reference, response.url)
  5266. };
  5267. }
  5268. return false;
  5269. },
  5270. filter: () => true,
  5271. shouldContinue: () => true,
  5272. countLimit: Number.POSITIVE_INFINITY,
  5273. backoff: 0,
  5274. requestLimit: 1e4,
  5275. stackAllItems: false
  5276. },
  5277. setHost: true,
  5278. maxHeaderSize: void 0,
  5279. signal: void 0,
  5280. enableUnixSockets: true
  5281. };
  5282. var cloneInternals = (internals) => {
  5283. const { hooks, retry } = internals;
  5284. const result = {
  5285. ...internals,
  5286. context: { ...internals.context },
  5287. cacheOptions: { ...internals.cacheOptions },
  5288. https: { ...internals.https },
  5289. agent: { ...internals.agent },
  5290. headers: { ...internals.headers },
  5291. retry: {
  5292. ...retry,
  5293. errorCodes: [...retry.errorCodes],
  5294. methods: [...retry.methods],
  5295. statusCodes: [...retry.statusCodes]
  5296. },
  5297. timeout: { ...internals.timeout },
  5298. hooks: {
  5299. init: [...hooks.init],
  5300. beforeRequest: [...hooks.beforeRequest],
  5301. beforeError: [...hooks.beforeError],
  5302. beforeRedirect: [...hooks.beforeRedirect],
  5303. beforeRetry: [...hooks.beforeRetry],
  5304. afterResponse: [...hooks.afterResponse]
  5305. },
  5306. searchParams: internals.searchParams ? new URLSearchParams(internals.searchParams) : void 0,
  5307. pagination: { ...internals.pagination }
  5308. };
  5309. if (result.url !== void 0) {
  5310. result.prefixUrl = "";
  5311. }
  5312. return result;
  5313. };
  5314. var cloneRaw = (raw) => {
  5315. const { hooks, retry } = raw;
  5316. const result = { ...raw };
  5317. if (dist_default.object(raw.context)) {
  5318. result.context = { ...raw.context };
  5319. }
  5320. if (dist_default.object(raw.cacheOptions)) {
  5321. result.cacheOptions = { ...raw.cacheOptions };
  5322. }
  5323. if (dist_default.object(raw.https)) {
  5324. result.https = { ...raw.https };
  5325. }
  5326. if (dist_default.object(raw.cacheOptions)) {
  5327. result.cacheOptions = { ...result.cacheOptions };
  5328. }
  5329. if (dist_default.object(raw.agent)) {
  5330. result.agent = { ...raw.agent };
  5331. }
  5332. if (dist_default.object(raw.headers)) {
  5333. result.headers = { ...raw.headers };
  5334. }
  5335. if (dist_default.object(retry)) {
  5336. result.retry = { ...retry };
  5337. if (dist_default.array(retry.errorCodes)) {
  5338. result.retry.errorCodes = [...retry.errorCodes];
  5339. }
  5340. if (dist_default.array(retry.methods)) {
  5341. result.retry.methods = [...retry.methods];
  5342. }
  5343. if (dist_default.array(retry.statusCodes)) {
  5344. result.retry.statusCodes = [...retry.statusCodes];
  5345. }
  5346. }
  5347. if (dist_default.object(raw.timeout)) {
  5348. result.timeout = { ...raw.timeout };
  5349. }
  5350. if (dist_default.object(hooks)) {
  5351. result.hooks = {
  5352. ...hooks
  5353. };
  5354. if (dist_default.array(hooks.init)) {
  5355. result.hooks.init = [...hooks.init];
  5356. }
  5357. if (dist_default.array(hooks.beforeRequest)) {
  5358. result.hooks.beforeRequest = [...hooks.beforeRequest];
  5359. }
  5360. if (dist_default.array(hooks.beforeError)) {
  5361. result.hooks.beforeError = [...hooks.beforeError];
  5362. }
  5363. if (dist_default.array(hooks.beforeRedirect)) {
  5364. result.hooks.beforeRedirect = [...hooks.beforeRedirect];
  5365. }
  5366. if (dist_default.array(hooks.beforeRetry)) {
  5367. result.hooks.beforeRetry = [...hooks.beforeRetry];
  5368. }
  5369. if (dist_default.array(hooks.afterResponse)) {
  5370. result.hooks.afterResponse = [...hooks.afterResponse];
  5371. }
  5372. }
  5373. if (dist_default.object(raw.pagination)) {
  5374. result.pagination = { ...raw.pagination };
  5375. }
  5376. return result;
  5377. };
  5378. var getHttp2TimeoutOption = (internals) => {
  5379. const delays = [internals.timeout.socket, internals.timeout.connect, internals.timeout.lookup, internals.timeout.request, internals.timeout.secureConnect].filter((delay2) => typeof delay2 === "number");
  5380. if (delays.length > 0) {
  5381. return Math.min(...delays);
  5382. }
  5383. return void 0;
  5384. };
  5385. var init = (options, withOptions, self) => {
  5386. var _a;
  5387. const initHooks = (_a = options.hooks) == null ? void 0 : _a.init;
  5388. if (initHooks) {
  5389. for (const hook of initHooks) {
  5390. hook(withOptions, self);
  5391. }
  5392. }
  5393. };
  5394. var Options = class {
  5395. constructor(input, options, defaults2) {
  5396. Object.defineProperty(this, "_unixOptions", {
  5397. enumerable: true,
  5398. configurable: true,
  5399. writable: true,
  5400. value: void 0
  5401. });
  5402. Object.defineProperty(this, "_internals", {
  5403. enumerable: true,
  5404. configurable: true,
  5405. writable: true,
  5406. value: void 0
  5407. });
  5408. Object.defineProperty(this, "_merging", {
  5409. enumerable: true,
  5410. configurable: true,
  5411. writable: true,
  5412. value: void 0
  5413. });
  5414. Object.defineProperty(this, "_init", {
  5415. enumerable: true,
  5416. configurable: true,
  5417. writable: true,
  5418. value: void 0
  5419. });
  5420. assert.any([dist_default.string, dist_default.urlInstance, dist_default.object, dist_default.undefined], input);
  5421. assert.any([dist_default.object, dist_default.undefined], options);
  5422. assert.any([dist_default.object, dist_default.undefined], defaults2);
  5423. if (input instanceof Options || options instanceof Options) {
  5424. throw new TypeError("The defaults must be passed as the third argument");
  5425. }
  5426. this._internals = cloneInternals((defaults2 == null ? void 0 : defaults2._internals) ?? defaults2 ?? defaultInternals);
  5427. this._init = [...(defaults2 == null ? void 0 : defaults2._init) ?? []];
  5428. this._merging = false;
  5429. this._unixOptions = void 0;
  5430. try {
  5431. if (dist_default.plainObject(input)) {
  5432. try {
  5433. this.merge(input);
  5434. this.merge(options);
  5435. } finally {
  5436. this.url = input.url;
  5437. }
  5438. } else {
  5439. try {
  5440. this.merge(options);
  5441. } finally {
  5442. if ((options == null ? void 0 : options.url) !== void 0) {
  5443. if (input === void 0) {
  5444. this.url = options.url;
  5445. } else {
  5446. throw new TypeError("The `url` option is mutually exclusive with the `input` argument");
  5447. }
  5448. } else if (input !== void 0) {
  5449. this.url = input;
  5450. }
  5451. }
  5452. }
  5453. } catch (error) {
  5454. error.options = this;
  5455. throw error;
  5456. }
  5457. }
  5458. merge(options) {
  5459. if (!options) {
  5460. return;
  5461. }
  5462. if (options instanceof Options) {
  5463. for (const init2 of options._init) {
  5464. this.merge(init2);
  5465. }
  5466. return;
  5467. }
  5468. options = cloneRaw(options);
  5469. init(this, options, this);
  5470. init(options, options, this);
  5471. this._merging = true;
  5472. if ("isStream" in options) {
  5473. this.isStream = options.isStream;
  5474. }
  5475. try {
  5476. let push = false;
  5477. for (const key in options) {
  5478. if (key === "mutableDefaults" || key === "handlers") {
  5479. continue;
  5480. }
  5481. if (key === "url") {
  5482. continue;
  5483. }
  5484. if (!(key in this)) {
  5485. throw new Error(`Unexpected option: ${key}`);
  5486. }
  5487. this[key] = options[key];
  5488. push = true;
  5489. }
  5490. if (push) {
  5491. this._init.push(options);
  5492. }
  5493. } finally {
  5494. this._merging = false;
  5495. }
  5496. }
  5497. /**
  5498. Custom request function.
  5499. The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper).
  5500. @default http.request | https.request
  5501. */
  5502. get request() {
  5503. return this._internals.request;
  5504. }
  5505. set request(value) {
  5506. assert.any([dist_default.function_, dist_default.undefined], value);
  5507. this._internals.request = value;
  5508. }
  5509. /**
  5510. An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance.
  5511. This is necessary because a request to one protocol might redirect to another.
  5512. In such a scenario, Got will switch over to the right protocol agent for you.
  5513. If a key is not present, it will default to a global agent.
  5514. @example
  5515. ```
  5516. import got from 'got';
  5517. import HttpAgent from 'agentkeepalive';
  5518. const {HttpsAgent} = HttpAgent;
  5519. await got('https://sindresorhus.com', {
  5520. agent: {
  5521. http: new HttpAgent(),
  5522. https: new HttpsAgent()
  5523. }
  5524. });
  5525. ```
  5526. */
  5527. get agent() {
  5528. return this._internals.agent;
  5529. }
  5530. set agent(value) {
  5531. assert.plainObject(value);
  5532. for (const key in value) {
  5533. if (!(key in this._internals.agent)) {
  5534. throw new TypeError(`Unexpected agent option: ${key}`);
  5535. }
  5536. assert.any([dist_default.object, dist_default.undefined], value[key]);
  5537. }
  5538. if (this._merging) {
  5539. Object.assign(this._internals.agent, value);
  5540. } else {
  5541. this._internals.agent = { ...value };
  5542. }
  5543. }
  5544. get h2session() {
  5545. return this._internals.h2session;
  5546. }
  5547. set h2session(value) {
  5548. this._internals.h2session = value;
  5549. }
  5550. /**
  5551. Decompress the response automatically.
  5552. This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself.
  5553. If this is disabled, a compressed response is returned as a `Buffer`.
  5554. This may be useful if you want to handle decompression yourself or stream the raw compressed data.
  5555. @default true
  5556. */
  5557. get decompress() {
  5558. return this._internals.decompress;
  5559. }
  5560. set decompress(value) {
  5561. assert.boolean(value);
  5562. this._internals.decompress = value;
  5563. }
  5564. /**
  5565. Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property).
  5566. By default, there's no timeout.
  5567. This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
  5568. - `lookup` starts when a socket is assigned and ends when the hostname has been resolved.
  5569. Does not apply when using a Unix domain socket.
  5570. - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected.
  5571. - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
  5572. - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
  5573. - `response` starts when the request has been written to the socket and ends when the response headers are received.
  5574. - `send` starts when the socket is connected and ends with the request has been written to the socket.
  5575. - `request` starts when the request is initiated and ends when the response's end event fires.
  5576. */
  5577. get timeout() {
  5578. return this._internals.timeout;
  5579. }
  5580. set timeout(value) {
  5581. assert.plainObject(value);
  5582. for (const key in value) {
  5583. if (!(key in this._internals.timeout)) {
  5584. throw new Error(`Unexpected timeout option: ${key}`);
  5585. }
  5586. assert.any([dist_default.number, dist_default.undefined], value[key]);
  5587. }
  5588. if (this._merging) {
  5589. Object.assign(this._internals.timeout, value);
  5590. } else {
  5591. this._internals.timeout = { ...value };
  5592. }
  5593. }
  5594. /**
  5595. When specified, `prefixUrl` will be prepended to `url`.
  5596. The prefix can be any valid URL, either relative or absolute.
  5597. A trailing slash `/` is optional - one will be added automatically.
  5598. __Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance.
  5599. __Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion.
  5600. For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`.
  5601. The latter is used by browsers.
  5602. __Tip__: Useful when used with `got.extend()` to create niche-specific Got instances.
  5603. __Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`.
  5604. If the URL doesn't include it anymore, it will throw.
  5605. @example
  5606. ```
  5607. import got from 'got';
  5608. await got('unicorn', {prefixUrl: 'https://cats.com'});
  5609. //=> 'https://cats.com/unicorn'
  5610. const instance = got.extend({
  5611. prefixUrl: 'https://google.com'
  5612. });
  5613. await instance('unicorn', {
  5614. hooks: {
  5615. beforeRequest: [
  5616. options => {
  5617. options.prefixUrl = 'https://cats.com';
  5618. }
  5619. ]
  5620. }
  5621. });
  5622. //=> 'https://cats.com/unicorn'
  5623. ```
  5624. */
  5625. get prefixUrl() {
  5626. return this._internals.prefixUrl;
  5627. }
  5628. set prefixUrl(value) {
  5629. assert.any([dist_default.string, dist_default.urlInstance], value);
  5630. if (value === "") {
  5631. this._internals.prefixUrl = "";
  5632. return;
  5633. }
  5634. value = value.toString();
  5635. if (!value.endsWith("/")) {
  5636. value += "/";
  5637. }
  5638. if (this._internals.prefixUrl && this._internals.url) {
  5639. const { href } = this._internals.url;
  5640. this._internals.url.href = value + href.slice(this._internals.prefixUrl.length);
  5641. }
  5642. this._internals.prefixUrl = value;
  5643. }
  5644. /**
  5645. __Note #1__: The `body` option cannot be used with the `json` or `form` option.
  5646. __Note #2__: If you provide this option, `got.stream()` will be read-only.
  5647. __Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`.
  5648. __Note #4__: This option is not enumerable and will not be merged with the instance defaults.
  5649. The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
  5650. Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`.
  5651. */
  5652. get body() {
  5653. return this._internals.body;
  5654. }
  5655. set body(value) {
  5656. assert.any([dist_default.string, dist_default.buffer, dist_default.nodeStream, dist_default.generator, dist_default.asyncGenerator, isFormData, dist_default.undefined], value);
  5657. if (dist_default.nodeStream(value)) {
  5658. assert.truthy(value.readable);
  5659. }
  5660. if (value !== void 0) {
  5661. assert.undefined(this._internals.form);
  5662. assert.undefined(this._internals.json);
  5663. }
  5664. this._internals.body = value;
  5665. }
  5666. /**
  5667. The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj).
  5668. If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`.
  5669. __Note #1__: If you provide this option, `got.stream()` will be read-only.
  5670. __Note #2__: This option is not enumerable and will not be merged with the instance defaults.
  5671. */
  5672. get form() {
  5673. return this._internals.form;
  5674. }
  5675. set form(value) {
  5676. assert.any([dist_default.plainObject, dist_default.undefined], value);
  5677. if (value !== void 0) {
  5678. assert.undefined(this._internals.body);
  5679. assert.undefined(this._internals.json);
  5680. }
  5681. this._internals.form = value;
  5682. }
  5683. /**
  5684. JSON body. If the `Content-Type` header is not set, it will be set to `application/json`.
  5685. __Note #1__: If you provide this option, `got.stream()` will be read-only.
  5686. __Note #2__: This option is not enumerable and will not be merged with the instance defaults.
  5687. */
  5688. get json() {
  5689. return this._internals.json;
  5690. }
  5691. set json(value) {
  5692. if (value !== void 0) {
  5693. assert.undefined(this._internals.body);
  5694. assert.undefined(this._internals.form);
  5695. }
  5696. this._internals.json = value;
  5697. }
  5698. /**
  5699. The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
  5700. Properties from `options` will override properties in the parsed `url`.
  5701. If no protocol is specified, it will throw a `TypeError`.
  5702. __Note__: The query string is **not** parsed as search params.
  5703. @example
  5704. ```
  5705. await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b
  5706. await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
  5707. // The query string is overridden by `searchParams`
  5708. await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
  5709. ```
  5710. */
  5711. get url() {
  5712. return this._internals.url;
  5713. }
  5714. set url(value) {
  5715. assert.any([dist_default.string, dist_default.urlInstance, dist_default.undefined], value);
  5716. if (value === void 0) {
  5717. this._internals.url = void 0;
  5718. return;
  5719. }
  5720. if (dist_default.string(value) && value.startsWith("/")) {
  5721. throw new Error("`url` must not start with a slash");
  5722. }
  5723. const urlString = `${this.prefixUrl}${value.toString()}`;
  5724. const url = new URL2(urlString);
  5725. this._internals.url = url;
  5726. decodeURI(urlString);
  5727. if (url.protocol === "unix:") {
  5728. url.href = `http://unix${url.pathname}${url.search}`;
  5729. }
  5730. if (url.protocol !== "http:" && url.protocol !== "https:") {
  5731. const error = new Error(`Unsupported protocol: ${url.protocol}`);
  5732. error.code = "ERR_UNSUPPORTED_PROTOCOL";
  5733. throw error;
  5734. }
  5735. if (this._internals.username) {
  5736. url.username = this._internals.username;
  5737. this._internals.username = "";
  5738. }
  5739. if (this._internals.password) {
  5740. url.password = this._internals.password;
  5741. this._internals.password = "";
  5742. }
  5743. if (this._internals.searchParams) {
  5744. url.search = this._internals.searchParams.toString();
  5745. this._internals.searchParams = void 0;
  5746. }
  5747. if (url.hostname === "unix") {
  5748. if (!this._internals.enableUnixSockets) {
  5749. throw new Error("Using UNIX domain sockets but option `enableUnixSockets` is not enabled");
  5750. }
  5751. const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(`${url.pathname}${url.search}`);
  5752. if (matches == null ? void 0 : matches.groups) {
  5753. const { socketPath, path } = matches.groups;
  5754. this._unixOptions = {
  5755. socketPath,
  5756. path,
  5757. host: ""
  5758. };
  5759. } else {
  5760. this._unixOptions = void 0;
  5761. }
  5762. return;
  5763. }
  5764. this._unixOptions = void 0;
  5765. }
  5766. /**
  5767. Cookie support. You don't have to care about parsing or how to store them.
  5768. __Note__: If you provide this option, `options.headers.cookie` will be overridden.
  5769. */
  5770. get cookieJar() {
  5771. return this._internals.cookieJar;
  5772. }
  5773. set cookieJar(value) {
  5774. assert.any([dist_default.object, dist_default.undefined], value);
  5775. if (value === void 0) {
  5776. this._internals.cookieJar = void 0;
  5777. return;
  5778. }
  5779. let { setCookie, getCookieString } = value;
  5780. assert.function_(setCookie);
  5781. assert.function_(getCookieString);
  5782. if (setCookie.length === 4 && getCookieString.length === 0) {
  5783. setCookie = promisify3(setCookie.bind(value));
  5784. getCookieString = promisify3(getCookieString.bind(value));
  5785. this._internals.cookieJar = {
  5786. setCookie,
  5787. getCookieString
  5788. };
  5789. } else {
  5790. this._internals.cookieJar = value;
  5791. }
  5792. }
  5793. /**
  5794. You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
  5795. *Requires Node.js 16 or later.*
  5796. @example
  5797. ```
  5798. import got from 'got';
  5799. const abortController = new AbortController();
  5800. const request = got('https://httpbin.org/anything', {
  5801. signal: abortController.signal
  5802. });
  5803. setTimeout(() => {
  5804. abortController.abort();
  5805. }, 100);
  5806. ```
  5807. */
  5808. // TODO: Replace `any` with `AbortSignal` when targeting Node 16.
  5809. get signal() {
  5810. return this._internals.signal;
  5811. }
  5812. // TODO: Replace `any` with `AbortSignal` when targeting Node 16.
  5813. set signal(value) {
  5814. assert.object(value);
  5815. this._internals.signal = value;
  5816. }
  5817. /**
  5818. Ignore invalid cookies instead of throwing an error.
  5819. Only useful when the `cookieJar` option has been set. Not recommended.
  5820. @default false
  5821. */
  5822. get ignoreInvalidCookies() {
  5823. return this._internals.ignoreInvalidCookies;
  5824. }
  5825. set ignoreInvalidCookies(value) {
  5826. assert.boolean(value);
  5827. this._internals.ignoreInvalidCookies = value;
  5828. }
  5829. /**
  5830. Query string that will be added to the request URL.
  5831. This will override the query string in `url`.
  5832. If you need to pass in an array, you can do it using a `URLSearchParams` instance.
  5833. @example
  5834. ```
  5835. import got from 'got';
  5836. const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]);
  5837. await got('https://example.com', {searchParams});
  5838. console.log(searchParams.toString());
  5839. //=> 'key=a&key=b'
  5840. ```
  5841. */
  5842. get searchParams() {
  5843. if (this._internals.url) {
  5844. return this._internals.url.searchParams;
  5845. }
  5846. if (this._internals.searchParams === void 0) {
  5847. this._internals.searchParams = new URLSearchParams();
  5848. }
  5849. return this._internals.searchParams;
  5850. }
  5851. set searchParams(value) {
  5852. assert.any([dist_default.string, dist_default.object, dist_default.undefined], value);
  5853. const url = this._internals.url;
  5854. if (value === void 0) {
  5855. this._internals.searchParams = void 0;
  5856. if (url) {
  5857. url.search = "";
  5858. }
  5859. return;
  5860. }
  5861. const searchParameters = this.searchParams;
  5862. let updated;
  5863. if (dist_default.string(value)) {
  5864. updated = new URLSearchParams(value);
  5865. } else if (value instanceof URLSearchParams) {
  5866. updated = value;
  5867. } else {
  5868. validateSearchParameters(value);
  5869. updated = new URLSearchParams();
  5870. for (const key in value) {
  5871. const entry = value[key];
  5872. if (entry === null) {
  5873. updated.append(key, "");
  5874. } else if (entry === void 0) {
  5875. searchParameters.delete(key);
  5876. } else {
  5877. updated.append(key, entry);
  5878. }
  5879. }
  5880. }
  5881. if (this._merging) {
  5882. for (const key of updated.keys()) {
  5883. searchParameters.delete(key);
  5884. }
  5885. for (const [key, value2] of updated) {
  5886. searchParameters.append(key, value2);
  5887. }
  5888. } else if (url) {
  5889. url.search = searchParameters.toString();
  5890. } else {
  5891. this._internals.searchParams = searchParameters;
  5892. }
  5893. }
  5894. get searchParameters() {
  5895. throw new Error("The `searchParameters` option does not exist. Use `searchParams` instead.");
  5896. }
  5897. set searchParameters(_value) {
  5898. throw new Error("The `searchParameters` option does not exist. Use `searchParams` instead.");
  5899. }
  5900. get dnsLookup() {
  5901. return this._internals.dnsLookup;
  5902. }
  5903. set dnsLookup(value) {
  5904. assert.any([dist_default.function_, dist_default.undefined], value);
  5905. this._internals.dnsLookup = value;
  5906. }
  5907. /**
  5908. An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups.
  5909. Useful when making lots of requests to different *public* hostnames.
  5910. `CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay.
  5911. __Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc.
  5912. @default false
  5913. */
  5914. get dnsCache() {
  5915. return this._internals.dnsCache;
  5916. }
  5917. set dnsCache(value) {
  5918. assert.any([dist_default.object, dist_default.boolean, dist_default.undefined], value);
  5919. if (value === true) {
  5920. this._internals.dnsCache = getGlobalDnsCache();
  5921. } else if (value === false) {
  5922. this._internals.dnsCache = void 0;
  5923. } else {
  5924. this._internals.dnsCache = value;
  5925. }
  5926. }
  5927. /**
  5928. User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged.
  5929. @example
  5930. ```
  5931. import got from 'got';
  5932. const instance = got.extend({
  5933. hooks: {
  5934. beforeRequest: [
  5935. options => {
  5936. if (!options.context || !options.context.token) {
  5937. throw new Error('Token required');
  5938. }
  5939. options.headers.token = options.context.token;
  5940. }
  5941. ]
  5942. }
  5943. });
  5944. const context = {
  5945. token: 'secret'
  5946. };
  5947. const response = await instance('https://httpbin.org/headers', {context});
  5948. // Let's see the headers
  5949. console.log(response.body);
  5950. ```
  5951. */
  5952. get context() {
  5953. return this._internals.context;
  5954. }
  5955. set context(value) {
  5956. assert.object(value);
  5957. if (this._merging) {
  5958. Object.assign(this._internals.context, value);
  5959. } else {
  5960. this._internals.context = { ...value };
  5961. }
  5962. }
  5963. /**
  5964. Hooks allow modifications during the request lifecycle.
  5965. Hook functions may be async and are run serially.
  5966. */
  5967. get hooks() {
  5968. return this._internals.hooks;
  5969. }
  5970. set hooks(value) {
  5971. assert.object(value);
  5972. for (const knownHookEvent in value) {
  5973. if (!(knownHookEvent in this._internals.hooks)) {
  5974. throw new Error(`Unexpected hook event: ${knownHookEvent}`);
  5975. }
  5976. const typedKnownHookEvent = knownHookEvent;
  5977. const hooks = value[typedKnownHookEvent];
  5978. assert.any([dist_default.array, dist_default.undefined], hooks);
  5979. if (hooks) {
  5980. for (const hook of hooks) {
  5981. assert.function_(hook);
  5982. }
  5983. }
  5984. if (this._merging) {
  5985. if (hooks) {
  5986. this._internals.hooks[typedKnownHookEvent].push(...hooks);
  5987. }
  5988. } else {
  5989. if (!hooks) {
  5990. throw new Error(`Missing hook event: ${knownHookEvent}`);
  5991. }
  5992. this._internals.hooks[knownHookEvent] = [...hooks];
  5993. }
  5994. }
  5995. }
  5996. /**
  5997. Defines if redirect responses should be followed automatically.
  5998. Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`.
  5999. This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`.
  6000. @default true
  6001. */
  6002. get followRedirect() {
  6003. return this._internals.followRedirect;
  6004. }
  6005. set followRedirect(value) {
  6006. assert.boolean(value);
  6007. this._internals.followRedirect = value;
  6008. }
  6009. get followRedirects() {
  6010. throw new TypeError("The `followRedirects` option does not exist. Use `followRedirect` instead.");
  6011. }
  6012. set followRedirects(_value) {
  6013. throw new TypeError("The `followRedirects` option does not exist. Use `followRedirect` instead.");
  6014. }
  6015. /**
  6016. If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown.
  6017. @default 10
  6018. */
  6019. get maxRedirects() {
  6020. return this._internals.maxRedirects;
  6021. }
  6022. set maxRedirects(value) {
  6023. assert.number(value);
  6024. this._internals.maxRedirects = value;
  6025. }
  6026. /**
  6027. A cache adapter instance for storing cached response data.
  6028. @default false
  6029. */
  6030. get cache() {
  6031. return this._internals.cache;
  6032. }
  6033. set cache(value) {
  6034. assert.any([dist_default.object, dist_default.string, dist_default.boolean, dist_default.undefined], value);
  6035. if (value === true) {
  6036. this._internals.cache = globalCache;
  6037. } else if (value === false) {
  6038. this._internals.cache = void 0;
  6039. } else {
  6040. this._internals.cache = value;
  6041. }
  6042. }
  6043. /**
  6044. Determines if a `got.HTTPError` is thrown for unsuccessful responses.
  6045. If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing.
  6046. This may be useful if you are checking for resource availability and are expecting error responses.
  6047. @default true
  6048. */
  6049. get throwHttpErrors() {
  6050. return this._internals.throwHttpErrors;
  6051. }
  6052. set throwHttpErrors(value) {
  6053. assert.boolean(value);
  6054. this._internals.throwHttpErrors = value;
  6055. }
  6056. get username() {
  6057. const url = this._internals.url;
  6058. const value = url ? url.username : this._internals.username;
  6059. return decodeURIComponent(value);
  6060. }
  6061. set username(value) {
  6062. assert.string(value);
  6063. const url = this._internals.url;
  6064. const fixedValue = encodeURIComponent(value);
  6065. if (url) {
  6066. url.username = fixedValue;
  6067. } else {
  6068. this._internals.username = fixedValue;
  6069. }
  6070. }
  6071. get password() {
  6072. const url = this._internals.url;
  6073. const value = url ? url.password : this._internals.password;
  6074. return decodeURIComponent(value);
  6075. }
  6076. set password(value) {
  6077. assert.string(value);
  6078. const url = this._internals.url;
  6079. const fixedValue = encodeURIComponent(value);
  6080. if (url) {
  6081. url.password = fixedValue;
  6082. } else {
  6083. this._internals.password = fixedValue;
  6084. }
  6085. }
  6086. /**
  6087. If set to `true`, Got will additionally accept HTTP2 requests.
  6088. It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol.
  6089. __Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy.
  6090. __Note__: Overriding `options.request` will disable HTTP2 support.
  6091. @default false
  6092. @example
  6093. ```
  6094. import got from 'got';
  6095. const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true});
  6096. console.log(headers.via);
  6097. //=> '2 nghttpx'
  6098. ```
  6099. */
  6100. get http2() {
  6101. return this._internals.http2;
  6102. }
  6103. set http2(value) {
  6104. assert.boolean(value);
  6105. this._internals.http2 = value;
  6106. }
  6107. /**
  6108. Set this to `true` to allow sending body for the `GET` method.
  6109. However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect.
  6110. This option is only meant to interact with non-compliant servers when you have no other choice.
  6111. __Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__.
  6112. @default false
  6113. */
  6114. get allowGetBody() {
  6115. return this._internals.allowGetBody;
  6116. }
  6117. set allowGetBody(value) {
  6118. assert.boolean(value);
  6119. this._internals.allowGetBody = value;
  6120. }
  6121. /**
  6122. Request headers.
  6123. Existing headers will be overwritten. Headers set to `undefined` will be omitted.
  6124. @default {}
  6125. */
  6126. get headers() {
  6127. return this._internals.headers;
  6128. }
  6129. set headers(value) {
  6130. assert.plainObject(value);
  6131. if (this._merging) {
  6132. Object.assign(this._internals.headers, lowercaseKeys(value));
  6133. } else {
  6134. this._internals.headers = lowercaseKeys(value);
  6135. }
  6136. }
  6137. /**
  6138. Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects.
  6139. As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior.
  6140. Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers.
  6141. __Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7).
  6142. @default false
  6143. */
  6144. get methodRewriting() {
  6145. return this._internals.methodRewriting;
  6146. }
  6147. set methodRewriting(value) {
  6148. assert.boolean(value);
  6149. this._internals.methodRewriting = value;
  6150. }
  6151. /**
  6152. Indicates which DNS record family to use.
  6153. Values:
  6154. - `undefined`: IPv4 (if present) or IPv6
  6155. - `4`: Only IPv4
  6156. - `6`: Only IPv6
  6157. @default undefined
  6158. */
  6159. get dnsLookupIpVersion() {
  6160. return this._internals.dnsLookupIpVersion;
  6161. }
  6162. set dnsLookupIpVersion(value) {
  6163. if (value !== void 0 && value !== 4 && value !== 6) {
  6164. throw new TypeError(`Invalid DNS lookup IP version: ${value}`);
  6165. }
  6166. this._internals.dnsLookupIpVersion = value;
  6167. }
  6168. /**
  6169. A function used to parse JSON responses.
  6170. @example
  6171. ```
  6172. import got from 'got';
  6173. import Bourne from '@hapi/bourne';
  6174. const parsed = await got('https://example.com', {
  6175. parseJson: text => Bourne.parse(text)
  6176. }).json();
  6177. console.log(parsed);
  6178. ```
  6179. */
  6180. get parseJson() {
  6181. return this._internals.parseJson;
  6182. }
  6183. set parseJson(value) {
  6184. assert.function_(value);
  6185. this._internals.parseJson = value;
  6186. }
  6187. /**
  6188. A function used to stringify the body of JSON requests.
  6189. @example
  6190. ```
  6191. import got from 'got';
  6192. await got.post('https://example.com', {
  6193. stringifyJson: object => JSON.stringify(object, (key, value) => {
  6194. if (key.startsWith('_')) {
  6195. return;
  6196. }
  6197. return value;
  6198. }),
  6199. json: {
  6200. some: 'payload',
  6201. _ignoreMe: 1234
  6202. }
  6203. });
  6204. ```
  6205. @example
  6206. ```
  6207. import got from 'got';
  6208. await got.post('https://example.com', {
  6209. stringifyJson: object => JSON.stringify(object, (key, value) => {
  6210. if (typeof value === 'number') {
  6211. return value.toString();
  6212. }
  6213. return value;
  6214. }),
  6215. json: {
  6216. some: 'payload',
  6217. number: 1
  6218. }
  6219. });
  6220. ```
  6221. */
  6222. get stringifyJson() {
  6223. return this._internals.stringifyJson;
  6224. }
  6225. set stringifyJson(value) {
  6226. assert.function_(value);
  6227. this._internals.stringifyJson = value;
  6228. }
  6229. /**
  6230. An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
  6231. Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
  6232. The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value.
  6233. The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
  6234. By default, it retries *only* on the specified methods, status codes, and on these network errors:
  6235. - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
  6236. - `ECONNRESET`: Connection was forcibly closed by a peer.
  6237. - `EADDRINUSE`: Could not bind to any free port.
  6238. - `ECONNREFUSED`: Connection was refused by the server.
  6239. - `EPIPE`: The remote side of the stream being written has been closed.
  6240. - `ENOTFOUND`: Couldn't resolve the hostname to an IP address.
  6241. - `ENETUNREACH`: No internet connection.
  6242. - `EAI_AGAIN`: DNS lookup timed out.
  6243. __Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.
  6244. __Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
  6245. */
  6246. get retry() {
  6247. return this._internals.retry;
  6248. }
  6249. set retry(value) {
  6250. assert.plainObject(value);
  6251. assert.any([dist_default.function_, dist_default.undefined], value.calculateDelay);
  6252. assert.any([dist_default.number, dist_default.undefined], value.maxRetryAfter);
  6253. assert.any([dist_default.number, dist_default.undefined], value.limit);
  6254. assert.any([dist_default.array, dist_default.undefined], value.methods);
  6255. assert.any([dist_default.array, dist_default.undefined], value.statusCodes);
  6256. assert.any([dist_default.array, dist_default.undefined], value.errorCodes);
  6257. assert.any([dist_default.number, dist_default.undefined], value.noise);
  6258. if (value.noise && Math.abs(value.noise) > 100) {
  6259. throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`);
  6260. }
  6261. for (const key in value) {
  6262. if (!(key in this._internals.retry)) {
  6263. throw new Error(`Unexpected retry option: ${key}`);
  6264. }
  6265. }
  6266. if (this._merging) {
  6267. Object.assign(this._internals.retry, value);
  6268. } else {
  6269. this._internals.retry = { ...value };
  6270. }
  6271. const { retry } = this._internals;
  6272. retry.methods = [...new Set(retry.methods.map((method) => method.toUpperCase()))];
  6273. retry.statusCodes = [...new Set(retry.statusCodes)];
  6274. retry.errorCodes = [...new Set(retry.errorCodes)];
  6275. }
  6276. /**
  6277. From `http.RequestOptions`.
  6278. The IP address used to send the request from.
  6279. */
  6280. get localAddress() {
  6281. return this._internals.localAddress;
  6282. }
  6283. set localAddress(value) {
  6284. assert.any([dist_default.string, dist_default.undefined], value);
  6285. this._internals.localAddress = value;
  6286. }
  6287. /**
  6288. The HTTP method used to make the request.
  6289. @default 'GET'
  6290. */
  6291. get method() {
  6292. return this._internals.method;
  6293. }
  6294. set method(value) {
  6295. assert.string(value);
  6296. this._internals.method = value.toUpperCase();
  6297. }
  6298. get createConnection() {
  6299. return this._internals.createConnection;
  6300. }
  6301. set createConnection(value) {
  6302. assert.any([dist_default.function_, dist_default.undefined], value);
  6303. this._internals.createConnection = value;
  6304. }
  6305. /**
  6306. From `http-cache-semantics`
  6307. @default {}
  6308. */
  6309. get cacheOptions() {
  6310. return this._internals.cacheOptions;
  6311. }
  6312. set cacheOptions(value) {
  6313. assert.plainObject(value);
  6314. assert.any([dist_default.boolean, dist_default.undefined], value.shared);
  6315. assert.any([dist_default.number, dist_default.undefined], value.cacheHeuristic);
  6316. assert.any([dist_default.number, dist_default.undefined], value.immutableMinTimeToLive);
  6317. assert.any([dist_default.boolean, dist_default.undefined], value.ignoreCargoCult);
  6318. for (const key in value) {
  6319. if (!(key in this._internals.cacheOptions)) {
  6320. throw new Error(`Cache option \`${key}\` does not exist`);
  6321. }
  6322. }
  6323. if (this._merging) {
  6324. Object.assign(this._internals.cacheOptions, value);
  6325. } else {
  6326. this._internals.cacheOptions = { ...value };
  6327. }
  6328. }
  6329. /**
  6330. Options for the advanced HTTPS API.
  6331. */
  6332. get https() {
  6333. return this._internals.https;
  6334. }
  6335. set https(value) {
  6336. assert.plainObject(value);
  6337. assert.any([dist_default.boolean, dist_default.undefined], value.rejectUnauthorized);
  6338. assert.any([dist_default.function_, dist_default.undefined], value.checkServerIdentity);
  6339. assert.any([dist_default.string, dist_default.object, dist_default.array, dist_default.undefined], value.certificateAuthority);
  6340. assert.any([dist_default.string, dist_default.object, dist_default.array, dist_default.undefined], value.key);
  6341. assert.any([dist_default.string, dist_default.object, dist_default.array, dist_default.undefined], value.certificate);
  6342. assert.any([dist_default.string, dist_default.undefined], value.passphrase);
  6343. assert.any([dist_default.string, dist_default.buffer, dist_default.array, dist_default.undefined], value.pfx);
  6344. assert.any([dist_default.array, dist_default.undefined], value.alpnProtocols);
  6345. assert.any([dist_default.string, dist_default.undefined], value.ciphers);
  6346. assert.any([dist_default.string, dist_default.buffer, dist_default.undefined], value.dhparam);
  6347. assert.any([dist_default.string, dist_default.undefined], value.signatureAlgorithms);
  6348. assert.any([dist_default.string, dist_default.undefined], value.minVersion);
  6349. assert.any([dist_default.string, dist_default.undefined], value.maxVersion);
  6350. assert.any([dist_default.boolean, dist_default.undefined], value.honorCipherOrder);
  6351. assert.any([dist_default.number, dist_default.undefined], value.tlsSessionLifetime);
  6352. assert.any([dist_default.string, dist_default.undefined], value.ecdhCurve);
  6353. assert.any([dist_default.string, dist_default.buffer, dist_default.array, dist_default.undefined], value.certificateRevocationLists);
  6354. for (const key in value) {
  6355. if (!(key in this._internals.https)) {
  6356. throw new Error(`HTTPS option \`${key}\` does not exist`);
  6357. }
  6358. }
  6359. if (this._merging) {
  6360. Object.assign(this._internals.https, value);
  6361. } else {
  6362. this._internals.https = { ...value };
  6363. }
  6364. }
  6365. /**
  6366. [Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data.
  6367. To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead.
  6368. Don't set this option to `null`.
  6369. __Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`.
  6370. @default 'utf-8'
  6371. */
  6372. get encoding() {
  6373. return this._internals.encoding;
  6374. }
  6375. set encoding(value) {
  6376. if (value === null) {
  6377. throw new TypeError("To get a Buffer, set `options.responseType` to `buffer` instead");
  6378. }
  6379. assert.any([dist_default.string, dist_default.undefined], value);
  6380. this._internals.encoding = value;
  6381. }
  6382. /**
  6383. When set to `true` the promise will return the Response body instead of the Response object.
  6384. @default false
  6385. */
  6386. get resolveBodyOnly() {
  6387. return this._internals.resolveBodyOnly;
  6388. }
  6389. set resolveBodyOnly(value) {
  6390. assert.boolean(value);
  6391. this._internals.resolveBodyOnly = value;
  6392. }
  6393. /**
  6394. Returns a `Stream` instead of a `Promise`.
  6395. This is equivalent to calling `got.stream(url, options?)`.
  6396. @default false
  6397. */
  6398. get isStream() {
  6399. return this._internals.isStream;
  6400. }
  6401. set isStream(value) {
  6402. assert.boolean(value);
  6403. this._internals.isStream = value;
  6404. }
  6405. /**
  6406. The parsing method.
  6407. The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body.
  6408. It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise.
  6409. __Note__: When using streams, this option is ignored.
  6410. @example
  6411. ```
  6412. const responsePromise = got(url);
  6413. const bufferPromise = responsePromise.buffer();
  6414. const jsonPromise = responsePromise.json();
  6415. const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]);
  6416. // `response` is an instance of Got Response
  6417. // `buffer` is an instance of Buffer
  6418. // `json` is an object
  6419. ```
  6420. @example
  6421. ```
  6422. // This
  6423. const body = await got(url).json();
  6424. // is semantically the same as this
  6425. const body = await got(url, {responseType: 'json', resolveBodyOnly: true});
  6426. ```
  6427. */
  6428. get responseType() {
  6429. return this._internals.responseType;
  6430. }
  6431. set responseType(value) {
  6432. if (value === void 0) {
  6433. this._internals.responseType = "text";
  6434. return;
  6435. }
  6436. if (value !== "text" && value !== "buffer" && value !== "json") {
  6437. throw new Error(`Invalid \`responseType\` option: ${value}`);
  6438. }
  6439. this._internals.responseType = value;
  6440. }
  6441. get pagination() {
  6442. return this._internals.pagination;
  6443. }
  6444. set pagination(value) {
  6445. assert.object(value);
  6446. if (this._merging) {
  6447. Object.assign(this._internals.pagination, value);
  6448. } else {
  6449. this._internals.pagination = value;
  6450. }
  6451. }
  6452. get auth() {
  6453. throw new Error("Parameter `auth` is deprecated. Use `username` / `password` instead.");
  6454. }
  6455. set auth(_value) {
  6456. throw new Error("Parameter `auth` is deprecated. Use `username` / `password` instead.");
  6457. }
  6458. get setHost() {
  6459. return this._internals.setHost;
  6460. }
  6461. set setHost(value) {
  6462. assert.boolean(value);
  6463. this._internals.setHost = value;
  6464. }
  6465. get maxHeaderSize() {
  6466. return this._internals.maxHeaderSize;
  6467. }
  6468. set maxHeaderSize(value) {
  6469. assert.any([dist_default.number, dist_default.undefined], value);
  6470. this._internals.maxHeaderSize = value;
  6471. }
  6472. get enableUnixSockets() {
  6473. return this._internals.enableUnixSockets;
  6474. }
  6475. set enableUnixSockets(value) {
  6476. assert.boolean(value);
  6477. this._internals.enableUnixSockets = value;
  6478. }
  6479. // eslint-disable-next-line @typescript-eslint/naming-convention
  6480. toJSON() {
  6481. return { ...this._internals };
  6482. }
  6483. [Symbol.for("nodejs.util.inspect.custom")](_depth, options) {
  6484. return inspect(this._internals, options);
  6485. }
  6486. createNativeRequestOptions() {
  6487. var _a;
  6488. const internals = this._internals;
  6489. const url = internals.url;
  6490. let agent2;
  6491. if (url.protocol === "https:") {
  6492. agent2 = internals.http2 ? internals.agent : internals.agent.https;
  6493. } else {
  6494. agent2 = internals.agent.http;
  6495. }
  6496. const { https: https2 } = internals;
  6497. let { pfx } = https2;
  6498. if (dist_default.array(pfx) && dist_default.plainObject(pfx[0])) {
  6499. pfx = pfx.map((object) => ({
  6500. buf: object.buffer,
  6501. passphrase: object.passphrase
  6502. }));
  6503. }
  6504. return {
  6505. ...internals.cacheOptions,
  6506. ...this._unixOptions,
  6507. // HTTPS options
  6508. // eslint-disable-next-line @typescript-eslint/naming-convention
  6509. ALPNProtocols: https2.alpnProtocols,
  6510. ca: https2.certificateAuthority,
  6511. cert: https2.certificate,
  6512. key: https2.key,
  6513. passphrase: https2.passphrase,
  6514. pfx: https2.pfx,
  6515. rejectUnauthorized: https2.rejectUnauthorized,
  6516. checkServerIdentity: https2.checkServerIdentity ?? checkServerIdentity,
  6517. ciphers: https2.ciphers,
  6518. honorCipherOrder: https2.honorCipherOrder,
  6519. minVersion: https2.minVersion,
  6520. maxVersion: https2.maxVersion,
  6521. sigalgs: https2.signatureAlgorithms,
  6522. sessionTimeout: https2.tlsSessionLifetime,
  6523. dhparam: https2.dhparam,
  6524. ecdhCurve: https2.ecdhCurve,
  6525. crl: https2.certificateRevocationLists,
  6526. // HTTP options
  6527. lookup: internals.dnsLookup ?? ((_a = internals.dnsCache) == null ? void 0 : _a.lookup),
  6528. family: internals.dnsLookupIpVersion,
  6529. agent: agent2,
  6530. setHost: internals.setHost,
  6531. method: internals.method,
  6532. maxHeaderSize: internals.maxHeaderSize,
  6533. localAddress: internals.localAddress,
  6534. headers: internals.headers,
  6535. createConnection: internals.createConnection,
  6536. timeout: internals.http2 ? getHttp2TimeoutOption(internals) : void 0,
  6537. // HTTP/2 options
  6538. h2session: internals.h2session
  6539. };
  6540. }
  6541. getRequestFunction() {
  6542. const url = this._internals.url;
  6543. const { request } = this._internals;
  6544. if (!request && url) {
  6545. return this.getFallbackRequestFunction();
  6546. }
  6547. return request;
  6548. }
  6549. getFallbackRequestFunction() {
  6550. const url = this._internals.url;
  6551. if (!url) {
  6552. return;
  6553. }
  6554. if (url.protocol === "https:") {
  6555. if (this._internals.http2) {
  6556. if (major < 15 || major === 15 && minor < 10) {
  6557. const error = new Error("To use the `http2` option, install Node.js 15.10.0 or above");
  6558. error.code = "EUNSUPPORTED";
  6559. throw error;
  6560. }
  6561. return import_http2_wrapper.default.auto;
  6562. }
  6563. return https.request;
  6564. }
  6565. return http.request;
  6566. }
  6567. freeze() {
  6568. const options = this._internals;
  6569. Object.freeze(options);
  6570. Object.freeze(options.hooks);
  6571. Object.freeze(options.hooks.afterResponse);
  6572. Object.freeze(options.hooks.beforeError);
  6573. Object.freeze(options.hooks.beforeRedirect);
  6574. Object.freeze(options.hooks.beforeRequest);
  6575. Object.freeze(options.hooks.beforeRetry);
  6576. Object.freeze(options.hooks.init);
  6577. Object.freeze(options.https);
  6578. Object.freeze(options.cacheOptions);
  6579. Object.freeze(options.agent);
  6580. Object.freeze(options.headers);
  6581. Object.freeze(options.timeout);
  6582. Object.freeze(options.retry);
  6583. Object.freeze(options.retry.errorCodes);
  6584. Object.freeze(options.retry.methods);
  6585. Object.freeze(options.retry.statusCodes);
  6586. }
  6587. };
  6588. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/response.js
  6589. var isResponseOk = (response) => {
  6590. const { statusCode } = response;
  6591. const limitStatusCode = response.request.options.followRedirect ? 299 : 399;
  6592. return statusCode >= 200 && statusCode <= limitStatusCode || statusCode === 304;
  6593. };
  6594. var ParseError = class extends RequestError {
  6595. constructor(error, response) {
  6596. const { options } = response.request;
  6597. super(`${error.message} in "${options.url.toString()}"`, error, response.request);
  6598. this.name = "ParseError";
  6599. this.code = "ERR_BODY_PARSE_FAILURE";
  6600. }
  6601. };
  6602. var parseBody = (response, responseType, parseJson, encoding) => {
  6603. const { rawBody } = response;
  6604. try {
  6605. if (responseType === "text") {
  6606. return rawBody.toString(encoding);
  6607. }
  6608. if (responseType === "json") {
  6609. return rawBody.length === 0 ? "" : parseJson(rawBody.toString(encoding));
  6610. }
  6611. if (responseType === "buffer") {
  6612. return rawBody;
  6613. }
  6614. } catch (error) {
  6615. throw new ParseError(error, response);
  6616. }
  6617. throw new ParseError({
  6618. message: `Unknown body type '${responseType}'`,
  6619. name: "Error"
  6620. }, response);
  6621. };
  6622. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/utils/is-client-request.js
  6623. function isClientRequest(clientRequest) {
  6624. return clientRequest.writable && !clientRequest.writableEnded;
  6625. }
  6626. var is_client_request_default = isClientRequest;
  6627. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/utils/is-unix-socket-url.js
  6628. function isUnixSocketURL(url) {
  6629. return url.protocol === "unix:" || url.hostname === "unix";
  6630. }
  6631. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/core/index.js
  6632. var supportsBrotli = dist_default.string(process3.versions.brotli);
  6633. var methodsWithoutBody = /* @__PURE__ */ new Set(["GET", "HEAD"]);
  6634. var cacheableStore = new WeakableMap();
  6635. var redirectCodes = /* @__PURE__ */ new Set([300, 301, 302, 303, 304, 307, 308]);
  6636. var proxiedRequestEvents = [
  6637. "socket",
  6638. "connect",
  6639. "continue",
  6640. "information",
  6641. "upgrade"
  6642. ];
  6643. var noop2 = () => {
  6644. };
  6645. var Request = class extends Duplex {
  6646. constructor(url, options, defaults2) {
  6647. super({
  6648. // Don't destroy immediately, as the error may be emitted on unsuccessful retry
  6649. autoDestroy: false,
  6650. // It needs to be zero because we're just proxying the data to another stream
  6651. highWaterMark: 0
  6652. });
  6653. Object.defineProperty(this, "constructor", {
  6654. enumerable: true,
  6655. configurable: true,
  6656. writable: true,
  6657. value: void 0
  6658. });
  6659. Object.defineProperty(this, "_noPipe", {
  6660. enumerable: true,
  6661. configurable: true,
  6662. writable: true,
  6663. value: void 0
  6664. });
  6665. Object.defineProperty(this, "options", {
  6666. enumerable: true,
  6667. configurable: true,
  6668. writable: true,
  6669. value: void 0
  6670. });
  6671. Object.defineProperty(this, "response", {
  6672. enumerable: true,
  6673. configurable: true,
  6674. writable: true,
  6675. value: void 0
  6676. });
  6677. Object.defineProperty(this, "requestUrl", {
  6678. enumerable: true,
  6679. configurable: true,
  6680. writable: true,
  6681. value: void 0
  6682. });
  6683. Object.defineProperty(this, "redirectUrls", {
  6684. enumerable: true,
  6685. configurable: true,
  6686. writable: true,
  6687. value: void 0
  6688. });
  6689. Object.defineProperty(this, "retryCount", {
  6690. enumerable: true,
  6691. configurable: true,
  6692. writable: true,
  6693. value: void 0
  6694. });
  6695. Object.defineProperty(this, "_stopRetry", {
  6696. enumerable: true,
  6697. configurable: true,
  6698. writable: true,
  6699. value: void 0
  6700. });
  6701. Object.defineProperty(this, "_downloadedSize", {
  6702. enumerable: true,
  6703. configurable: true,
  6704. writable: true,
  6705. value: void 0
  6706. });
  6707. Object.defineProperty(this, "_uploadedSize", {
  6708. enumerable: true,
  6709. configurable: true,
  6710. writable: true,
  6711. value: void 0
  6712. });
  6713. Object.defineProperty(this, "_stopReading", {
  6714. enumerable: true,
  6715. configurable: true,
  6716. writable: true,
  6717. value: void 0
  6718. });
  6719. Object.defineProperty(this, "_pipedServerResponses", {
  6720. enumerable: true,
  6721. configurable: true,
  6722. writable: true,
  6723. value: void 0
  6724. });
  6725. Object.defineProperty(this, "_request", {
  6726. enumerable: true,
  6727. configurable: true,
  6728. writable: true,
  6729. value: void 0
  6730. });
  6731. Object.defineProperty(this, "_responseSize", {
  6732. enumerable: true,
  6733. configurable: true,
  6734. writable: true,
  6735. value: void 0
  6736. });
  6737. Object.defineProperty(this, "_bodySize", {
  6738. enumerable: true,
  6739. configurable: true,
  6740. writable: true,
  6741. value: void 0
  6742. });
  6743. Object.defineProperty(this, "_unproxyEvents", {
  6744. enumerable: true,
  6745. configurable: true,
  6746. writable: true,
  6747. value: void 0
  6748. });
  6749. Object.defineProperty(this, "_isFromCache", {
  6750. enumerable: true,
  6751. configurable: true,
  6752. writable: true,
  6753. value: void 0
  6754. });
  6755. Object.defineProperty(this, "_cannotHaveBody", {
  6756. enumerable: true,
  6757. configurable: true,
  6758. writable: true,
  6759. value: void 0
  6760. });
  6761. Object.defineProperty(this, "_triggerRead", {
  6762. enumerable: true,
  6763. configurable: true,
  6764. writable: true,
  6765. value: void 0
  6766. });
  6767. Object.defineProperty(this, "_cancelTimeouts", {
  6768. enumerable: true,
  6769. configurable: true,
  6770. writable: true,
  6771. value: void 0
  6772. });
  6773. Object.defineProperty(this, "_removeListeners", {
  6774. enumerable: true,
  6775. configurable: true,
  6776. writable: true,
  6777. value: void 0
  6778. });
  6779. Object.defineProperty(this, "_nativeResponse", {
  6780. enumerable: true,
  6781. configurable: true,
  6782. writable: true,
  6783. value: void 0
  6784. });
  6785. Object.defineProperty(this, "_flushed", {
  6786. enumerable: true,
  6787. configurable: true,
  6788. writable: true,
  6789. value: void 0
  6790. });
  6791. Object.defineProperty(this, "_aborted", {
  6792. enumerable: true,
  6793. configurable: true,
  6794. writable: true,
  6795. value: void 0
  6796. });
  6797. Object.defineProperty(this, "_requestInitialized", {
  6798. enumerable: true,
  6799. configurable: true,
  6800. writable: true,
  6801. value: void 0
  6802. });
  6803. this._downloadedSize = 0;
  6804. this._uploadedSize = 0;
  6805. this._stopReading = false;
  6806. this._pipedServerResponses = /* @__PURE__ */ new Set();
  6807. this._cannotHaveBody = false;
  6808. this._unproxyEvents = noop2;
  6809. this._triggerRead = false;
  6810. this._cancelTimeouts = noop2;
  6811. this._removeListeners = noop2;
  6812. this._jobs = [];
  6813. this._flushed = false;
  6814. this._requestInitialized = false;
  6815. this._aborted = false;
  6816. this.redirectUrls = [];
  6817. this.retryCount = 0;
  6818. this._stopRetry = noop2;
  6819. this.on("pipe", (source) => {
  6820. if (source.headers) {
  6821. Object.assign(this.options.headers, source.headers);
  6822. }
  6823. });
  6824. this.on("newListener", (event) => {
  6825. if (event === "retry" && this.listenerCount("retry") > 0) {
  6826. throw new Error("A retry listener has been attached already.");
  6827. }
  6828. });
  6829. try {
  6830. this.options = new Options(url, options, defaults2);
  6831. if (!this.options.url) {
  6832. if (this.options.prefixUrl === "") {
  6833. throw new TypeError("Missing `url` property");
  6834. }
  6835. this.options.url = "";
  6836. }
  6837. this.requestUrl = this.options.url;
  6838. } catch (error) {
  6839. const { options: options2 } = error;
  6840. if (options2) {
  6841. this.options = options2;
  6842. }
  6843. this.flush = async () => {
  6844. this.flush = async () => {
  6845. };
  6846. this.destroy(error);
  6847. };
  6848. return;
  6849. }
  6850. const { body } = this.options;
  6851. if (dist_default.nodeStream(body)) {
  6852. body.once("error", (error) => {
  6853. if (this._flushed) {
  6854. this._beforeError(new UploadError(error, this));
  6855. } else {
  6856. this.flush = async () => {
  6857. this.flush = async () => {
  6858. };
  6859. this._beforeError(new UploadError(error, this));
  6860. };
  6861. }
  6862. });
  6863. }
  6864. if (this.options.signal) {
  6865. const abort = () => {
  6866. this.destroy(new AbortError(this));
  6867. };
  6868. if (this.options.signal.aborted) {
  6869. abort();
  6870. } else {
  6871. this.options.signal.addEventListener("abort", abort);
  6872. this._removeListeners = () => {
  6873. this.options.signal.removeEventListener("abort", abort);
  6874. };
  6875. }
  6876. }
  6877. }
  6878. async flush() {
  6879. var _a;
  6880. if (this._flushed) {
  6881. return;
  6882. }
  6883. this._flushed = true;
  6884. try {
  6885. await this._finalizeBody();
  6886. if (this.destroyed) {
  6887. return;
  6888. }
  6889. await this._makeRequest();
  6890. if (this.destroyed) {
  6891. (_a = this._request) == null ? void 0 : _a.destroy();
  6892. return;
  6893. }
  6894. for (const job of this._jobs) {
  6895. job();
  6896. }
  6897. this._jobs.length = 0;
  6898. this._requestInitialized = true;
  6899. } catch (error) {
  6900. this._beforeError(error);
  6901. }
  6902. }
  6903. _beforeError(error) {
  6904. if (this._stopReading) {
  6905. return;
  6906. }
  6907. const { response, options } = this;
  6908. const attemptCount = this.retryCount + (error.name === "RetryError" ? 0 : 1);
  6909. this._stopReading = true;
  6910. if (!(error instanceof RequestError)) {
  6911. error = new RequestError(error.message, error, this);
  6912. }
  6913. const typedError = error;
  6914. void (async () => {
  6915. var _a, _b;
  6916. if ((response == null ? void 0 : response.readable) && !response.rawBody && !((_b = (_a = this._request) == null ? void 0 : _a.socket) == null ? void 0 : _b.destroyed)) {
  6917. response.setEncoding(this.readableEncoding);
  6918. const success = await this._setRawBody(response);
  6919. if (success) {
  6920. response.body = response.rawBody.toString();
  6921. }
  6922. }
  6923. if (this.listenerCount("retry") !== 0) {
  6924. let backoff;
  6925. try {
  6926. let retryAfter;
  6927. if (response && "retry-after" in response.headers) {
  6928. retryAfter = Number(response.headers["retry-after"]);
  6929. if (Number.isNaN(retryAfter)) {
  6930. retryAfter = Date.parse(response.headers["retry-after"]) - Date.now();
  6931. if (retryAfter <= 0) {
  6932. retryAfter = 1;
  6933. }
  6934. } else {
  6935. retryAfter *= 1e3;
  6936. }
  6937. }
  6938. const retryOptions = options.retry;
  6939. backoff = await retryOptions.calculateDelay({
  6940. attemptCount,
  6941. retryOptions,
  6942. error: typedError,
  6943. retryAfter,
  6944. computedValue: calculate_retry_delay_default({
  6945. attemptCount,
  6946. retryOptions,
  6947. error: typedError,
  6948. retryAfter,
  6949. computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY
  6950. })
  6951. });
  6952. } catch (error_) {
  6953. void this._error(new RequestError(error_.message, error_, this));
  6954. return;
  6955. }
  6956. if (backoff) {
  6957. await new Promise((resolve) => {
  6958. const timeout = setTimeout(resolve, backoff);
  6959. this._stopRetry = () => {
  6960. clearTimeout(timeout);
  6961. resolve();
  6962. };
  6963. });
  6964. if (this.destroyed) {
  6965. return;
  6966. }
  6967. try {
  6968. for (const hook of this.options.hooks.beforeRetry) {
  6969. await hook(typedError, this.retryCount + 1);
  6970. }
  6971. } catch (error_) {
  6972. void this._error(new RequestError(error_.message, error, this));
  6973. return;
  6974. }
  6975. if (this.destroyed) {
  6976. return;
  6977. }
  6978. this.destroy();
  6979. this.emit("retry", this.retryCount + 1, error, (updatedOptions) => {
  6980. const request = new Request(options.url, updatedOptions, options);
  6981. request.retryCount = this.retryCount + 1;
  6982. process3.nextTick(() => {
  6983. void request.flush();
  6984. });
  6985. return request;
  6986. });
  6987. return;
  6988. }
  6989. }
  6990. void this._error(typedError);
  6991. })();
  6992. }
  6993. _read() {
  6994. this._triggerRead = true;
  6995. const { response } = this;
  6996. if (response && !this._stopReading) {
  6997. if (response.readableLength) {
  6998. this._triggerRead = false;
  6999. }
  7000. let data;
  7001. while ((data = response.read()) !== null) {
  7002. this._downloadedSize += data.length;
  7003. const progress = this.downloadProgress;
  7004. if (progress.percent < 1) {
  7005. this.emit("downloadProgress", progress);
  7006. }
  7007. this.push(data);
  7008. }
  7009. }
  7010. }
  7011. _write(chunk, encoding, callback) {
  7012. const write = () => {
  7013. this._writeRequest(chunk, encoding, callback);
  7014. };
  7015. if (this._requestInitialized) {
  7016. write();
  7017. } else {
  7018. this._jobs.push(write);
  7019. }
  7020. }
  7021. _final(callback) {
  7022. const endRequest = () => {
  7023. if (!this._request || this._request.destroyed) {
  7024. callback();
  7025. return;
  7026. }
  7027. this._request.end((error) => {
  7028. var _a;
  7029. if ((_a = this._request._writableState) == null ? void 0 : _a.errored) {
  7030. return;
  7031. }
  7032. if (!error) {
  7033. this._bodySize = this._uploadedSize;
  7034. this.emit("uploadProgress", this.uploadProgress);
  7035. this._request.emit("upload-complete");
  7036. }
  7037. callback(error);
  7038. });
  7039. };
  7040. if (this._requestInitialized) {
  7041. endRequest();
  7042. } else {
  7043. this._jobs.push(endRequest);
  7044. }
  7045. }
  7046. _destroy(error, callback) {
  7047. this._stopReading = true;
  7048. this.flush = async () => {
  7049. };
  7050. this._stopRetry();
  7051. this._cancelTimeouts();
  7052. this._removeListeners();
  7053. if (this.options) {
  7054. const { body } = this.options;
  7055. if (dist_default.nodeStream(body)) {
  7056. body.destroy();
  7057. }
  7058. }
  7059. if (this._request) {
  7060. this._request.destroy();
  7061. }
  7062. if (error !== null && !dist_default.undefined(error) && !(error instanceof RequestError)) {
  7063. error = new RequestError(error.message, error, this);
  7064. }
  7065. callback(error);
  7066. }
  7067. pipe(destination, options) {
  7068. if (destination instanceof ServerResponse) {
  7069. this._pipedServerResponses.add(destination);
  7070. }
  7071. return super.pipe(destination, options);
  7072. }
  7073. unpipe(destination) {
  7074. if (destination instanceof ServerResponse) {
  7075. this._pipedServerResponses.delete(destination);
  7076. }
  7077. super.unpipe(destination);
  7078. return this;
  7079. }
  7080. async _finalizeBody() {
  7081. const { options } = this;
  7082. const { headers } = options;
  7083. const isForm = !dist_default.undefined(options.form);
  7084. const isJSON = !dist_default.undefined(options.json);
  7085. const isBody = !dist_default.undefined(options.body);
  7086. const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === "GET" && options.allowGetBody);
  7087. this._cannotHaveBody = cannotHaveBody;
  7088. if (isForm || isJSON || isBody) {
  7089. if (cannotHaveBody) {
  7090. throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
  7091. }
  7092. const noContentType = !dist_default.string(headers["content-type"]);
  7093. if (isBody) {
  7094. if (isFormData(options.body)) {
  7095. const encoder = new FormDataEncoder(options.body);
  7096. if (noContentType) {
  7097. headers["content-type"] = encoder.headers["Content-Type"];
  7098. }
  7099. if ("Content-Length" in encoder.headers) {
  7100. headers["content-length"] = encoder.headers["Content-Length"];
  7101. }
  7102. options.body = encoder.encode();
  7103. }
  7104. if (isFormData2(options.body) && noContentType) {
  7105. headers["content-type"] = `multipart/form-data; boundary=${options.body.getBoundary()}`;
  7106. }
  7107. } else if (isForm) {
  7108. if (noContentType) {
  7109. headers["content-type"] = "application/x-www-form-urlencoded";
  7110. }
  7111. const { form } = options;
  7112. options.form = void 0;
  7113. options.body = new URLSearchParams2(form).toString();
  7114. } else {
  7115. if (noContentType) {
  7116. headers["content-type"] = "application/json";
  7117. }
  7118. const { json } = options;
  7119. options.json = void 0;
  7120. options.body = options.stringifyJson(json);
  7121. }
  7122. const uploadBodySize = await getBodySize(options.body, options.headers);
  7123. if (dist_default.undefined(headers["content-length"]) && dist_default.undefined(headers["transfer-encoding"]) && !cannotHaveBody && !dist_default.undefined(uploadBodySize)) {
  7124. headers["content-length"] = String(uploadBodySize);
  7125. }
  7126. }
  7127. if (options.responseType === "json" && !("accept" in options.headers)) {
  7128. options.headers.accept = "application/json";
  7129. }
  7130. this._bodySize = Number(headers["content-length"]) || void 0;
  7131. }
  7132. async _onResponseBase(response) {
  7133. if (this.isAborted) {
  7134. return;
  7135. }
  7136. const { options } = this;
  7137. const { url } = options;
  7138. this._nativeResponse = response;
  7139. if (options.decompress) {
  7140. response = (0, import_decompress_response.default)(response);
  7141. }
  7142. const statusCode = response.statusCode;
  7143. const typedResponse = response;
  7144. typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http2.STATUS_CODES[statusCode];
  7145. typedResponse.url = options.url.toString();
  7146. typedResponse.requestUrl = this.requestUrl;
  7147. typedResponse.redirectUrls = this.redirectUrls;
  7148. typedResponse.request = this;
  7149. typedResponse.isFromCache = this._nativeResponse.fromCache ?? false;
  7150. typedResponse.ip = this.ip;
  7151. typedResponse.retryCount = this.retryCount;
  7152. typedResponse.ok = isResponseOk(typedResponse);
  7153. this._isFromCache = typedResponse.isFromCache;
  7154. this._responseSize = Number(response.headers["content-length"]) || void 0;
  7155. this.response = typedResponse;
  7156. response.once("end", () => {
  7157. this._responseSize = this._downloadedSize;
  7158. this.emit("downloadProgress", this.downloadProgress);
  7159. });
  7160. response.once("error", (error) => {
  7161. this._aborted = true;
  7162. response.destroy();
  7163. this._beforeError(new ReadError(error, this));
  7164. });
  7165. response.once("aborted", () => {
  7166. this._aborted = true;
  7167. this._beforeError(new ReadError({
  7168. name: "Error",
  7169. message: "The server aborted pending request",
  7170. code: "ECONNRESET"
  7171. }, this));
  7172. });
  7173. this.emit("downloadProgress", this.downloadProgress);
  7174. const rawCookies = response.headers["set-cookie"];
  7175. if (dist_default.object(options.cookieJar) && rawCookies) {
  7176. let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString()));
  7177. if (options.ignoreInvalidCookies) {
  7178. promises = promises.map(async (promise) => {
  7179. try {
  7180. await promise;
  7181. } catch {
  7182. }
  7183. });
  7184. }
  7185. try {
  7186. await Promise.all(promises);
  7187. } catch (error) {
  7188. this._beforeError(error);
  7189. return;
  7190. }
  7191. }
  7192. if (this.isAborted) {
  7193. return;
  7194. }
  7195. if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {
  7196. response.resume();
  7197. this._cancelTimeouts();
  7198. this._unproxyEvents();
  7199. if (this.redirectUrls.length >= options.maxRedirects) {
  7200. this._beforeError(new MaxRedirectsError(this));
  7201. return;
  7202. }
  7203. this._request = void 0;
  7204. const updatedOptions = new Options(void 0, void 0, this.options);
  7205. const serverRequestedGet = statusCode === 303 && updatedOptions.method !== "GET" && updatedOptions.method !== "HEAD";
  7206. const canRewrite = statusCode !== 307 && statusCode !== 308;
  7207. const userRequestedGet = updatedOptions.methodRewriting && canRewrite;
  7208. if (serverRequestedGet || userRequestedGet) {
  7209. updatedOptions.method = "GET";
  7210. updatedOptions.body = void 0;
  7211. updatedOptions.json = void 0;
  7212. updatedOptions.form = void 0;
  7213. delete updatedOptions.headers["content-length"];
  7214. }
  7215. try {
  7216. const redirectBuffer = Buffer3.from(response.headers.location, "binary").toString();
  7217. const redirectUrl = new URL3(redirectBuffer, url);
  7218. if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) {
  7219. this._beforeError(new RequestError("Cannot redirect to UNIX socket", {}, this));
  7220. return;
  7221. }
  7222. if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) {
  7223. if ("host" in updatedOptions.headers) {
  7224. delete updatedOptions.headers.host;
  7225. }
  7226. if ("cookie" in updatedOptions.headers) {
  7227. delete updatedOptions.headers.cookie;
  7228. }
  7229. if ("authorization" in updatedOptions.headers) {
  7230. delete updatedOptions.headers.authorization;
  7231. }
  7232. if (updatedOptions.username || updatedOptions.password) {
  7233. updatedOptions.username = "";
  7234. updatedOptions.password = "";
  7235. }
  7236. } else {
  7237. redirectUrl.username = updatedOptions.username;
  7238. redirectUrl.password = updatedOptions.password;
  7239. }
  7240. this.redirectUrls.push(redirectUrl);
  7241. updatedOptions.prefixUrl = "";
  7242. updatedOptions.url = redirectUrl;
  7243. for (const hook of updatedOptions.hooks.beforeRedirect) {
  7244. await hook(updatedOptions, typedResponse);
  7245. }
  7246. this.emit("redirect", updatedOptions, typedResponse);
  7247. this.options = updatedOptions;
  7248. await this._makeRequest();
  7249. } catch (error) {
  7250. this._beforeError(error);
  7251. return;
  7252. }
  7253. return;
  7254. }
  7255. if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) {
  7256. this._beforeError(new HTTPError(typedResponse));
  7257. return;
  7258. }
  7259. response.on("readable", () => {
  7260. if (this._triggerRead) {
  7261. this._read();
  7262. }
  7263. });
  7264. this.on("resume", () => {
  7265. response.resume();
  7266. });
  7267. this.on("pause", () => {
  7268. response.pause();
  7269. });
  7270. response.once("end", () => {
  7271. this.push(null);
  7272. });
  7273. if (this._noPipe) {
  7274. const success = await this._setRawBody();
  7275. if (success) {
  7276. this.emit("response", response);
  7277. }
  7278. return;
  7279. }
  7280. this.emit("response", response);
  7281. for (const destination of this._pipedServerResponses) {
  7282. if (destination.headersSent) {
  7283. continue;
  7284. }
  7285. for (const key in response.headers) {
  7286. const isAllowed = options.decompress ? key !== "content-encoding" : true;
  7287. const value = response.headers[key];
  7288. if (isAllowed) {
  7289. destination.setHeader(key, value);
  7290. }
  7291. }
  7292. destination.statusCode = statusCode;
  7293. }
  7294. }
  7295. async _setRawBody(from = this) {
  7296. if (from.readableEnded) {
  7297. return false;
  7298. }
  7299. try {
  7300. const rawBody = await (0, import_get_stream2.buffer)(from);
  7301. if (!this.isAborted) {
  7302. this.response.rawBody = rawBody;
  7303. return true;
  7304. }
  7305. } catch {
  7306. }
  7307. return false;
  7308. }
  7309. async _onResponse(response) {
  7310. try {
  7311. await this._onResponseBase(response);
  7312. } catch (error) {
  7313. this._beforeError(error);
  7314. }
  7315. }
  7316. _onRequest(request) {
  7317. const { options } = this;
  7318. const { timeout, url } = options;
  7319. source_default(request);
  7320. if (this.options.http2) {
  7321. request.setTimeout(0);
  7322. }
  7323. this._cancelTimeouts = timedOut(request, timeout, url);
  7324. const responseEventName = options.cache ? "cacheableResponse" : "response";
  7325. request.once(responseEventName, (response) => {
  7326. void this._onResponse(response);
  7327. });
  7328. request.once("error", (error) => {
  7329. this._aborted = true;
  7330. request.destroy();
  7331. error = error instanceof TimeoutError2 ? new TimeoutError(error, this.timings, this) : new RequestError(error.message, error, this);
  7332. this._beforeError(error);
  7333. });
  7334. this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents);
  7335. this._request = request;
  7336. this.emit("uploadProgress", this.uploadProgress);
  7337. this._sendBody();
  7338. this.emit("request", request);
  7339. }
  7340. async _asyncWrite(chunk) {
  7341. return new Promise((resolve, reject) => {
  7342. super.write(chunk, (error) => {
  7343. if (error) {
  7344. reject(error);
  7345. return;
  7346. }
  7347. resolve();
  7348. });
  7349. });
  7350. }
  7351. _sendBody() {
  7352. const { body } = this.options;
  7353. const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this;
  7354. if (dist_default.nodeStream(body)) {
  7355. body.pipe(currentRequest);
  7356. } else if (dist_default.generator(body) || dist_default.asyncGenerator(body)) {
  7357. (async () => {
  7358. try {
  7359. for await (const chunk of body) {
  7360. await this._asyncWrite(chunk);
  7361. }
  7362. super.end();
  7363. } catch (error) {
  7364. this._beforeError(error);
  7365. }
  7366. })();
  7367. } else if (!dist_default.undefined(body)) {
  7368. this._writeRequest(body, void 0, () => {
  7369. });
  7370. currentRequest.end();
  7371. } else if (this._cannotHaveBody || this._noPipe) {
  7372. currentRequest.end();
  7373. }
  7374. }
  7375. _prepareCache(cache) {
  7376. if (!cacheableStore.has(cache)) {
  7377. const cacheableRequest = new dist_default2((requestOptions, handler) => {
  7378. const result = requestOptions._request(requestOptions, handler);
  7379. if (dist_default.promise(result)) {
  7380. result.once = (event, handler2) => {
  7381. if (event === "error") {
  7382. (async () => {
  7383. try {
  7384. await result;
  7385. } catch (error) {
  7386. handler2(error);
  7387. }
  7388. })();
  7389. } else if (event === "abort") {
  7390. (async () => {
  7391. try {
  7392. const request = await result;
  7393. request.once("abort", handler2);
  7394. } catch {
  7395. }
  7396. })();
  7397. } else {
  7398. throw new Error(`Unknown HTTP2 promise event: ${event}`);
  7399. }
  7400. return result;
  7401. };
  7402. }
  7403. return result;
  7404. }, cache);
  7405. cacheableStore.set(cache, cacheableRequest.request());
  7406. }
  7407. }
  7408. async _createCacheableRequest(url, options) {
  7409. return new Promise((resolve, reject) => {
  7410. Object.assign(options, urlToOptions(url));
  7411. let request;
  7412. const cacheRequest = cacheableStore.get(options.cache)(options, async (response) => {
  7413. response._readableState.autoDestroy = false;
  7414. if (request) {
  7415. const fix = () => {
  7416. if (response.req) {
  7417. response.complete = response.req.res.complete;
  7418. }
  7419. };
  7420. response.prependOnceListener("end", fix);
  7421. fix();
  7422. (await request).emit("cacheableResponse", response);
  7423. }
  7424. resolve(response);
  7425. });
  7426. cacheRequest.once("error", reject);
  7427. cacheRequest.once("request", async (requestOrPromise) => {
  7428. request = requestOrPromise;
  7429. resolve(request);
  7430. });
  7431. });
  7432. }
  7433. async _makeRequest() {
  7434. const { options } = this;
  7435. const { headers, username, password } = options;
  7436. const cookieJar = options.cookieJar;
  7437. for (const key in headers) {
  7438. if (dist_default.undefined(headers[key])) {
  7439. delete headers[key];
  7440. } else if (dist_default.null_(headers[key])) {
  7441. throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`);
  7442. }
  7443. }
  7444. if (options.decompress && dist_default.undefined(headers["accept-encoding"])) {
  7445. headers["accept-encoding"] = supportsBrotli ? "gzip, deflate, br" : "gzip, deflate";
  7446. }
  7447. if (username || password) {
  7448. const credentials = Buffer3.from(`${username}:${password}`).toString("base64");
  7449. headers.authorization = `Basic ${credentials}`;
  7450. }
  7451. if (cookieJar) {
  7452. const cookieString = await cookieJar.getCookieString(options.url.toString());
  7453. if (dist_default.nonEmptyString(cookieString)) {
  7454. headers.cookie = cookieString;
  7455. }
  7456. }
  7457. options.prefixUrl = "";
  7458. let request;
  7459. for (const hook of options.hooks.beforeRequest) {
  7460. const result = await hook(options);
  7461. if (!dist_default.undefined(result)) {
  7462. request = () => result;
  7463. break;
  7464. }
  7465. }
  7466. if (!request) {
  7467. request = options.getRequestFunction();
  7468. }
  7469. const url = options.url;
  7470. this._requestOptions = options.createNativeRequestOptions();
  7471. if (options.cache) {
  7472. this._requestOptions._request = request;
  7473. this._requestOptions.cache = options.cache;
  7474. this._requestOptions.body = options.body;
  7475. this._prepareCache(options.cache);
  7476. }
  7477. const fn = options.cache ? this._createCacheableRequest : request;
  7478. try {
  7479. let requestOrResponse = fn(url, this._requestOptions);
  7480. if (dist_default.promise(requestOrResponse)) {
  7481. requestOrResponse = await requestOrResponse;
  7482. }
  7483. if (dist_default.undefined(requestOrResponse)) {
  7484. requestOrResponse = options.getFallbackRequestFunction()(url, this._requestOptions);
  7485. if (dist_default.promise(requestOrResponse)) {
  7486. requestOrResponse = await requestOrResponse;
  7487. }
  7488. }
  7489. if (is_client_request_default(requestOrResponse)) {
  7490. this._onRequest(requestOrResponse);
  7491. } else if (this.writable) {
  7492. this.once("finish", () => {
  7493. void this._onResponse(requestOrResponse);
  7494. });
  7495. this._sendBody();
  7496. } else {
  7497. void this._onResponse(requestOrResponse);
  7498. }
  7499. } catch (error) {
  7500. if (error instanceof CacheError2) {
  7501. throw new CacheError(error, this);
  7502. }
  7503. throw error;
  7504. }
  7505. }
  7506. async _error(error) {
  7507. try {
  7508. if (error instanceof HTTPError && !this.options.throwHttpErrors) {
  7509. } else {
  7510. for (const hook of this.options.hooks.beforeError) {
  7511. error = await hook(error);
  7512. }
  7513. }
  7514. } catch (error_) {
  7515. error = new RequestError(error_.message, error_, this);
  7516. }
  7517. this.destroy(error);
  7518. }
  7519. _writeRequest(chunk, encoding, callback) {
  7520. if (!this._request || this._request.destroyed) {
  7521. return;
  7522. }
  7523. this._request.write(chunk, encoding, (error) => {
  7524. if (!error && !this._request.destroyed) {
  7525. this._uploadedSize += Buffer3.byteLength(chunk, encoding);
  7526. const progress = this.uploadProgress;
  7527. if (progress.percent < 1) {
  7528. this.emit("uploadProgress", progress);
  7529. }
  7530. }
  7531. callback(error);
  7532. });
  7533. }
  7534. /**
  7535. The remote IP address.
  7536. */
  7537. get ip() {
  7538. var _a;
  7539. return (_a = this.socket) == null ? void 0 : _a.remoteAddress;
  7540. }
  7541. /**
  7542. Indicates whether the request has been aborted or not.
  7543. */
  7544. get isAborted() {
  7545. return this._aborted;
  7546. }
  7547. get socket() {
  7548. var _a;
  7549. return ((_a = this._request) == null ? void 0 : _a.socket) ?? void 0;
  7550. }
  7551. /**
  7552. Progress event for downloading (receiving a response).
  7553. */
  7554. get downloadProgress() {
  7555. let percent;
  7556. if (this._responseSize) {
  7557. percent = this._downloadedSize / this._responseSize;
  7558. } else if (this._responseSize === this._downloadedSize) {
  7559. percent = 1;
  7560. } else {
  7561. percent = 0;
  7562. }
  7563. return {
  7564. percent,
  7565. transferred: this._downloadedSize,
  7566. total: this._responseSize
  7567. };
  7568. }
  7569. /**
  7570. Progress event for uploading (sending a request).
  7571. */
  7572. get uploadProgress() {
  7573. let percent;
  7574. if (this._bodySize) {
  7575. percent = this._uploadedSize / this._bodySize;
  7576. } else if (this._bodySize === this._uploadedSize) {
  7577. percent = 1;
  7578. } else {
  7579. percent = 0;
  7580. }
  7581. return {
  7582. percent,
  7583. transferred: this._uploadedSize,
  7584. total: this._bodySize
  7585. };
  7586. }
  7587. /**
  7588. The object contains the following properties:
  7589. - `start` - Time when the request started.
  7590. - `socket` - Time when a socket was assigned to the request.
  7591. - `lookup` - Time when the DNS lookup finished.
  7592. - `connect` - Time when the socket successfully connected.
  7593. - `secureConnect` - Time when the socket securely connected.
  7594. - `upload` - Time when the request finished uploading.
  7595. - `response` - Time when the request fired `response` event.
  7596. - `end` - Time when the response fired `end` event.
  7597. - `error` - Time when the request fired `error` event.
  7598. - `abort` - Time when the request fired `abort` event.
  7599. - `phases`
  7600. - `wait` - `timings.socket - timings.start`
  7601. - `dns` - `timings.lookup - timings.socket`
  7602. - `tcp` - `timings.connect - timings.lookup`
  7603. - `tls` - `timings.secureConnect - timings.connect`
  7604. - `request` - `timings.upload - (timings.secureConnect || timings.connect)`
  7605. - `firstByte` - `timings.response - timings.upload`
  7606. - `download` - `timings.end - timings.response`
  7607. - `total` - `(timings.end || timings.error || timings.abort) - timings.start`
  7608. If something has not been measured yet, it will be `undefined`.
  7609. __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
  7610. */
  7611. get timings() {
  7612. var _a;
  7613. return (_a = this._request) == null ? void 0 : _a.timings;
  7614. }
  7615. /**
  7616. Whether the response was retrieved from the cache.
  7617. */
  7618. get isFromCache() {
  7619. return this._isFromCache;
  7620. }
  7621. get reusedSocket() {
  7622. var _a;
  7623. return (_a = this._request) == null ? void 0 : _a.reusedSocket;
  7624. }
  7625. };
  7626. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/as-promise/types.js
  7627. var CancelError2 = class extends RequestError {
  7628. constructor(request) {
  7629. super("Promise was canceled", {}, request);
  7630. this.name = "CancelError";
  7631. this.code = "ERR_CANCELED";
  7632. }
  7633. /**
  7634. Whether the promise is canceled.
  7635. */
  7636. get isCanceled() {
  7637. return true;
  7638. }
  7639. };
  7640. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/as-promise/index.js
  7641. var proxiedRequestEvents2 = [
  7642. "request",
  7643. "response",
  7644. "redirect",
  7645. "uploadProgress",
  7646. "downloadProgress"
  7647. ];
  7648. function asPromise(firstRequest) {
  7649. let globalRequest;
  7650. let globalResponse;
  7651. let normalizedOptions;
  7652. const emitter = new EventEmitter2();
  7653. const promise = new PCancelable((resolve, reject, onCancel) => {
  7654. onCancel(() => {
  7655. globalRequest.destroy();
  7656. });
  7657. onCancel.shouldReject = false;
  7658. onCancel(() => {
  7659. reject(new CancelError2(globalRequest));
  7660. });
  7661. const makeRequest = (retryCount) => {
  7662. var _a;
  7663. onCancel(() => {
  7664. });
  7665. const request = firstRequest ?? new Request(void 0, void 0, normalizedOptions);
  7666. request.retryCount = retryCount;
  7667. request._noPipe = true;
  7668. globalRequest = request;
  7669. request.once("response", async (response) => {
  7670. const contentEncoding = (response.headers["content-encoding"] ?? "").toLowerCase();
  7671. const isCompressed = contentEncoding === "gzip" || contentEncoding === "deflate" || contentEncoding === "br";
  7672. const { options } = request;
  7673. if (isCompressed && !options.decompress) {
  7674. response.body = response.rawBody;
  7675. } else {
  7676. try {
  7677. response.body = parseBody(response, options.responseType, options.parseJson, options.encoding);
  7678. } catch (error) {
  7679. response.body = response.rawBody.toString();
  7680. if (isResponseOk(response)) {
  7681. request._beforeError(error);
  7682. return;
  7683. }
  7684. }
  7685. }
  7686. try {
  7687. const hooks = options.hooks.afterResponse;
  7688. for (const [index, hook] of hooks.entries()) {
  7689. response = await hook(response, async (updatedOptions) => {
  7690. options.merge(updatedOptions);
  7691. options.prefixUrl = "";
  7692. if (updatedOptions.url) {
  7693. options.url = updatedOptions.url;
  7694. }
  7695. options.hooks.afterResponse = options.hooks.afterResponse.slice(0, index);
  7696. throw new RetryError(request);
  7697. });
  7698. if (!(dist_default.object(response) && dist_default.number(response.statusCode) && !dist_default.nullOrUndefined(response.body))) {
  7699. throw new TypeError("The `afterResponse` hook returned an invalid value");
  7700. }
  7701. }
  7702. } catch (error) {
  7703. request._beforeError(error);
  7704. return;
  7705. }
  7706. globalResponse = response;
  7707. if (!isResponseOk(response)) {
  7708. request._beforeError(new HTTPError(response));
  7709. return;
  7710. }
  7711. request.destroy();
  7712. resolve(request.options.resolveBodyOnly ? response.body : response);
  7713. });
  7714. const onError = (error) => {
  7715. if (promise.isCanceled) {
  7716. return;
  7717. }
  7718. const { options } = request;
  7719. if (error instanceof HTTPError && !options.throwHttpErrors) {
  7720. const { response } = error;
  7721. request.destroy();
  7722. resolve(request.options.resolveBodyOnly ? response.body : response);
  7723. return;
  7724. }
  7725. reject(error);
  7726. };
  7727. request.once("error", onError);
  7728. const previousBody = (_a = request.options) == null ? void 0 : _a.body;
  7729. request.once("retry", (newRetryCount, error) => {
  7730. firstRequest = void 0;
  7731. const newBody = request.options.body;
  7732. if (previousBody === newBody && dist_default.nodeStream(newBody)) {
  7733. error.message = "Cannot retry with consumed body stream";
  7734. onError(error);
  7735. return;
  7736. }
  7737. normalizedOptions = request.options;
  7738. makeRequest(newRetryCount);
  7739. });
  7740. proxyEvents(request, emitter, proxiedRequestEvents2);
  7741. if (dist_default.undefined(firstRequest)) {
  7742. void request.flush();
  7743. }
  7744. };
  7745. makeRequest(0);
  7746. });
  7747. promise.on = (event, fn) => {
  7748. emitter.on(event, fn);
  7749. return promise;
  7750. };
  7751. promise.off = (event, fn) => {
  7752. emitter.off(event, fn);
  7753. return promise;
  7754. };
  7755. const shortcut = (responseType) => {
  7756. const newPromise = (async () => {
  7757. await promise;
  7758. const { options } = globalResponse.request;
  7759. return parseBody(globalResponse, responseType, options.parseJson, options.encoding);
  7760. })();
  7761. Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));
  7762. return newPromise;
  7763. };
  7764. promise.json = () => {
  7765. if (globalRequest.options) {
  7766. const { headers } = globalRequest.options;
  7767. if (!globalRequest.writableFinished && !("accept" in headers)) {
  7768. headers.accept = "application/json";
  7769. }
  7770. }
  7771. return shortcut("json");
  7772. };
  7773. promise.buffer = () => shortcut("buffer");
  7774. promise.text = () => shortcut("text");
  7775. return promise;
  7776. }
  7777. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/create.js
  7778. var delay = async (ms) => new Promise((resolve) => {
  7779. setTimeout(resolve, ms);
  7780. });
  7781. var isGotInstance = (value) => dist_default.function_(value);
  7782. var aliases = [
  7783. "get",
  7784. "post",
  7785. "put",
  7786. "patch",
  7787. "head",
  7788. "delete"
  7789. ];
  7790. var create = (defaults2) => {
  7791. defaults2 = {
  7792. options: new Options(void 0, void 0, defaults2.options),
  7793. handlers: [...defaults2.handlers],
  7794. mutableDefaults: defaults2.mutableDefaults
  7795. };
  7796. Object.defineProperty(defaults2, "mutableDefaults", {
  7797. enumerable: true,
  7798. configurable: false,
  7799. writable: false
  7800. });
  7801. const got2 = (url, options, defaultOptions2 = defaults2.options) => {
  7802. const request = new Request(url, options, defaultOptions2);
  7803. let promise;
  7804. const lastHandler = (normalized) => {
  7805. request.options = normalized;
  7806. request._noPipe = !normalized.isStream;
  7807. void request.flush();
  7808. if (normalized.isStream) {
  7809. return request;
  7810. }
  7811. if (!promise) {
  7812. promise = asPromise(request);
  7813. }
  7814. return promise;
  7815. };
  7816. let iteration = 0;
  7817. const iterateHandlers = (newOptions) => {
  7818. const handler = defaults2.handlers[iteration++] ?? lastHandler;
  7819. const result = handler(newOptions, iterateHandlers);
  7820. if (dist_default.promise(result) && !request.options.isStream) {
  7821. if (!promise) {
  7822. promise = asPromise(request);
  7823. }
  7824. if (result !== promise) {
  7825. const descriptors = Object.getOwnPropertyDescriptors(promise);
  7826. for (const key in descriptors) {
  7827. if (key in result) {
  7828. delete descriptors[key];
  7829. }
  7830. }
  7831. Object.defineProperties(result, descriptors);
  7832. result.cancel = promise.cancel;
  7833. }
  7834. }
  7835. return result;
  7836. };
  7837. return iterateHandlers(request.options);
  7838. };
  7839. got2.extend = (...instancesOrOptions) => {
  7840. const options = new Options(void 0, void 0, defaults2.options);
  7841. const handlers = [...defaults2.handlers];
  7842. let mutableDefaults;
  7843. for (const value of instancesOrOptions) {
  7844. if (isGotInstance(value)) {
  7845. options.merge(value.defaults.options);
  7846. handlers.push(...value.defaults.handlers);
  7847. mutableDefaults = value.defaults.mutableDefaults;
  7848. } else {
  7849. options.merge(value);
  7850. if (value.handlers) {
  7851. handlers.push(...value.handlers);
  7852. }
  7853. mutableDefaults = value.mutableDefaults;
  7854. }
  7855. }
  7856. return create({
  7857. options,
  7858. handlers,
  7859. mutableDefaults: Boolean(mutableDefaults)
  7860. });
  7861. };
  7862. const paginateEach = async function* (url, options) {
  7863. let normalizedOptions = new Options(url, options, defaults2.options);
  7864. normalizedOptions.resolveBodyOnly = false;
  7865. const { pagination } = normalizedOptions;
  7866. assert.function_(pagination.transform);
  7867. assert.function_(pagination.shouldContinue);
  7868. assert.function_(pagination.filter);
  7869. assert.function_(pagination.paginate);
  7870. assert.number(pagination.countLimit);
  7871. assert.number(pagination.requestLimit);
  7872. assert.number(pagination.backoff);
  7873. const allItems = [];
  7874. let { countLimit } = pagination;
  7875. let numberOfRequests = 0;
  7876. while (numberOfRequests < pagination.requestLimit) {
  7877. if (numberOfRequests !== 0) {
  7878. await delay(pagination.backoff);
  7879. }
  7880. const response = await got2(void 0, void 0, normalizedOptions);
  7881. const parsed = await pagination.transform(response);
  7882. const currentItems = [];
  7883. assert.array(parsed);
  7884. for (const item of parsed) {
  7885. if (pagination.filter({ item, currentItems, allItems })) {
  7886. if (!pagination.shouldContinue({ item, currentItems, allItems })) {
  7887. return;
  7888. }
  7889. yield item;
  7890. if (pagination.stackAllItems) {
  7891. allItems.push(item);
  7892. }
  7893. currentItems.push(item);
  7894. if (--countLimit <= 0) {
  7895. return;
  7896. }
  7897. }
  7898. }
  7899. const optionsToMerge = pagination.paginate({
  7900. response,
  7901. currentItems,
  7902. allItems
  7903. });
  7904. if (optionsToMerge === false) {
  7905. return;
  7906. }
  7907. if (optionsToMerge === response.request.options) {
  7908. normalizedOptions = response.request.options;
  7909. } else {
  7910. normalizedOptions.merge(optionsToMerge);
  7911. assert.any([dist_default.urlInstance, dist_default.undefined], optionsToMerge.url);
  7912. if (optionsToMerge.url !== void 0) {
  7913. normalizedOptions.prefixUrl = "";
  7914. normalizedOptions.url = optionsToMerge.url;
  7915. }
  7916. }
  7917. numberOfRequests++;
  7918. }
  7919. };
  7920. got2.paginate = paginateEach;
  7921. got2.paginate.all = async (url, options) => {
  7922. const results = [];
  7923. for await (const item of paginateEach(url, options)) {
  7924. results.push(item);
  7925. }
  7926. return results;
  7927. };
  7928. got2.paginate.each = paginateEach;
  7929. got2.stream = (url, options) => got2(url, { ...options, isStream: true });
  7930. for (const method of aliases) {
  7931. got2[method] = (url, options) => got2(url, { ...options, method });
  7932. got2.stream[method] = (url, options) => got2(url, { ...options, method, isStream: true });
  7933. }
  7934. if (!defaults2.mutableDefaults) {
  7935. Object.freeze(defaults2.handlers);
  7936. defaults2.options.freeze();
  7937. }
  7938. Object.defineProperty(got2, "defaults", {
  7939. value: defaults2,
  7940. writable: false,
  7941. configurable: false,
  7942. enumerable: true
  7943. });
  7944. return got2;
  7945. };
  7946. var create_default = create;
  7947. // node_modules/.pnpm/got@12.5.3/node_modules/got/dist/source/index.js
  7948. var defaults = {
  7949. options: new Options(),
  7950. handlers: [],
  7951. mutableDefaults: false
  7952. };
  7953. var got = create_default(defaults);
  7954. var source_default2 = got;
  7955. // src/index.ts
  7956. import pipe from "pump";
  7957. import { extract } from "tar-fs";
  7958. import gunzipMaybe from "gunzip-maybe";
  7959. var agentOpts = {
  7960. keepAlive: true,
  7961. maxSockets: 20
  7962. };
  7963. var agent = {
  7964. http: new HttpAgent(agentOpts),
  7965. https: new HttpsAgent(agentOpts)
  7966. };
  7967. async function download({ url, gotOpts, extractOpts, dir }) {
  7968. return new Promise((res, rej) => {
  7969. const callback = (err) => {
  7970. err ? rej(err) : res();
  7971. };
  7972. pipe(
  7973. source_default2.stream(url, Object.assign({ agent }, gotOpts)),
  7974. gunzipMaybe(),
  7975. extract(dir, extractOpts),
  7976. callback
  7977. );
  7978. });
  7979. }
  7980. export {
  7981. download as default
  7982. };