bin.cjs 3.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875
  1. #!/usr/bin/env node
  2. "use strict";
  3. var __create = Object.create;
  4. var __defProp = Object.defineProperty;
  5. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  6. var __getOwnPropNames = Object.getOwnPropertyNames;
  7. var __getProtoOf = Object.getPrototypeOf;
  8. var __hasOwnProp = Object.prototype.hasOwnProperty;
  9. var __esm = (fn, res) => function __init() {
  10. return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
  11. };
  12. var __commonJS = (cb, mod) => function __require() {
  13. return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  14. };
  15. var __export = (target, all) => {
  16. for (var name in all)
  17. __defProp(target, name, { get: all[name], enumerable: true });
  18. };
  19. var __copyProps = (to, from, except, desc) => {
  20. if (from && typeof from === "object" || typeof from === "function") {
  21. for (let key of __getOwnPropNames(from))
  22. if (!__hasOwnProp.call(to, key) && key !== except)
  23. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  24. }
  25. return to;
  26. };
  27. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  28. // If the importer is in node compatibility mode or this is not an ESM
  29. // file that has been converted to a CommonJS file using a Babel-
  30. // compatible transform (i.e. "__esModule" has not been set), then set
  31. // "default" to the CommonJS "module.exports" for node compatibility.
  32. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  33. mod
  34. ));
  35. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  36. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js
  37. function assembleStyles() {
  38. const codes = /* @__PURE__ */ new Map();
  39. for (const [groupName, group] of Object.entries(styles)) {
  40. for (const [styleName, style] of Object.entries(group)) {
  41. styles[styleName] = {
  42. open: `\x1B[${style[0]}m`,
  43. close: `\x1B[${style[1]}m`
  44. };
  45. group[styleName] = styles[styleName];
  46. codes.set(style[0], style[1]);
  47. }
  48. Object.defineProperty(styles, groupName, {
  49. value: group,
  50. enumerable: false
  51. });
  52. }
  53. Object.defineProperty(styles, "codes", {
  54. value: codes,
  55. enumerable: false
  56. });
  57. styles.color.close = "\x1B[39m";
  58. styles.bgColor.close = "\x1B[49m";
  59. styles.color.ansi = wrapAnsi16();
  60. styles.color.ansi256 = wrapAnsi256();
  61. styles.color.ansi16m = wrapAnsi16m();
  62. styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
  63. styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
  64. styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
  65. Object.defineProperties(styles, {
  66. rgbToAnsi256: {
  67. value(red, green, blue) {
  68. if (red === green && green === blue) {
  69. if (red < 8) {
  70. return 16;
  71. }
  72. if (red > 248) {
  73. return 231;
  74. }
  75. return Math.round((red - 8) / 247 * 24) + 232;
  76. }
  77. return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
  78. },
  79. enumerable: false
  80. },
  81. hexToRgb: {
  82. value(hex) {
  83. const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
  84. if (!matches) {
  85. return [0, 0, 0];
  86. }
  87. let [colorString] = matches;
  88. if (colorString.length === 3) {
  89. colorString = [...colorString].map((character) => character + character).join("");
  90. }
  91. const integer = Number.parseInt(colorString, 16);
  92. return [
  93. /* eslint-disable no-bitwise */
  94. integer >> 16 & 255,
  95. integer >> 8 & 255,
  96. integer & 255
  97. /* eslint-enable no-bitwise */
  98. ];
  99. },
  100. enumerable: false
  101. },
  102. hexToAnsi256: {
  103. value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
  104. enumerable: false
  105. },
  106. ansi256ToAnsi: {
  107. value(code) {
  108. if (code < 8) {
  109. return 30 + code;
  110. }
  111. if (code < 16) {
  112. return 90 + (code - 8);
  113. }
  114. let red;
  115. let green;
  116. let blue;
  117. if (code >= 232) {
  118. red = ((code - 232) * 10 + 8) / 255;
  119. green = red;
  120. blue = red;
  121. } else {
  122. code -= 16;
  123. const remainder = code % 36;
  124. red = Math.floor(code / 36) / 5;
  125. green = Math.floor(remainder / 6) / 5;
  126. blue = remainder % 6 / 5;
  127. }
  128. const value = Math.max(red, green, blue) * 2;
  129. if (value === 0) {
  130. return 30;
  131. }
  132. let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
  133. if (value === 2) {
  134. result += 60;
  135. }
  136. return result;
  137. },
  138. enumerable: false
  139. },
  140. rgbToAnsi: {
  141. value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
  142. enumerable: false
  143. },
  144. hexToAnsi: {
  145. value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
  146. enumerable: false
  147. }
  148. });
  149. return styles;
  150. }
  151. var ANSI_BACKGROUND_OFFSET, wrapAnsi16, wrapAnsi256, wrapAnsi16m, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
  152. var init_ansi_styles = __esm({
  153. "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js"() {
  154. ANSI_BACKGROUND_OFFSET = 10;
  155. wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
  156. wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
  157. wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
  158. styles = {
  159. modifier: {
  160. reset: [0, 0],
  161. // 21 isn't widely supported and 22 does the same thing
  162. bold: [1, 22],
  163. dim: [2, 22],
  164. italic: [3, 23],
  165. underline: [4, 24],
  166. overline: [53, 55],
  167. inverse: [7, 27],
  168. hidden: [8, 28],
  169. strikethrough: [9, 29]
  170. },
  171. color: {
  172. black: [30, 39],
  173. red: [31, 39],
  174. green: [32, 39],
  175. yellow: [33, 39],
  176. blue: [34, 39],
  177. magenta: [35, 39],
  178. cyan: [36, 39],
  179. white: [37, 39],
  180. // Bright color
  181. blackBright: [90, 39],
  182. gray: [90, 39],
  183. // Alias of `blackBright`
  184. grey: [90, 39],
  185. // Alias of `blackBright`
  186. redBright: [91, 39],
  187. greenBright: [92, 39],
  188. yellowBright: [93, 39],
  189. blueBright: [94, 39],
  190. magentaBright: [95, 39],
  191. cyanBright: [96, 39],
  192. whiteBright: [97, 39]
  193. },
  194. bgColor: {
  195. bgBlack: [40, 49],
  196. bgRed: [41, 49],
  197. bgGreen: [42, 49],
  198. bgYellow: [43, 49],
  199. bgBlue: [44, 49],
  200. bgMagenta: [45, 49],
  201. bgCyan: [46, 49],
  202. bgWhite: [47, 49],
  203. // Bright color
  204. bgBlackBright: [100, 49],
  205. bgGray: [100, 49],
  206. // Alias of `bgBlackBright`
  207. bgGrey: [100, 49],
  208. // Alias of `bgBlackBright`
  209. bgRedBright: [101, 49],
  210. bgGreenBright: [102, 49],
  211. bgYellowBright: [103, 49],
  212. bgBlueBright: [104, 49],
  213. bgMagentaBright: [105, 49],
  214. bgCyanBright: [106, 49],
  215. bgWhiteBright: [107, 49]
  216. }
  217. };
  218. modifierNames = Object.keys(styles.modifier);
  219. foregroundColorNames = Object.keys(styles.color);
  220. backgroundColorNames = Object.keys(styles.bgColor);
  221. colorNames = [...foregroundColorNames, ...backgroundColorNames];
  222. ansiStyles = assembleStyles();
  223. ansi_styles_default = ansiStyles;
  224. }
  225. });
  226. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js
  227. function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
  228. const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  229. const position = argv.indexOf(prefix2 + flag);
  230. const terminatorPosition = argv.indexOf("--");
  231. return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
  232. }
  233. function envForceColor() {
  234. if ("FORCE_COLOR" in env) {
  235. if (env.FORCE_COLOR === "true") {
  236. return 1;
  237. }
  238. if (env.FORCE_COLOR === "false") {
  239. return 0;
  240. }
  241. return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
  242. }
  243. }
  244. function translateLevel(level) {
  245. if (level === 0) {
  246. return false;
  247. }
  248. return {
  249. level,
  250. hasBasic: true,
  251. has256: level >= 2,
  252. has16m: level >= 3
  253. };
  254. }
  255. function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
  256. const noFlagForceColor = envForceColor();
  257. if (noFlagForceColor !== void 0) {
  258. flagForceColor = noFlagForceColor;
  259. }
  260. const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
  261. if (forceColor === 0) {
  262. return 0;
  263. }
  264. if (sniffFlags) {
  265. if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
  266. return 3;
  267. }
  268. if (hasFlag("color=256")) {
  269. return 2;
  270. }
  271. }
  272. if ("TF_BUILD" in env && "AGENT_NAME" in env) {
  273. return 1;
  274. }
  275. if (haveStream && !streamIsTTY && forceColor === void 0) {
  276. return 0;
  277. }
  278. const min = forceColor || 0;
  279. if (env.TERM === "dumb") {
  280. return min;
  281. }
  282. if (import_node_process.default.platform === "win32") {
  283. const osRelease = import_node_os.default.release().split(".");
  284. if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
  285. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  286. }
  287. return 1;
  288. }
  289. if ("CI" in env) {
  290. if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
  291. return 3;
  292. }
  293. if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
  294. return 1;
  295. }
  296. return min;
  297. }
  298. if ("TEAMCITY_VERSION" in env) {
  299. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  300. }
  301. if (env.COLORTERM === "truecolor") {
  302. return 3;
  303. }
  304. if (env.TERM === "xterm-kitty") {
  305. return 3;
  306. }
  307. if ("TERM_PROGRAM" in env) {
  308. const version3 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
  309. switch (env.TERM_PROGRAM) {
  310. case "iTerm.app": {
  311. return version3 >= 3 ? 3 : 2;
  312. }
  313. case "Apple_Terminal": {
  314. return 2;
  315. }
  316. }
  317. }
  318. if (/-256(color)?$/i.test(env.TERM)) {
  319. return 2;
  320. }
  321. if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
  322. return 1;
  323. }
  324. if ("COLORTERM" in env) {
  325. return 1;
  326. }
  327. return min;
  328. }
  329. function createSupportsColor(stream, options = {}) {
  330. const level = _supportsColor(stream, {
  331. streamIsTTY: stream && stream.isTTY,
  332. ...options
  333. });
  334. return translateLevel(level);
  335. }
  336. var import_node_process, import_node_os, import_node_tty, env, flagForceColor, supportsColor, supports_color_default;
  337. var init_supports_color = __esm({
  338. "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js"() {
  339. import_node_process = __toESM(require("node:process"), 1);
  340. import_node_os = __toESM(require("node:os"), 1);
  341. import_node_tty = __toESM(require("node:tty"), 1);
  342. ({ env } = import_node_process.default);
  343. if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
  344. flagForceColor = 0;
  345. } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
  346. flagForceColor = 1;
  347. }
  348. supportsColor = {
  349. stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
  350. stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
  351. };
  352. supports_color_default = supportsColor;
  353. }
  354. });
  355. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js
  356. function stringReplaceAll(string2, substring, replacer) {
  357. let index6 = string2.indexOf(substring);
  358. if (index6 === -1) {
  359. return string2;
  360. }
  361. const substringLength = substring.length;
  362. let endIndex = 0;
  363. let returnValue = "";
  364. do {
  365. returnValue += string2.slice(endIndex, index6) + substring + replacer;
  366. endIndex = index6 + substringLength;
  367. index6 = string2.indexOf(substring, endIndex);
  368. } while (index6 !== -1);
  369. returnValue += string2.slice(endIndex);
  370. return returnValue;
  371. }
  372. function stringEncaseCRLFWithFirstIndex(string2, prefix2, postfix, index6) {
  373. let endIndex = 0;
  374. let returnValue = "";
  375. do {
  376. const gotCR = string2[index6 - 1] === "\r";
  377. returnValue += string2.slice(endIndex, gotCR ? index6 - 1 : index6) + prefix2 + (gotCR ? "\r\n" : "\n") + postfix;
  378. endIndex = index6 + 1;
  379. index6 = string2.indexOf("\n", endIndex);
  380. } while (index6 !== -1);
  381. returnValue += string2.slice(endIndex);
  382. return returnValue;
  383. }
  384. var init_utilities = __esm({
  385. "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js"() {
  386. }
  387. });
  388. // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js
  389. function createChalk(options) {
  390. return chalkFactory(options);
  391. }
  392. var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions, chalkFactory, getModelAnsi, usedModels, proto, createStyler, createBuilder, applyStyle, chalk, chalkStderr, source_default;
  393. var init_source = __esm({
  394. "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js"() {
  395. init_ansi_styles();
  396. init_supports_color();
  397. init_utilities();
  398. ({ stdout: stdoutColor, stderr: stderrColor } = supports_color_default);
  399. GENERATOR = Symbol("GENERATOR");
  400. STYLER = Symbol("STYLER");
  401. IS_EMPTY = Symbol("IS_EMPTY");
  402. levelMapping = [
  403. "ansi",
  404. "ansi",
  405. "ansi256",
  406. "ansi16m"
  407. ];
  408. styles2 = /* @__PURE__ */ Object.create(null);
  409. applyOptions = (object, options = {}) => {
  410. if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
  411. throw new Error("The `level` option should be an integer from 0 to 3");
  412. }
  413. const colorLevel = stdoutColor ? stdoutColor.level : 0;
  414. object.level = options.level === void 0 ? colorLevel : options.level;
  415. };
  416. chalkFactory = (options) => {
  417. const chalk2 = (...strings) => strings.join(" ");
  418. applyOptions(chalk2, options);
  419. Object.setPrototypeOf(chalk2, createChalk.prototype);
  420. return chalk2;
  421. };
  422. Object.setPrototypeOf(createChalk.prototype, Function.prototype);
  423. for (const [styleName, style] of Object.entries(ansi_styles_default)) {
  424. styles2[styleName] = {
  425. get() {
  426. const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
  427. Object.defineProperty(this, styleName, { value: builder });
  428. return builder;
  429. }
  430. };
  431. }
  432. styles2.visible = {
  433. get() {
  434. const builder = createBuilder(this, this[STYLER], true);
  435. Object.defineProperty(this, "visible", { value: builder });
  436. return builder;
  437. }
  438. };
  439. getModelAnsi = (model, level, type, ...arguments_) => {
  440. if (model === "rgb") {
  441. if (level === "ansi16m") {
  442. return ansi_styles_default[type].ansi16m(...arguments_);
  443. }
  444. if (level === "ansi256") {
  445. return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
  446. }
  447. return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
  448. }
  449. if (model === "hex") {
  450. return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
  451. }
  452. return ansi_styles_default[type][model](...arguments_);
  453. };
  454. usedModels = ["rgb", "hex", "ansi256"];
  455. for (const model of usedModels) {
  456. styles2[model] = {
  457. get() {
  458. const { level } = this;
  459. return function(...arguments_) {
  460. const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
  461. return createBuilder(this, styler, this[IS_EMPTY]);
  462. };
  463. }
  464. };
  465. const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
  466. styles2[bgModel] = {
  467. get() {
  468. const { level } = this;
  469. return function(...arguments_) {
  470. const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
  471. return createBuilder(this, styler, this[IS_EMPTY]);
  472. };
  473. }
  474. };
  475. }
  476. proto = Object.defineProperties(() => {
  477. }, {
  478. ...styles2,
  479. level: {
  480. enumerable: true,
  481. get() {
  482. return this[GENERATOR].level;
  483. },
  484. set(level) {
  485. this[GENERATOR].level = level;
  486. }
  487. }
  488. });
  489. createStyler = (open, close, parent) => {
  490. let openAll;
  491. let closeAll;
  492. if (parent === void 0) {
  493. openAll = open;
  494. closeAll = close;
  495. } else {
  496. openAll = parent.openAll + open;
  497. closeAll = close + parent.closeAll;
  498. }
  499. return {
  500. open,
  501. close,
  502. openAll,
  503. closeAll,
  504. parent
  505. };
  506. };
  507. createBuilder = (self2, _styler, _isEmpty) => {
  508. const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
  509. Object.setPrototypeOf(builder, proto);
  510. builder[GENERATOR] = self2;
  511. builder[STYLER] = _styler;
  512. builder[IS_EMPTY] = _isEmpty;
  513. return builder;
  514. };
  515. applyStyle = (self2, string2) => {
  516. if (self2.level <= 0 || !string2) {
  517. return self2[IS_EMPTY] ? "" : string2;
  518. }
  519. let styler = self2[STYLER];
  520. if (styler === void 0) {
  521. return string2;
  522. }
  523. const { openAll, closeAll } = styler;
  524. if (string2.includes("\x1B")) {
  525. while (styler !== void 0) {
  526. string2 = stringReplaceAll(string2, styler.close, styler.open);
  527. styler = styler.parent;
  528. }
  529. }
  530. const lfIndex = string2.indexOf("\n");
  531. if (lfIndex !== -1) {
  532. string2 = stringEncaseCRLFWithFirstIndex(string2, closeAll, openAll, lfIndex);
  533. }
  534. return openAll + string2 + closeAll;
  535. };
  536. Object.defineProperties(createChalk.prototype, styles2);
  537. chalk = createChalk();
  538. chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
  539. source_default = chalk;
  540. }
  541. });
  542. // ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/package.json
  543. var require_package = __commonJS({
  544. "../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/package.json"(exports2, module2) {
  545. module2.exports = {
  546. name: "dotenv",
  547. version: "16.5.0",
  548. description: "Loads environment variables from .env file",
  549. main: "lib/main.js",
  550. types: "lib/main.d.ts",
  551. exports: {
  552. ".": {
  553. types: "./lib/main.d.ts",
  554. require: "./lib/main.js",
  555. default: "./lib/main.js"
  556. },
  557. "./config": "./config.js",
  558. "./config.js": "./config.js",
  559. "./lib/env-options": "./lib/env-options.js",
  560. "./lib/env-options.js": "./lib/env-options.js",
  561. "./lib/cli-options": "./lib/cli-options.js",
  562. "./lib/cli-options.js": "./lib/cli-options.js",
  563. "./package.json": "./package.json"
  564. },
  565. scripts: {
  566. "dts-check": "tsc --project tests/types/tsconfig.json",
  567. lint: "standard",
  568. pretest: "npm run lint && npm run dts-check",
  569. test: "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
  570. "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",
  571. prerelease: "npm test",
  572. release: "standard-version"
  573. },
  574. repository: {
  575. type: "git",
  576. url: "git://github.com/motdotla/dotenv.git"
  577. },
  578. homepage: "https://github.com/motdotla/dotenv#readme",
  579. funding: "https://dotenvx.com",
  580. keywords: [
  581. "dotenv",
  582. "env",
  583. ".env",
  584. "environment",
  585. "variables",
  586. "config",
  587. "settings"
  588. ],
  589. readmeFilename: "README.md",
  590. license: "BSD-2-Clause",
  591. devDependencies: {
  592. "@types/node": "^18.11.3",
  593. decache: "^4.6.2",
  594. sinon: "^14.0.1",
  595. standard: "^17.0.0",
  596. "standard-version": "^9.5.0",
  597. tap: "^19.2.0",
  598. typescript: "^4.8.4"
  599. },
  600. engines: {
  601. node: ">=12"
  602. },
  603. browser: {
  604. fs: false
  605. }
  606. };
  607. }
  608. });
  609. // ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/main.js
  610. var require_main = __commonJS({
  611. "../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/main.js"(exports2, module2) {
  612. var fs7 = require("fs");
  613. var path4 = require("path");
  614. var os3 = require("os");
  615. var crypto7 = require("crypto");
  616. var packageJson = require_package();
  617. var version3 = packageJson.version;
  618. var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
  619. function parse4(src) {
  620. const obj = {};
  621. let lines = src.toString();
  622. lines = lines.replace(/\r\n?/mg, "\n");
  623. let match2;
  624. while ((match2 = LINE.exec(lines)) != null) {
  625. const key = match2[1];
  626. let value = match2[2] || "";
  627. value = value.trim();
  628. const maybeQuote = value[0];
  629. value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
  630. if (maybeQuote === '"') {
  631. value = value.replace(/\\n/g, "\n");
  632. value = value.replace(/\\r/g, "\r");
  633. }
  634. obj[key] = value;
  635. }
  636. return obj;
  637. }
  638. function _parseVault(options) {
  639. const vaultPath = _vaultPath(options);
  640. const result = DotenvModule.configDotenv({ path: vaultPath });
  641. if (!result.parsed) {
  642. const err2 = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
  643. err2.code = "MISSING_DATA";
  644. throw err2;
  645. }
  646. const keys = _dotenvKey(options).split(",");
  647. const length = keys.length;
  648. let decrypted;
  649. for (let i4 = 0; i4 < length; i4++) {
  650. try {
  651. const key = keys[i4].trim();
  652. const attrs = _instructions(result, key);
  653. decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
  654. break;
  655. } catch (error2) {
  656. if (i4 + 1 >= length) {
  657. throw error2;
  658. }
  659. }
  660. }
  661. return DotenvModule.parse(decrypted);
  662. }
  663. function _warn(message) {
  664. console.log(`[dotenv@${version3}][WARN] ${message}`);
  665. }
  666. function _debug(message) {
  667. console.log(`[dotenv@${version3}][DEBUG] ${message}`);
  668. }
  669. function _dotenvKey(options) {
  670. if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
  671. return options.DOTENV_KEY;
  672. }
  673. if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
  674. return process.env.DOTENV_KEY;
  675. }
  676. return "";
  677. }
  678. function _instructions(result, dotenvKey) {
  679. let uri;
  680. try {
  681. uri = new URL(dotenvKey);
  682. } catch (error2) {
  683. if (error2.code === "ERR_INVALID_URL") {
  684. const err2 = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
  685. err2.code = "INVALID_DOTENV_KEY";
  686. throw err2;
  687. }
  688. throw error2;
  689. }
  690. const key = uri.password;
  691. if (!key) {
  692. const err2 = new Error("INVALID_DOTENV_KEY: Missing key part");
  693. err2.code = "INVALID_DOTENV_KEY";
  694. throw err2;
  695. }
  696. const environment = uri.searchParams.get("environment");
  697. if (!environment) {
  698. const err2 = new Error("INVALID_DOTENV_KEY: Missing environment part");
  699. err2.code = "INVALID_DOTENV_KEY";
  700. throw err2;
  701. }
  702. const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
  703. const ciphertext = result.parsed[environmentKey];
  704. if (!ciphertext) {
  705. const err2 = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
  706. err2.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
  707. throw err2;
  708. }
  709. return { ciphertext, key };
  710. }
  711. function _vaultPath(options) {
  712. let possibleVaultPath = null;
  713. if (options && options.path && options.path.length > 0) {
  714. if (Array.isArray(options.path)) {
  715. for (const filepath of options.path) {
  716. if (fs7.existsSync(filepath)) {
  717. possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
  718. }
  719. }
  720. } else {
  721. possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
  722. }
  723. } else {
  724. possibleVaultPath = path4.resolve(process.cwd(), ".env.vault");
  725. }
  726. if (fs7.existsSync(possibleVaultPath)) {
  727. return possibleVaultPath;
  728. }
  729. return null;
  730. }
  731. function _resolveHome(envPath) {
  732. return envPath[0] === "~" ? path4.join(os3.homedir(), envPath.slice(1)) : envPath;
  733. }
  734. function _configVault(options) {
  735. const debug = Boolean(options && options.debug);
  736. if (debug) {
  737. _debug("Loading env from encrypted .env.vault");
  738. }
  739. const parsed = DotenvModule._parseVault(options);
  740. let processEnv = process.env;
  741. if (options && options.processEnv != null) {
  742. processEnv = options.processEnv;
  743. }
  744. DotenvModule.populate(processEnv, parsed, options);
  745. return { parsed };
  746. }
  747. function configDotenv(options) {
  748. const dotenvPath = path4.resolve(process.cwd(), ".env");
  749. let encoding = "utf8";
  750. const debug = Boolean(options && options.debug);
  751. if (options && options.encoding) {
  752. encoding = options.encoding;
  753. } else {
  754. if (debug) {
  755. _debug("No encoding is specified. UTF-8 is used by default");
  756. }
  757. }
  758. let optionPaths = [dotenvPath];
  759. if (options && options.path) {
  760. if (!Array.isArray(options.path)) {
  761. optionPaths = [_resolveHome(options.path)];
  762. } else {
  763. optionPaths = [];
  764. for (const filepath of options.path) {
  765. optionPaths.push(_resolveHome(filepath));
  766. }
  767. }
  768. }
  769. let lastError;
  770. const parsedAll = {};
  771. for (const path5 of optionPaths) {
  772. try {
  773. const parsed = DotenvModule.parse(fs7.readFileSync(path5, { encoding }));
  774. DotenvModule.populate(parsedAll, parsed, options);
  775. } catch (e4) {
  776. if (debug) {
  777. _debug(`Failed to load ${path5} ${e4.message}`);
  778. }
  779. lastError = e4;
  780. }
  781. }
  782. let processEnv = process.env;
  783. if (options && options.processEnv != null) {
  784. processEnv = options.processEnv;
  785. }
  786. DotenvModule.populate(processEnv, parsedAll, options);
  787. if (lastError) {
  788. return { parsed: parsedAll, error: lastError };
  789. } else {
  790. return { parsed: parsedAll };
  791. }
  792. }
  793. function config(options) {
  794. if (_dotenvKey(options).length === 0) {
  795. return DotenvModule.configDotenv(options);
  796. }
  797. const vaultPath = _vaultPath(options);
  798. if (!vaultPath) {
  799. _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
  800. return DotenvModule.configDotenv(options);
  801. }
  802. return DotenvModule._configVault(options);
  803. }
  804. function decrypt(encrypted, keyStr) {
  805. const key = Buffer.from(keyStr.slice(-64), "hex");
  806. let ciphertext = Buffer.from(encrypted, "base64");
  807. const nonce = ciphertext.subarray(0, 12);
  808. const authTag = ciphertext.subarray(-16);
  809. ciphertext = ciphertext.subarray(12, -16);
  810. try {
  811. const aesgcm = crypto7.createDecipheriv("aes-256-gcm", key, nonce);
  812. aesgcm.setAuthTag(authTag);
  813. return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
  814. } catch (error2) {
  815. const isRange = error2 instanceof RangeError;
  816. const invalidKeyLength = error2.message === "Invalid key length";
  817. const decryptionFailed = error2.message === "Unsupported state or unable to authenticate data";
  818. if (isRange || invalidKeyLength) {
  819. const err2 = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
  820. err2.code = "INVALID_DOTENV_KEY";
  821. throw err2;
  822. } else if (decryptionFailed) {
  823. const err2 = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
  824. err2.code = "DECRYPTION_FAILED";
  825. throw err2;
  826. } else {
  827. throw error2;
  828. }
  829. }
  830. }
  831. function populate(processEnv, parsed, options = {}) {
  832. const debug = Boolean(options && options.debug);
  833. const override = Boolean(options && options.override);
  834. if (typeof parsed !== "object") {
  835. const err2 = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
  836. err2.code = "OBJECT_REQUIRED";
  837. throw err2;
  838. }
  839. for (const key of Object.keys(parsed)) {
  840. if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
  841. if (override === true) {
  842. processEnv[key] = parsed[key];
  843. }
  844. if (debug) {
  845. if (override === true) {
  846. _debug(`"${key}" is already defined and WAS overwritten`);
  847. } else {
  848. _debug(`"${key}" is already defined and was NOT overwritten`);
  849. }
  850. }
  851. } else {
  852. processEnv[key] = parsed[key];
  853. }
  854. }
  855. }
  856. var DotenvModule = {
  857. configDotenv,
  858. _configVault,
  859. _parseVault,
  860. config,
  861. decrypt,
  862. parse: parse4,
  863. populate
  864. };
  865. module2.exports.configDotenv = DotenvModule.configDotenv;
  866. module2.exports._configVault = DotenvModule._configVault;
  867. module2.exports._parseVault = DotenvModule._parseVault;
  868. module2.exports.config = DotenvModule.config;
  869. module2.exports.decrypt = DotenvModule.decrypt;
  870. module2.exports.parse = DotenvModule.parse;
  871. module2.exports.populate = DotenvModule.populate;
  872. module2.exports = DotenvModule;
  873. }
  874. });
  875. // ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/env-options.js
  876. var require_env_options = __commonJS({
  877. "../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/env-options.js"(exports2, module2) {
  878. var options = {};
  879. if (process.env.DOTENV_CONFIG_ENCODING != null) {
  880. options.encoding = process.env.DOTENV_CONFIG_ENCODING;
  881. }
  882. if (process.env.DOTENV_CONFIG_PATH != null) {
  883. options.path = process.env.DOTENV_CONFIG_PATH;
  884. }
  885. if (process.env.DOTENV_CONFIG_DEBUG != null) {
  886. options.debug = process.env.DOTENV_CONFIG_DEBUG;
  887. }
  888. if (process.env.DOTENV_CONFIG_OVERRIDE != null) {
  889. options.override = process.env.DOTENV_CONFIG_OVERRIDE;
  890. }
  891. if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {
  892. options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
  893. }
  894. module2.exports = options;
  895. }
  896. });
  897. // ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/cli-options.js
  898. var require_cli_options = __commonJS({
  899. "../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/cli-options.js"(exports2, module2) {
  900. var re = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/;
  901. module2.exports = function optionMatcher(args) {
  902. return args.reduce(function(acc, cur) {
  903. const matches = cur.match(re);
  904. if (matches) {
  905. acc[matches[1]] = matches[2];
  906. }
  907. return acc;
  908. }, {});
  909. };
  910. }
  911. });
  912. // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/readline.js
  913. var require_readline = __commonJS({
  914. "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/readline.js"(exports2) {
  915. "use strict";
  916. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  917. return mod && mod.__esModule ? mod : { "default": mod };
  918. };
  919. Object.defineProperty(exports2, "__esModule", { value: true });
  920. exports2.createClosable = exports2.stdout = exports2.stdin = void 0;
  921. var readline_1 = __importDefault2(require("readline"));
  922. exports2.stdin = process.stdin;
  923. exports2.stdout = process.stdout;
  924. readline_1.default.emitKeypressEvents(exports2.stdin);
  925. var createClosable = () => {
  926. return readline_1.default.createInterface({
  927. input: exports2.stdin,
  928. escapeCodeTimeout: 50
  929. });
  930. };
  931. exports2.createClosable = createClosable;
  932. }
  933. });
  934. // ../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
  935. var require_src = __commonJS({
  936. "../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2, module2) {
  937. "use strict";
  938. var ESC = "\x1B";
  939. var CSI = `${ESC}[`;
  940. var beep = "\x07";
  941. var cursor = {
  942. to(x4, y2) {
  943. if (!y2) return `${CSI}${x4 + 1}G`;
  944. return `${CSI}${y2 + 1};${x4 + 1}H`;
  945. },
  946. move(x4, y2) {
  947. let ret = "";
  948. if (x4 < 0) ret += `${CSI}${-x4}D`;
  949. else if (x4 > 0) ret += `${CSI}${x4}C`;
  950. if (y2 < 0) ret += `${CSI}${-y2}A`;
  951. else if (y2 > 0) ret += `${CSI}${y2}B`;
  952. return ret;
  953. },
  954. up: (count = 1) => `${CSI}${count}A`,
  955. down: (count = 1) => `${CSI}${count}B`,
  956. forward: (count = 1) => `${CSI}${count}C`,
  957. backward: (count = 1) => `${CSI}${count}D`,
  958. nextLine: (count = 1) => `${CSI}E`.repeat(count),
  959. prevLine: (count = 1) => `${CSI}F`.repeat(count),
  960. left: `${CSI}G`,
  961. hide: `${CSI}?25l`,
  962. show: `${CSI}?25h`,
  963. save: `${ESC}7`,
  964. restore: `${ESC}8`
  965. };
  966. var scroll = {
  967. up: (count = 1) => `${CSI}S`.repeat(count),
  968. down: (count = 1) => `${CSI}T`.repeat(count)
  969. };
  970. var erase = {
  971. screen: `${CSI}2J`,
  972. up: (count = 1) => `${CSI}1J`.repeat(count),
  973. down: (count = 1) => `${CSI}J`.repeat(count),
  974. line: `${CSI}2K`,
  975. lineEnd: `${CSI}K`,
  976. lineStart: `${CSI}1K`,
  977. lines(count) {
  978. let clear = "";
  979. for (let i4 = 0; i4 < count; i4++)
  980. clear += this.line + (i4 < count - 1 ? cursor.up() : "");
  981. if (count)
  982. clear += cursor.left;
  983. return clear;
  984. }
  985. };
  986. module2.exports = { cursor, scroll, erase, beep };
  987. }
  988. });
  989. // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/utils.js
  990. var require_utils = __commonJS({
  991. "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/utils.js"(exports2) {
  992. "use strict";
  993. Object.defineProperty(exports2, "__esModule", { value: true });
  994. exports2.clear = exports2.stringWidth = exports2.fallbackStringWidth = exports2.stripAnsi = exports2.strip = void 0;
  995. var sisteransi_1 = require_src();
  996. var strip = (str) => {
  997. const pattern = [
  998. "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
  999. "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
  1000. ].join("|");
  1001. const RGX = new RegExp(pattern, "g");
  1002. return typeof str === "string" ? str.replace(RGX, "") : str;
  1003. };
  1004. exports2.strip = strip;
  1005. var stripAnsi = (str) => {
  1006. if (typeof Bun !== "undefined" && Bun.stripANSI) {
  1007. return Bun.stripANSI(str);
  1008. }
  1009. return (0, exports2.strip)(str);
  1010. };
  1011. exports2.stripAnsi = stripAnsi;
  1012. var fallbackStringWidth = (str) => {
  1013. let len = 0;
  1014. const stripped = (0, exports2.stripAnsi)(str);
  1015. for (const _3 of stripped)
  1016. len++;
  1017. return len;
  1018. };
  1019. exports2.fallbackStringWidth = fallbackStringWidth;
  1020. var stringWidth = (str) => {
  1021. if (typeof Bun !== "undefined" && Bun.stringWidth)
  1022. return Bun.stringWidth(str);
  1023. return (0, exports2.fallbackStringWidth)(str);
  1024. };
  1025. exports2.stringWidth = stringWidth;
  1026. var clear = function(prompt, perLine) {
  1027. if (!perLine)
  1028. return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
  1029. let rows = 0;
  1030. const lines = prompt.split(/\r?\n/);
  1031. for (let line of lines) {
  1032. rows += 1 + Math.floor(Math.max((0, exports2.stringWidth)(line) - 1, 0) / perLine);
  1033. }
  1034. return sisteransi_1.erase.lines(rows);
  1035. };
  1036. exports2.clear = clear;
  1037. }
  1038. });
  1039. // ../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
  1040. var require_lodash = __commonJS({
  1041. "../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports2, module2) {
  1042. var FUNC_ERROR_TEXT = "Expected a function";
  1043. var NAN = 0 / 0;
  1044. var symbolTag = "[object Symbol]";
  1045. var reTrim = /^\s+|\s+$/g;
  1046. var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
  1047. var reIsBinary = /^0b[01]+$/i;
  1048. var reIsOctal = /^0o[0-7]+$/i;
  1049. var freeParseInt = parseInt;
  1050. var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
  1051. var freeSelf = typeof self == "object" && self && self.Object === Object && self;
  1052. var root = freeGlobal || freeSelf || Function("return this")();
  1053. var objectProto = Object.prototype;
  1054. var objectToString = objectProto.toString;
  1055. var nativeMax = Math.max;
  1056. var nativeMin = Math.min;
  1057. var now = function() {
  1058. return root.Date.now();
  1059. };
  1060. function debounce(func, wait, options) {
  1061. var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
  1062. if (typeof func != "function") {
  1063. throw new TypeError(FUNC_ERROR_TEXT);
  1064. }
  1065. wait = toNumber(wait) || 0;
  1066. if (isObject(options)) {
  1067. leading = !!options.leading;
  1068. maxing = "maxWait" in options;
  1069. maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
  1070. trailing = "trailing" in options ? !!options.trailing : trailing;
  1071. }
  1072. function invokeFunc(time) {
  1073. var args = lastArgs, thisArg = lastThis;
  1074. lastArgs = lastThis = void 0;
  1075. lastInvokeTime = time;
  1076. result = func.apply(thisArg, args);
  1077. return result;
  1078. }
  1079. function leadingEdge(time) {
  1080. lastInvokeTime = time;
  1081. timerId = setTimeout(timerExpired, wait);
  1082. return leading ? invokeFunc(time) : result;
  1083. }
  1084. function remainingWait(time) {
  1085. var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
  1086. return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
  1087. }
  1088. function shouldInvoke(time) {
  1089. var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
  1090. return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
  1091. }
  1092. function timerExpired() {
  1093. var time = now();
  1094. if (shouldInvoke(time)) {
  1095. return trailingEdge(time);
  1096. }
  1097. timerId = setTimeout(timerExpired, remainingWait(time));
  1098. }
  1099. function trailingEdge(time) {
  1100. timerId = void 0;
  1101. if (trailing && lastArgs) {
  1102. return invokeFunc(time);
  1103. }
  1104. lastArgs = lastThis = void 0;
  1105. return result;
  1106. }
  1107. function cancel() {
  1108. if (timerId !== void 0) {
  1109. clearTimeout(timerId);
  1110. }
  1111. lastInvokeTime = 0;
  1112. lastArgs = lastCallTime = lastThis = timerId = void 0;
  1113. }
  1114. function flush() {
  1115. return timerId === void 0 ? result : trailingEdge(now());
  1116. }
  1117. function debounced() {
  1118. var time = now(), isInvoking = shouldInvoke(time);
  1119. lastArgs = arguments;
  1120. lastThis = this;
  1121. lastCallTime = time;
  1122. if (isInvoking) {
  1123. if (timerId === void 0) {
  1124. return leadingEdge(lastCallTime);
  1125. }
  1126. if (maxing) {
  1127. timerId = setTimeout(timerExpired, wait);
  1128. return invokeFunc(lastCallTime);
  1129. }
  1130. }
  1131. if (timerId === void 0) {
  1132. timerId = setTimeout(timerExpired, wait);
  1133. }
  1134. return result;
  1135. }
  1136. debounced.cancel = cancel;
  1137. debounced.flush = flush;
  1138. return debounced;
  1139. }
  1140. function throttle(func, wait, options) {
  1141. var leading = true, trailing = true;
  1142. if (typeof func != "function") {
  1143. throw new TypeError(FUNC_ERROR_TEXT);
  1144. }
  1145. if (isObject(options)) {
  1146. leading = "leading" in options ? !!options.leading : leading;
  1147. trailing = "trailing" in options ? !!options.trailing : trailing;
  1148. }
  1149. return debounce(func, wait, {
  1150. "leading": leading,
  1151. "maxWait": wait,
  1152. "trailing": trailing
  1153. });
  1154. }
  1155. function isObject(value) {
  1156. var type = typeof value;
  1157. return !!value && (type == "object" || type == "function");
  1158. }
  1159. function isObjectLike(value) {
  1160. return !!value && typeof value == "object";
  1161. }
  1162. function isSymbol(value) {
  1163. return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
  1164. }
  1165. function toNumber(value) {
  1166. if (typeof value == "number") {
  1167. return value;
  1168. }
  1169. if (isSymbol(value)) {
  1170. return NAN;
  1171. }
  1172. if (isObject(value)) {
  1173. var other = typeof value.valueOf == "function" ? value.valueOf() : value;
  1174. value = isObject(other) ? other + "" : other;
  1175. }
  1176. if (typeof value != "string") {
  1177. return value === 0 ? value : +value;
  1178. }
  1179. value = value.replace(reTrim, "");
  1180. var isBinary = reIsBinary.test(value);
  1181. return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
  1182. }
  1183. module2.exports = throttle;
  1184. }
  1185. });
  1186. // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/index.js
  1187. var require_hanji = __commonJS({
  1188. "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/index.js"(exports2) {
  1189. "use strict";
  1190. var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
  1191. function adopt(value) {
  1192. return value instanceof P ? value : new P(function(resolve2) {
  1193. resolve2(value);
  1194. });
  1195. }
  1196. return new (P || (P = Promise))(function(resolve2, reject) {
  1197. function fulfilled(value) {
  1198. try {
  1199. step(generator.next(value));
  1200. } catch (e4) {
  1201. reject(e4);
  1202. }
  1203. }
  1204. function rejected(value) {
  1205. try {
  1206. step(generator["throw"](value));
  1207. } catch (e4) {
  1208. reject(e4);
  1209. }
  1210. }
  1211. function step(result) {
  1212. result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
  1213. }
  1214. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1215. });
  1216. };
  1217. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  1218. return mod && mod.__esModule ? mod : { "default": mod };
  1219. };
  1220. Object.defineProperty(exports2, "__esModule", { value: true });
  1221. exports2.TaskTerminal = exports2.TaskView = exports2.Terminal = exports2.deferred = exports2.SelectState = exports2.Prompt = void 0;
  1222. exports2.render = render10;
  1223. exports2.renderWithTask = renderWithTask7;
  1224. exports2.onTerminate = onTerminate;
  1225. var readline_1 = require_readline();
  1226. var sisteransi_1 = require_src();
  1227. var utils_1 = require_utils();
  1228. var lodash_throttle_1 = __importDefault2(require_lodash());
  1229. var Prompt3 = class {
  1230. constructor() {
  1231. this.attachCallbacks = [];
  1232. this.detachCallbacks = [];
  1233. this.inputCallbacks = [];
  1234. }
  1235. requestLayout() {
  1236. this.terminal.requestLayout();
  1237. }
  1238. on(type, callback) {
  1239. if (type === "attach") {
  1240. this.attachCallbacks.push(callback);
  1241. } else if (type === "detach") {
  1242. this.detachCallbacks.push(callback);
  1243. } else if (type === "input") {
  1244. this.inputCallbacks.push(callback);
  1245. }
  1246. }
  1247. attach(terminal) {
  1248. this.terminal = terminal;
  1249. this.attachCallbacks.forEach((it) => it(terminal));
  1250. }
  1251. detach(terminal) {
  1252. this.detachCallbacks.forEach((it) => it(terminal));
  1253. this.terminal = void 0;
  1254. }
  1255. input(str, key) {
  1256. this.inputCallbacks.forEach((it) => it(str, key));
  1257. }
  1258. };
  1259. exports2.Prompt = Prompt3;
  1260. var SelectState3 = class {
  1261. constructor(items) {
  1262. this.items = items;
  1263. this.selectedIdx = 0;
  1264. }
  1265. bind(prompt) {
  1266. prompt.on("input", (str, key) => {
  1267. const invalidate = this.consume(str, key);
  1268. if (invalidate)
  1269. prompt.requestLayout();
  1270. });
  1271. }
  1272. consume(str, key) {
  1273. if (!key)
  1274. return false;
  1275. if (key.name === "down") {
  1276. this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
  1277. return true;
  1278. }
  1279. if (key.name === "up") {
  1280. this.selectedIdx -= 1;
  1281. this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
  1282. return true;
  1283. }
  1284. return false;
  1285. }
  1286. };
  1287. exports2.SelectState = SelectState3;
  1288. var deferred = () => {
  1289. let resolve2;
  1290. let reject;
  1291. const promise = new Promise((res, rej) => {
  1292. resolve2 = res;
  1293. reject = rej;
  1294. });
  1295. return {
  1296. resolve: resolve2,
  1297. reject,
  1298. promise
  1299. };
  1300. };
  1301. exports2.deferred = deferred;
  1302. var Terminal = class {
  1303. constructor(view5, stdin, stdout, closable) {
  1304. this.view = view5;
  1305. this.stdin = stdin;
  1306. this.stdout = stdout;
  1307. this.closable = closable;
  1308. this.text = "";
  1309. this.status = "idle";
  1310. if (this.stdin.isTTY)
  1311. this.stdin.setRawMode(true);
  1312. const keypress = (str, key) => {
  1313. if (key.name === "c" && key.ctrl === true) {
  1314. this.requestLayout();
  1315. this.view.detach(this);
  1316. this.tearDown(keypress);
  1317. if (terminateHandler) {
  1318. terminateHandler(this.stdin, this.stdout);
  1319. return;
  1320. }
  1321. this.stdout.write(`
  1322. ^C
  1323. `);
  1324. process.exit(1);
  1325. }
  1326. if (key.name === "escape") {
  1327. this.status = "aborted";
  1328. this.requestLayout();
  1329. this.view.detach(this);
  1330. this.tearDown(keypress);
  1331. this.resolve({ status: "aborted", data: void 0 });
  1332. return;
  1333. }
  1334. if (key.name === "return") {
  1335. this.status = "submitted";
  1336. this.requestLayout();
  1337. this.view.detach(this);
  1338. this.tearDown(keypress);
  1339. this.resolve({ status: "submitted", data: this.view.result() });
  1340. return;
  1341. }
  1342. view5.input(str, key);
  1343. };
  1344. this.stdin.on("keypress", keypress);
  1345. this.view.attach(this);
  1346. const { resolve: resolve2, promise } = (0, exports2.deferred)();
  1347. this.resolve = resolve2;
  1348. this.promise = promise;
  1349. this.renderFunc = (0, lodash_throttle_1.default)((str) => {
  1350. this.stdout.write(str);
  1351. });
  1352. }
  1353. tearDown(keypress) {
  1354. this.stdout.write(sisteransi_1.cursor.show);
  1355. this.stdin.removeListener("keypress", keypress);
  1356. if (this.stdin.isTTY)
  1357. this.stdin.setRawMode(false);
  1358. this.closable.close();
  1359. }
  1360. result() {
  1361. return this.promise;
  1362. }
  1363. toggleCursor(state2) {
  1364. if (state2 === "hide") {
  1365. this.stdout.write(sisteransi_1.cursor.hide);
  1366. } else {
  1367. this.stdout.write(sisteransi_1.cursor.show);
  1368. }
  1369. }
  1370. requestLayout() {
  1371. const string2 = this.view.render(this.status);
  1372. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  1373. this.text = string2;
  1374. this.renderFunc(`${clearPrefix}${string2}`);
  1375. }
  1376. };
  1377. exports2.Terminal = Terminal;
  1378. var TaskView2 = class {
  1379. constructor() {
  1380. this.attachCallbacks = [];
  1381. this.detachCallbacks = [];
  1382. }
  1383. requestLayout() {
  1384. this.terminal.requestLayout();
  1385. }
  1386. attach(terminal) {
  1387. this.terminal = terminal;
  1388. this.attachCallbacks.forEach((it) => it(terminal));
  1389. }
  1390. detach(terminal) {
  1391. this.detachCallbacks.forEach((it) => it(terminal));
  1392. this.terminal = void 0;
  1393. }
  1394. on(type, callback) {
  1395. if (type === "attach") {
  1396. this.attachCallbacks.push(callback);
  1397. } else if (type === "detach") {
  1398. this.detachCallbacks.push(callback);
  1399. }
  1400. }
  1401. };
  1402. exports2.TaskView = TaskView2;
  1403. var TaskTerminal = class {
  1404. constructor(view5, stdout) {
  1405. this.view = view5;
  1406. this.stdout = stdout;
  1407. this.text = "";
  1408. this.view.attach(this);
  1409. }
  1410. requestLayout() {
  1411. const string2 = this.view.render("pending");
  1412. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  1413. this.text = string2;
  1414. this.stdout.write(`${clearPrefix}${string2}`);
  1415. }
  1416. clear() {
  1417. const string2 = this.view.render("done");
  1418. this.view.detach(this);
  1419. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  1420. this.stdout.write(`${clearPrefix}${string2}`);
  1421. }
  1422. reject(err2) {
  1423. const string2 = this.view.render("rejected", err2);
  1424. this.view.detach(this);
  1425. const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
  1426. this.stdout.write(`${clearPrefix}${string2}`);
  1427. }
  1428. };
  1429. exports2.TaskTerminal = TaskTerminal;
  1430. function render10(view5) {
  1431. if (typeof view5 === "string") {
  1432. process.stdout.write(`${view5}
  1433. `);
  1434. return;
  1435. }
  1436. if (!process.stdin.isTTY || !process.stdout.isTTY) {
  1437. return Promise.reject(new Error("Interactive prompts require a TTY terminal (process.stdin.isTTY or process.stdout.isTTY is false). This can happen when running in CI, piped input, or non-interactive shells."));
  1438. }
  1439. const closable = (0, readline_1.createClosable)();
  1440. const terminal = new Terminal(view5, readline_1.stdin, readline_1.stdout, closable);
  1441. terminal.requestLayout();
  1442. return terminal.result();
  1443. }
  1444. function renderWithTask7(view5, task) {
  1445. return __awaiter2(this, void 0, void 0, function* () {
  1446. const terminal = new TaskTerminal(view5, process.stdout);
  1447. terminal.requestLayout();
  1448. try {
  1449. const result = yield task;
  1450. terminal.clear();
  1451. return result;
  1452. } catch (err2) {
  1453. terminal.reject(err2);
  1454. process.exit(1);
  1455. }
  1456. });
  1457. }
  1458. var terminateHandler;
  1459. function onTerminate(callback) {
  1460. terminateHandler = callback;
  1461. }
  1462. }
  1463. });
  1464. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js
  1465. var util, objectUtil, ZodParsedType, getParsedType;
  1466. var init_util = __esm({
  1467. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js"() {
  1468. (function(util2) {
  1469. util2.assertEqual = (_3) => {
  1470. };
  1471. function assertIs(_arg) {
  1472. }
  1473. util2.assertIs = assertIs;
  1474. function assertNever(_x) {
  1475. throw new Error();
  1476. }
  1477. util2.assertNever = assertNever;
  1478. util2.arrayToEnum = (items) => {
  1479. const obj = {};
  1480. for (const item of items) {
  1481. obj[item] = item;
  1482. }
  1483. return obj;
  1484. };
  1485. util2.getValidEnumValues = (obj) => {
  1486. const validKeys = util2.objectKeys(obj).filter((k3) => typeof obj[obj[k3]] !== "number");
  1487. const filtered = {};
  1488. for (const k3 of validKeys) {
  1489. filtered[k3] = obj[k3];
  1490. }
  1491. return util2.objectValues(filtered);
  1492. };
  1493. util2.objectValues = (obj) => {
  1494. return util2.objectKeys(obj).map(function(e4) {
  1495. return obj[e4];
  1496. });
  1497. };
  1498. util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
  1499. const keys = [];
  1500. for (const key in object) {
  1501. if (Object.prototype.hasOwnProperty.call(object, key)) {
  1502. keys.push(key);
  1503. }
  1504. }
  1505. return keys;
  1506. };
  1507. util2.find = (arr, checker) => {
  1508. for (const item of arr) {
  1509. if (checker(item))
  1510. return item;
  1511. }
  1512. return void 0;
  1513. };
  1514. util2.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2;
  1515. function joinValues(array2, separator = " | ") {
  1516. return array2.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator);
  1517. }
  1518. util2.joinValues = joinValues;
  1519. util2.jsonStringifyReplacer = (_3, value) => {
  1520. if (typeof value === "bigint") {
  1521. return value.toString();
  1522. }
  1523. return value;
  1524. };
  1525. })(util || (util = {}));
  1526. (function(objectUtil2) {
  1527. objectUtil2.mergeShapes = (first, second) => {
  1528. return {
  1529. ...first,
  1530. ...second
  1531. // second overwrites first
  1532. };
  1533. };
  1534. })(objectUtil || (objectUtil = {}));
  1535. ZodParsedType = util.arrayToEnum([
  1536. "string",
  1537. "nan",
  1538. "number",
  1539. "integer",
  1540. "float",
  1541. "boolean",
  1542. "date",
  1543. "bigint",
  1544. "symbol",
  1545. "function",
  1546. "undefined",
  1547. "null",
  1548. "array",
  1549. "object",
  1550. "unknown",
  1551. "promise",
  1552. "void",
  1553. "never",
  1554. "map",
  1555. "set"
  1556. ]);
  1557. getParsedType = (data) => {
  1558. const t4 = typeof data;
  1559. switch (t4) {
  1560. case "undefined":
  1561. return ZodParsedType.undefined;
  1562. case "string":
  1563. return ZodParsedType.string;
  1564. case "number":
  1565. return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
  1566. case "boolean":
  1567. return ZodParsedType.boolean;
  1568. case "function":
  1569. return ZodParsedType.function;
  1570. case "bigint":
  1571. return ZodParsedType.bigint;
  1572. case "symbol":
  1573. return ZodParsedType.symbol;
  1574. case "object":
  1575. if (Array.isArray(data)) {
  1576. return ZodParsedType.array;
  1577. }
  1578. if (data === null) {
  1579. return ZodParsedType.null;
  1580. }
  1581. if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
  1582. return ZodParsedType.promise;
  1583. }
  1584. if (typeof Map !== "undefined" && data instanceof Map) {
  1585. return ZodParsedType.map;
  1586. }
  1587. if (typeof Set !== "undefined" && data instanceof Set) {
  1588. return ZodParsedType.set;
  1589. }
  1590. if (typeof Date !== "undefined" && data instanceof Date) {
  1591. return ZodParsedType.date;
  1592. }
  1593. return ZodParsedType.object;
  1594. default:
  1595. return ZodParsedType.unknown;
  1596. }
  1597. };
  1598. }
  1599. });
  1600. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js
  1601. var ZodIssueCode, quotelessJson, ZodError;
  1602. var init_ZodError = __esm({
  1603. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js"() {
  1604. init_util();
  1605. ZodIssueCode = util.arrayToEnum([
  1606. "invalid_type",
  1607. "invalid_literal",
  1608. "custom",
  1609. "invalid_union",
  1610. "invalid_union_discriminator",
  1611. "invalid_enum_value",
  1612. "unrecognized_keys",
  1613. "invalid_arguments",
  1614. "invalid_return_type",
  1615. "invalid_date",
  1616. "invalid_string",
  1617. "too_small",
  1618. "too_big",
  1619. "invalid_intersection_types",
  1620. "not_multiple_of",
  1621. "not_finite"
  1622. ]);
  1623. quotelessJson = (obj) => {
  1624. const json = JSON.stringify(obj, null, 2);
  1625. return json.replace(/"([^"]+)":/g, "$1:");
  1626. };
  1627. ZodError = class _ZodError extends Error {
  1628. get errors() {
  1629. return this.issues;
  1630. }
  1631. constructor(issues) {
  1632. super();
  1633. this.issues = [];
  1634. this.addIssue = (sub) => {
  1635. this.issues = [...this.issues, sub];
  1636. };
  1637. this.addIssues = (subs = []) => {
  1638. this.issues = [...this.issues, ...subs];
  1639. };
  1640. const actualProto = new.target.prototype;
  1641. if (Object.setPrototypeOf) {
  1642. Object.setPrototypeOf(this, actualProto);
  1643. } else {
  1644. this.__proto__ = actualProto;
  1645. }
  1646. this.name = "ZodError";
  1647. this.issues = issues;
  1648. }
  1649. format(_mapper) {
  1650. const mapper = _mapper || function(issue) {
  1651. return issue.message;
  1652. };
  1653. const fieldErrors = { _errors: [] };
  1654. const processError = (error2) => {
  1655. for (const issue of error2.issues) {
  1656. if (issue.code === "invalid_union") {
  1657. issue.unionErrors.map(processError);
  1658. } else if (issue.code === "invalid_return_type") {
  1659. processError(issue.returnTypeError);
  1660. } else if (issue.code === "invalid_arguments") {
  1661. processError(issue.argumentsError);
  1662. } else if (issue.path.length === 0) {
  1663. fieldErrors._errors.push(mapper(issue));
  1664. } else {
  1665. let curr = fieldErrors;
  1666. let i4 = 0;
  1667. while (i4 < issue.path.length) {
  1668. const el = issue.path[i4];
  1669. const terminal = i4 === issue.path.length - 1;
  1670. if (!terminal) {
  1671. curr[el] = curr[el] || { _errors: [] };
  1672. } else {
  1673. curr[el] = curr[el] || { _errors: [] };
  1674. curr[el]._errors.push(mapper(issue));
  1675. }
  1676. curr = curr[el];
  1677. i4++;
  1678. }
  1679. }
  1680. }
  1681. };
  1682. processError(this);
  1683. return fieldErrors;
  1684. }
  1685. static assert(value) {
  1686. if (!(value instanceof _ZodError)) {
  1687. throw new Error(`Not a ZodError: ${value}`);
  1688. }
  1689. }
  1690. toString() {
  1691. return this.message;
  1692. }
  1693. get message() {
  1694. return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  1695. }
  1696. get isEmpty() {
  1697. return this.issues.length === 0;
  1698. }
  1699. flatten(mapper = (issue) => issue.message) {
  1700. const fieldErrors = {};
  1701. const formErrors = [];
  1702. for (const sub of this.issues) {
  1703. if (sub.path.length > 0) {
  1704. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
  1705. fieldErrors[sub.path[0]].push(mapper(sub));
  1706. } else {
  1707. formErrors.push(mapper(sub));
  1708. }
  1709. }
  1710. return { formErrors, fieldErrors };
  1711. }
  1712. get formErrors() {
  1713. return this.flatten();
  1714. }
  1715. };
  1716. ZodError.create = (issues) => {
  1717. const error2 = new ZodError(issues);
  1718. return error2;
  1719. };
  1720. }
  1721. });
  1722. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js
  1723. var errorMap, en_default;
  1724. var init_en = __esm({
  1725. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js"() {
  1726. init_ZodError();
  1727. init_util();
  1728. errorMap = (issue, _ctx) => {
  1729. let message;
  1730. switch (issue.code) {
  1731. case ZodIssueCode.invalid_type:
  1732. if (issue.received === ZodParsedType.undefined) {
  1733. message = "Required";
  1734. } else {
  1735. message = `Expected ${issue.expected}, received ${issue.received}`;
  1736. }
  1737. break;
  1738. case ZodIssueCode.invalid_literal:
  1739. message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
  1740. break;
  1741. case ZodIssueCode.unrecognized_keys:
  1742. message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
  1743. break;
  1744. case ZodIssueCode.invalid_union:
  1745. message = `Invalid input`;
  1746. break;
  1747. case ZodIssueCode.invalid_union_discriminator:
  1748. message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
  1749. break;
  1750. case ZodIssueCode.invalid_enum_value:
  1751. message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
  1752. break;
  1753. case ZodIssueCode.invalid_arguments:
  1754. message = `Invalid function arguments`;
  1755. break;
  1756. case ZodIssueCode.invalid_return_type:
  1757. message = `Invalid function return type`;
  1758. break;
  1759. case ZodIssueCode.invalid_date:
  1760. message = `Invalid date`;
  1761. break;
  1762. case ZodIssueCode.invalid_string:
  1763. if (typeof issue.validation === "object") {
  1764. if ("includes" in issue.validation) {
  1765. message = `Invalid input: must include "${issue.validation.includes}"`;
  1766. if (typeof issue.validation.position === "number") {
  1767. message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
  1768. }
  1769. } else if ("startsWith" in issue.validation) {
  1770. message = `Invalid input: must start with "${issue.validation.startsWith}"`;
  1771. } else if ("endsWith" in issue.validation) {
  1772. message = `Invalid input: must end with "${issue.validation.endsWith}"`;
  1773. } else {
  1774. util.assertNever(issue.validation);
  1775. }
  1776. } else if (issue.validation !== "regex") {
  1777. message = `Invalid ${issue.validation}`;
  1778. } else {
  1779. message = "Invalid";
  1780. }
  1781. break;
  1782. case ZodIssueCode.too_small:
  1783. if (issue.type === "array")
  1784. message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
  1785. else if (issue.type === "string")
  1786. message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
  1787. else if (issue.type === "number")
  1788. message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
  1789. else if (issue.type === "date")
  1790. message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
  1791. else
  1792. message = "Invalid input";
  1793. break;
  1794. case ZodIssueCode.too_big:
  1795. if (issue.type === "array")
  1796. message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
  1797. else if (issue.type === "string")
  1798. message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
  1799. else if (issue.type === "number")
  1800. message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
  1801. else if (issue.type === "bigint")
  1802. message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
  1803. else if (issue.type === "date")
  1804. message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
  1805. else
  1806. message = "Invalid input";
  1807. break;
  1808. case ZodIssueCode.custom:
  1809. message = `Invalid input`;
  1810. break;
  1811. case ZodIssueCode.invalid_intersection_types:
  1812. message = `Intersection results could not be merged`;
  1813. break;
  1814. case ZodIssueCode.not_multiple_of:
  1815. message = `Number must be a multiple of ${issue.multipleOf}`;
  1816. break;
  1817. case ZodIssueCode.not_finite:
  1818. message = "Number must be finite";
  1819. break;
  1820. default:
  1821. message = _ctx.defaultError;
  1822. util.assertNever(issue);
  1823. }
  1824. return { message };
  1825. };
  1826. en_default = errorMap;
  1827. }
  1828. });
  1829. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js
  1830. function setErrorMap(map2) {
  1831. overrideErrorMap = map2;
  1832. }
  1833. function getErrorMap() {
  1834. return overrideErrorMap;
  1835. }
  1836. var overrideErrorMap;
  1837. var init_errors = __esm({
  1838. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js"() {
  1839. init_en();
  1840. overrideErrorMap = en_default;
  1841. }
  1842. });
  1843. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js
  1844. function addIssueToContext(ctx, issueData) {
  1845. const overrideMap = getErrorMap();
  1846. const issue = makeIssue({
  1847. issueData,
  1848. data: ctx.data,
  1849. path: ctx.path,
  1850. errorMaps: [
  1851. ctx.common.contextualErrorMap,
  1852. // contextual error map is first priority
  1853. ctx.schemaErrorMap,
  1854. // then schema-bound map if available
  1855. overrideMap,
  1856. // then global override map
  1857. overrideMap === en_default ? void 0 : en_default
  1858. // then global default map
  1859. ].filter((x4) => !!x4)
  1860. });
  1861. ctx.common.issues.push(issue);
  1862. }
  1863. var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync;
  1864. var init_parseUtil = __esm({
  1865. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js"() {
  1866. init_errors();
  1867. init_en();
  1868. makeIssue = (params) => {
  1869. const { data, path: path4, errorMaps, issueData } = params;
  1870. const fullPath = [...path4, ...issueData.path || []];
  1871. const fullIssue = {
  1872. ...issueData,
  1873. path: fullPath
  1874. };
  1875. if (issueData.message !== void 0) {
  1876. return {
  1877. ...issueData,
  1878. path: fullPath,
  1879. message: issueData.message
  1880. };
  1881. }
  1882. let errorMessage = "";
  1883. const maps = errorMaps.filter((m4) => !!m4).slice().reverse();
  1884. for (const map2 of maps) {
  1885. errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
  1886. }
  1887. return {
  1888. ...issueData,
  1889. path: fullPath,
  1890. message: errorMessage
  1891. };
  1892. };
  1893. EMPTY_PATH = [];
  1894. ParseStatus = class _ParseStatus {
  1895. constructor() {
  1896. this.value = "valid";
  1897. }
  1898. dirty() {
  1899. if (this.value === "valid")
  1900. this.value = "dirty";
  1901. }
  1902. abort() {
  1903. if (this.value !== "aborted")
  1904. this.value = "aborted";
  1905. }
  1906. static mergeArray(status, results) {
  1907. const arrayValue = [];
  1908. for (const s4 of results) {
  1909. if (s4.status === "aborted")
  1910. return INVALID;
  1911. if (s4.status === "dirty")
  1912. status.dirty();
  1913. arrayValue.push(s4.value);
  1914. }
  1915. return { status: status.value, value: arrayValue };
  1916. }
  1917. static async mergeObjectAsync(status, pairs) {
  1918. const syncPairs = [];
  1919. for (const pair of pairs) {
  1920. const key = await pair.key;
  1921. const value = await pair.value;
  1922. syncPairs.push({
  1923. key,
  1924. value
  1925. });
  1926. }
  1927. return _ParseStatus.mergeObjectSync(status, syncPairs);
  1928. }
  1929. static mergeObjectSync(status, pairs) {
  1930. const finalObject = {};
  1931. for (const pair of pairs) {
  1932. const { key, value } = pair;
  1933. if (key.status === "aborted")
  1934. return INVALID;
  1935. if (value.status === "aborted")
  1936. return INVALID;
  1937. if (key.status === "dirty")
  1938. status.dirty();
  1939. if (value.status === "dirty")
  1940. status.dirty();
  1941. if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
  1942. finalObject[key.value] = value.value;
  1943. }
  1944. }
  1945. return { status: status.value, value: finalObject };
  1946. }
  1947. };
  1948. INVALID = Object.freeze({
  1949. status: "aborted"
  1950. });
  1951. DIRTY = (value) => ({ status: "dirty", value });
  1952. OK = (value) => ({ status: "valid", value });
  1953. isAborted = (x4) => x4.status === "aborted";
  1954. isDirty = (x4) => x4.status === "dirty";
  1955. isValid = (x4) => x4.status === "valid";
  1956. isAsync = (x4) => typeof Promise !== "undefined" && x4 instanceof Promise;
  1957. }
  1958. });
  1959. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js
  1960. var init_typeAliases = __esm({
  1961. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js"() {
  1962. }
  1963. });
  1964. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js
  1965. var errorUtil;
  1966. var init_errorUtil = __esm({
  1967. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js"() {
  1968. (function(errorUtil2) {
  1969. errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  1970. errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message;
  1971. })(errorUtil || (errorUtil = {}));
  1972. }
  1973. });
  1974. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js
  1975. function processCreateParams(params) {
  1976. if (!params)
  1977. return {};
  1978. const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  1979. if (errorMap2 && (invalid_type_error || required_error)) {
  1980. throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  1981. }
  1982. if (errorMap2)
  1983. return { errorMap: errorMap2, description };
  1984. const customMap = (iss, ctx) => {
  1985. const { message } = params;
  1986. if (iss.code === "invalid_enum_value") {
  1987. return { message: message ?? ctx.defaultError };
  1988. }
  1989. if (typeof ctx.data === "undefined") {
  1990. return { message: message ?? required_error ?? ctx.defaultError };
  1991. }
  1992. if (iss.code !== "invalid_type")
  1993. return { message: ctx.defaultError };
  1994. return { message: message ?? invalid_type_error ?? ctx.defaultError };
  1995. };
  1996. return { errorMap: customMap, description };
  1997. }
  1998. function timeRegexSource(args) {
  1999. let secondsRegexSource = `[0-5]\\d`;
  2000. if (args.precision) {
  2001. secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  2002. } else if (args.precision == null) {
  2003. secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  2004. }
  2005. const secondsQuantifier = args.precision ? "+" : "?";
  2006. return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
  2007. }
  2008. function timeRegex(args) {
  2009. return new RegExp(`^${timeRegexSource(args)}$`);
  2010. }
  2011. function datetimeRegex(args) {
  2012. let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  2013. const opts = [];
  2014. opts.push(args.local ? `Z?` : `Z`);
  2015. if (args.offset)
  2016. opts.push(`([+-]\\d{2}:?\\d{2})`);
  2017. regex = `${regex}(${opts.join("|")})`;
  2018. return new RegExp(`^${regex}$`);
  2019. }
  2020. function isValidIP(ip, version3) {
  2021. if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) {
  2022. return true;
  2023. }
  2024. if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) {
  2025. return true;
  2026. }
  2027. return false;
  2028. }
  2029. function isValidJWT(jwt, alg) {
  2030. if (!jwtRegex.test(jwt))
  2031. return false;
  2032. try {
  2033. const [header] = jwt.split(".");
  2034. const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
  2035. const decoded = JSON.parse(atob(base64));
  2036. if (typeof decoded !== "object" || decoded === null)
  2037. return false;
  2038. if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT")
  2039. return false;
  2040. if (!decoded.alg)
  2041. return false;
  2042. if (alg && decoded.alg !== alg)
  2043. return false;
  2044. return true;
  2045. } catch {
  2046. return false;
  2047. }
  2048. }
  2049. function isValidCidr(ip, version3) {
  2050. if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) {
  2051. return true;
  2052. }
  2053. if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) {
  2054. return true;
  2055. }
  2056. return false;
  2057. }
  2058. function floatSafeRemainder(val2, step) {
  2059. const valDecCount = (val2.toString().split(".")[1] || "").length;
  2060. const stepDecCount = (step.toString().split(".")[1] || "").length;
  2061. const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  2062. const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", ""));
  2063. const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  2064. return valInt % stepInt / 10 ** decCount;
  2065. }
  2066. function deepPartialify(schema6) {
  2067. if (schema6 instanceof ZodObject) {
  2068. const newShape = {};
  2069. for (const key in schema6.shape) {
  2070. const fieldSchema = schema6.shape[key];
  2071. newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
  2072. }
  2073. return new ZodObject({
  2074. ...schema6._def,
  2075. shape: () => newShape
  2076. });
  2077. } else if (schema6 instanceof ZodArray) {
  2078. return new ZodArray({
  2079. ...schema6._def,
  2080. type: deepPartialify(schema6.element)
  2081. });
  2082. } else if (schema6 instanceof ZodOptional) {
  2083. return ZodOptional.create(deepPartialify(schema6.unwrap()));
  2084. } else if (schema6 instanceof ZodNullable) {
  2085. return ZodNullable.create(deepPartialify(schema6.unwrap()));
  2086. } else if (schema6 instanceof ZodTuple) {
  2087. return ZodTuple.create(schema6.items.map((item) => deepPartialify(item)));
  2088. } else {
  2089. return schema6;
  2090. }
  2091. }
  2092. function mergeValues(a3, b3) {
  2093. const aType = getParsedType(a3);
  2094. const bType = getParsedType(b3);
  2095. if (a3 === b3) {
  2096. return { valid: true, data: a3 };
  2097. } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
  2098. const bKeys = util.objectKeys(b3);
  2099. const sharedKeys = util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1);
  2100. const newObj = { ...a3, ...b3 };
  2101. for (const key of sharedKeys) {
  2102. const sharedValue = mergeValues(a3[key], b3[key]);
  2103. if (!sharedValue.valid) {
  2104. return { valid: false };
  2105. }
  2106. newObj[key] = sharedValue.data;
  2107. }
  2108. return { valid: true, data: newObj };
  2109. } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
  2110. if (a3.length !== b3.length) {
  2111. return { valid: false };
  2112. }
  2113. const newArray = [];
  2114. for (let index6 = 0; index6 < a3.length; index6++) {
  2115. const itemA = a3[index6];
  2116. const itemB = b3[index6];
  2117. const sharedValue = mergeValues(itemA, itemB);
  2118. if (!sharedValue.valid) {
  2119. return { valid: false };
  2120. }
  2121. newArray.push(sharedValue.data);
  2122. }
  2123. return { valid: true, data: newArray };
  2124. } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a3 === +b3) {
  2125. return { valid: true, data: a3 };
  2126. } else {
  2127. return { valid: false };
  2128. }
  2129. }
  2130. function createZodEnum(values, params) {
  2131. return new ZodEnum({
  2132. values,
  2133. typeName: ZodFirstPartyTypeKind.ZodEnum,
  2134. ...processCreateParams(params)
  2135. });
  2136. }
  2137. function cleanParams(params, data) {
  2138. const p3 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  2139. const p22 = typeof p3 === "string" ? { message: p3 } : p3;
  2140. return p22;
  2141. }
  2142. function custom(check2, _params = {}, fatal) {
  2143. if (check2)
  2144. return ZodAny.create().superRefine((data, ctx) => {
  2145. const r4 = check2(data);
  2146. if (r4 instanceof Promise) {
  2147. return r4.then((r5) => {
  2148. if (!r5) {
  2149. const params = cleanParams(_params, data);
  2150. const _fatal = params.fatal ?? fatal ?? true;
  2151. ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
  2152. }
  2153. });
  2154. }
  2155. if (!r4) {
  2156. const params = cleanParams(_params, data);
  2157. const _fatal = params.fatal ?? fatal ?? true;
  2158. ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
  2159. }
  2160. return;
  2161. });
  2162. return ZodAny.create();
  2163. }
  2164. var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER;
  2165. var init_types = __esm({
  2166. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js"() {
  2167. init_ZodError();
  2168. init_errors();
  2169. init_errorUtil();
  2170. init_parseUtil();
  2171. init_util();
  2172. ParseInputLazyPath = class {
  2173. constructor(parent, value, path4, key) {
  2174. this._cachedPath = [];
  2175. this.parent = parent;
  2176. this.data = value;
  2177. this._path = path4;
  2178. this._key = key;
  2179. }
  2180. get path() {
  2181. if (!this._cachedPath.length) {
  2182. if (Array.isArray(this._key)) {
  2183. this._cachedPath.push(...this._path, ...this._key);
  2184. } else {
  2185. this._cachedPath.push(...this._path, this._key);
  2186. }
  2187. }
  2188. return this._cachedPath;
  2189. }
  2190. };
  2191. handleResult = (ctx, result) => {
  2192. if (isValid(result)) {
  2193. return { success: true, data: result.value };
  2194. } else {
  2195. if (!ctx.common.issues.length) {
  2196. throw new Error("Validation failed but no issues detected.");
  2197. }
  2198. return {
  2199. success: false,
  2200. get error() {
  2201. if (this._error)
  2202. return this._error;
  2203. const error2 = new ZodError(ctx.common.issues);
  2204. this._error = error2;
  2205. return this._error;
  2206. }
  2207. };
  2208. }
  2209. };
  2210. ZodType = class {
  2211. get description() {
  2212. return this._def.description;
  2213. }
  2214. _getType(input) {
  2215. return getParsedType(input.data);
  2216. }
  2217. _getOrReturnCtx(input, ctx) {
  2218. return ctx || {
  2219. common: input.parent.common,
  2220. data: input.data,
  2221. parsedType: getParsedType(input.data),
  2222. schemaErrorMap: this._def.errorMap,
  2223. path: input.path,
  2224. parent: input.parent
  2225. };
  2226. }
  2227. _processInputParams(input) {
  2228. return {
  2229. status: new ParseStatus(),
  2230. ctx: {
  2231. common: input.parent.common,
  2232. data: input.data,
  2233. parsedType: getParsedType(input.data),
  2234. schemaErrorMap: this._def.errorMap,
  2235. path: input.path,
  2236. parent: input.parent
  2237. }
  2238. };
  2239. }
  2240. _parseSync(input) {
  2241. const result = this._parse(input);
  2242. if (isAsync(result)) {
  2243. throw new Error("Synchronous parse encountered promise.");
  2244. }
  2245. return result;
  2246. }
  2247. _parseAsync(input) {
  2248. const result = this._parse(input);
  2249. return Promise.resolve(result);
  2250. }
  2251. parse(data, params) {
  2252. const result = this.safeParse(data, params);
  2253. if (result.success)
  2254. return result.data;
  2255. throw result.error;
  2256. }
  2257. safeParse(data, params) {
  2258. const ctx = {
  2259. common: {
  2260. issues: [],
  2261. async: (params == null ? void 0 : params.async) ?? false,
  2262. contextualErrorMap: params == null ? void 0 : params.errorMap
  2263. },
  2264. path: (params == null ? void 0 : params.path) || [],
  2265. schemaErrorMap: this._def.errorMap,
  2266. parent: null,
  2267. data,
  2268. parsedType: getParsedType(data)
  2269. };
  2270. const result = this._parseSync({ data, path: ctx.path, parent: ctx });
  2271. return handleResult(ctx, result);
  2272. }
  2273. "~validate"(data) {
  2274. var _a2, _b;
  2275. const ctx = {
  2276. common: {
  2277. issues: [],
  2278. async: !!this["~standard"].async
  2279. },
  2280. path: [],
  2281. schemaErrorMap: this._def.errorMap,
  2282. parent: null,
  2283. data,
  2284. parsedType: getParsedType(data)
  2285. };
  2286. if (!this["~standard"].async) {
  2287. try {
  2288. const result = this._parseSync({ data, path: [], parent: ctx });
  2289. return isValid(result) ? {
  2290. value: result.value
  2291. } : {
  2292. issues: ctx.common.issues
  2293. };
  2294. } catch (err2) {
  2295. if ((_b = (_a2 = err2 == null ? void 0 : err2.message) == null ? void 0 : _a2.toLowerCase()) == null ? void 0 : _b.includes("encountered")) {
  2296. this["~standard"].async = true;
  2297. }
  2298. ctx.common = {
  2299. issues: [],
  2300. async: true
  2301. };
  2302. }
  2303. }
  2304. return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
  2305. value: result.value
  2306. } : {
  2307. issues: ctx.common.issues
  2308. });
  2309. }
  2310. async parseAsync(data, params) {
  2311. const result = await this.safeParseAsync(data, params);
  2312. if (result.success)
  2313. return result.data;
  2314. throw result.error;
  2315. }
  2316. async safeParseAsync(data, params) {
  2317. const ctx = {
  2318. common: {
  2319. issues: [],
  2320. contextualErrorMap: params == null ? void 0 : params.errorMap,
  2321. async: true
  2322. },
  2323. path: (params == null ? void 0 : params.path) || [],
  2324. schemaErrorMap: this._def.errorMap,
  2325. parent: null,
  2326. data,
  2327. parsedType: getParsedType(data)
  2328. };
  2329. const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
  2330. const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
  2331. return handleResult(ctx, result);
  2332. }
  2333. refine(check2, message) {
  2334. const getIssueProperties = (val2) => {
  2335. if (typeof message === "string" || typeof message === "undefined") {
  2336. return { message };
  2337. } else if (typeof message === "function") {
  2338. return message(val2);
  2339. } else {
  2340. return message;
  2341. }
  2342. };
  2343. return this._refinement((val2, ctx) => {
  2344. const result = check2(val2);
  2345. const setError = () => ctx.addIssue({
  2346. code: ZodIssueCode.custom,
  2347. ...getIssueProperties(val2)
  2348. });
  2349. if (typeof Promise !== "undefined" && result instanceof Promise) {
  2350. return result.then((data) => {
  2351. if (!data) {
  2352. setError();
  2353. return false;
  2354. } else {
  2355. return true;
  2356. }
  2357. });
  2358. }
  2359. if (!result) {
  2360. setError();
  2361. return false;
  2362. } else {
  2363. return true;
  2364. }
  2365. });
  2366. }
  2367. refinement(check2, refinementData) {
  2368. return this._refinement((val2, ctx) => {
  2369. if (!check2(val2)) {
  2370. ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData);
  2371. return false;
  2372. } else {
  2373. return true;
  2374. }
  2375. });
  2376. }
  2377. _refinement(refinement) {
  2378. return new ZodEffects({
  2379. schema: this,
  2380. typeName: ZodFirstPartyTypeKind.ZodEffects,
  2381. effect: { type: "refinement", refinement }
  2382. });
  2383. }
  2384. superRefine(refinement) {
  2385. return this._refinement(refinement);
  2386. }
  2387. constructor(def) {
  2388. this.spa = this.safeParseAsync;
  2389. this._def = def;
  2390. this.parse = this.parse.bind(this);
  2391. this.safeParse = this.safeParse.bind(this);
  2392. this.parseAsync = this.parseAsync.bind(this);
  2393. this.safeParseAsync = this.safeParseAsync.bind(this);
  2394. this.spa = this.spa.bind(this);
  2395. this.refine = this.refine.bind(this);
  2396. this.refinement = this.refinement.bind(this);
  2397. this.superRefine = this.superRefine.bind(this);
  2398. this.optional = this.optional.bind(this);
  2399. this.nullable = this.nullable.bind(this);
  2400. this.nullish = this.nullish.bind(this);
  2401. this.array = this.array.bind(this);
  2402. this.promise = this.promise.bind(this);
  2403. this.or = this.or.bind(this);
  2404. this.and = this.and.bind(this);
  2405. this.transform = this.transform.bind(this);
  2406. this.brand = this.brand.bind(this);
  2407. this.default = this.default.bind(this);
  2408. this.catch = this.catch.bind(this);
  2409. this.describe = this.describe.bind(this);
  2410. this.pipe = this.pipe.bind(this);
  2411. this.readonly = this.readonly.bind(this);
  2412. this.isNullable = this.isNullable.bind(this);
  2413. this.isOptional = this.isOptional.bind(this);
  2414. this["~standard"] = {
  2415. version: 1,
  2416. vendor: "zod",
  2417. validate: (data) => this["~validate"](data)
  2418. };
  2419. }
  2420. optional() {
  2421. return ZodOptional.create(this, this._def);
  2422. }
  2423. nullable() {
  2424. return ZodNullable.create(this, this._def);
  2425. }
  2426. nullish() {
  2427. return this.nullable().optional();
  2428. }
  2429. array() {
  2430. return ZodArray.create(this);
  2431. }
  2432. promise() {
  2433. return ZodPromise.create(this, this._def);
  2434. }
  2435. or(option) {
  2436. return ZodUnion.create([this, option], this._def);
  2437. }
  2438. and(incoming) {
  2439. return ZodIntersection.create(this, incoming, this._def);
  2440. }
  2441. transform(transform) {
  2442. return new ZodEffects({
  2443. ...processCreateParams(this._def),
  2444. schema: this,
  2445. typeName: ZodFirstPartyTypeKind.ZodEffects,
  2446. effect: { type: "transform", transform }
  2447. });
  2448. }
  2449. default(def) {
  2450. const defaultValueFunc = typeof def === "function" ? def : () => def;
  2451. return new ZodDefault({
  2452. ...processCreateParams(this._def),
  2453. innerType: this,
  2454. defaultValue: defaultValueFunc,
  2455. typeName: ZodFirstPartyTypeKind.ZodDefault
  2456. });
  2457. }
  2458. brand() {
  2459. return new ZodBranded({
  2460. typeName: ZodFirstPartyTypeKind.ZodBranded,
  2461. type: this,
  2462. ...processCreateParams(this._def)
  2463. });
  2464. }
  2465. catch(def) {
  2466. const catchValueFunc = typeof def === "function" ? def : () => def;
  2467. return new ZodCatch({
  2468. ...processCreateParams(this._def),
  2469. innerType: this,
  2470. catchValue: catchValueFunc,
  2471. typeName: ZodFirstPartyTypeKind.ZodCatch
  2472. });
  2473. }
  2474. describe(description) {
  2475. const This = this.constructor;
  2476. return new This({
  2477. ...this._def,
  2478. description
  2479. });
  2480. }
  2481. pipe(target) {
  2482. return ZodPipeline.create(this, target);
  2483. }
  2484. readonly() {
  2485. return ZodReadonly.create(this);
  2486. }
  2487. isOptional() {
  2488. return this.safeParse(void 0).success;
  2489. }
  2490. isNullable() {
  2491. return this.safeParse(null).success;
  2492. }
  2493. };
  2494. cuidRegex = /^c[^\s-]{8,}$/i;
  2495. cuid2Regex = /^[0-9a-z]+$/;
  2496. ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
  2497. uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
  2498. nanoidRegex = /^[a-z0-9_-]{21}$/i;
  2499. jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
  2500. durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
  2501. emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
  2502. _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
  2503. ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
  2504. ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
  2505. ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
  2506. ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
  2507. base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
  2508. base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
  2509. dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
  2510. dateRegex = new RegExp(`^${dateRegexSource}$`);
  2511. ZodString = class _ZodString extends ZodType {
  2512. _parse(input) {
  2513. if (this._def.coerce) {
  2514. input.data = String(input.data);
  2515. }
  2516. const parsedType = this._getType(input);
  2517. if (parsedType !== ZodParsedType.string) {
  2518. const ctx2 = this._getOrReturnCtx(input);
  2519. addIssueToContext(ctx2, {
  2520. code: ZodIssueCode.invalid_type,
  2521. expected: ZodParsedType.string,
  2522. received: ctx2.parsedType
  2523. });
  2524. return INVALID;
  2525. }
  2526. const status = new ParseStatus();
  2527. let ctx = void 0;
  2528. for (const check2 of this._def.checks) {
  2529. if (check2.kind === "min") {
  2530. if (input.data.length < check2.value) {
  2531. ctx = this._getOrReturnCtx(input, ctx);
  2532. addIssueToContext(ctx, {
  2533. code: ZodIssueCode.too_small,
  2534. minimum: check2.value,
  2535. type: "string",
  2536. inclusive: true,
  2537. exact: false,
  2538. message: check2.message
  2539. });
  2540. status.dirty();
  2541. }
  2542. } else if (check2.kind === "max") {
  2543. if (input.data.length > check2.value) {
  2544. ctx = this._getOrReturnCtx(input, ctx);
  2545. addIssueToContext(ctx, {
  2546. code: ZodIssueCode.too_big,
  2547. maximum: check2.value,
  2548. type: "string",
  2549. inclusive: true,
  2550. exact: false,
  2551. message: check2.message
  2552. });
  2553. status.dirty();
  2554. }
  2555. } else if (check2.kind === "length") {
  2556. const tooBig = input.data.length > check2.value;
  2557. const tooSmall = input.data.length < check2.value;
  2558. if (tooBig || tooSmall) {
  2559. ctx = this._getOrReturnCtx(input, ctx);
  2560. if (tooBig) {
  2561. addIssueToContext(ctx, {
  2562. code: ZodIssueCode.too_big,
  2563. maximum: check2.value,
  2564. type: "string",
  2565. inclusive: true,
  2566. exact: true,
  2567. message: check2.message
  2568. });
  2569. } else if (tooSmall) {
  2570. addIssueToContext(ctx, {
  2571. code: ZodIssueCode.too_small,
  2572. minimum: check2.value,
  2573. type: "string",
  2574. inclusive: true,
  2575. exact: true,
  2576. message: check2.message
  2577. });
  2578. }
  2579. status.dirty();
  2580. }
  2581. } else if (check2.kind === "email") {
  2582. if (!emailRegex.test(input.data)) {
  2583. ctx = this._getOrReturnCtx(input, ctx);
  2584. addIssueToContext(ctx, {
  2585. validation: "email",
  2586. code: ZodIssueCode.invalid_string,
  2587. message: check2.message
  2588. });
  2589. status.dirty();
  2590. }
  2591. } else if (check2.kind === "emoji") {
  2592. if (!emojiRegex) {
  2593. emojiRegex = new RegExp(_emojiRegex, "u");
  2594. }
  2595. if (!emojiRegex.test(input.data)) {
  2596. ctx = this._getOrReturnCtx(input, ctx);
  2597. addIssueToContext(ctx, {
  2598. validation: "emoji",
  2599. code: ZodIssueCode.invalid_string,
  2600. message: check2.message
  2601. });
  2602. status.dirty();
  2603. }
  2604. } else if (check2.kind === "uuid") {
  2605. if (!uuidRegex.test(input.data)) {
  2606. ctx = this._getOrReturnCtx(input, ctx);
  2607. addIssueToContext(ctx, {
  2608. validation: "uuid",
  2609. code: ZodIssueCode.invalid_string,
  2610. message: check2.message
  2611. });
  2612. status.dirty();
  2613. }
  2614. } else if (check2.kind === "nanoid") {
  2615. if (!nanoidRegex.test(input.data)) {
  2616. ctx = this._getOrReturnCtx(input, ctx);
  2617. addIssueToContext(ctx, {
  2618. validation: "nanoid",
  2619. code: ZodIssueCode.invalid_string,
  2620. message: check2.message
  2621. });
  2622. status.dirty();
  2623. }
  2624. } else if (check2.kind === "cuid") {
  2625. if (!cuidRegex.test(input.data)) {
  2626. ctx = this._getOrReturnCtx(input, ctx);
  2627. addIssueToContext(ctx, {
  2628. validation: "cuid",
  2629. code: ZodIssueCode.invalid_string,
  2630. message: check2.message
  2631. });
  2632. status.dirty();
  2633. }
  2634. } else if (check2.kind === "cuid2") {
  2635. if (!cuid2Regex.test(input.data)) {
  2636. ctx = this._getOrReturnCtx(input, ctx);
  2637. addIssueToContext(ctx, {
  2638. validation: "cuid2",
  2639. code: ZodIssueCode.invalid_string,
  2640. message: check2.message
  2641. });
  2642. status.dirty();
  2643. }
  2644. } else if (check2.kind === "ulid") {
  2645. if (!ulidRegex.test(input.data)) {
  2646. ctx = this._getOrReturnCtx(input, ctx);
  2647. addIssueToContext(ctx, {
  2648. validation: "ulid",
  2649. code: ZodIssueCode.invalid_string,
  2650. message: check2.message
  2651. });
  2652. status.dirty();
  2653. }
  2654. } else if (check2.kind === "url") {
  2655. try {
  2656. new URL(input.data);
  2657. } catch {
  2658. ctx = this._getOrReturnCtx(input, ctx);
  2659. addIssueToContext(ctx, {
  2660. validation: "url",
  2661. code: ZodIssueCode.invalid_string,
  2662. message: check2.message
  2663. });
  2664. status.dirty();
  2665. }
  2666. } else if (check2.kind === "regex") {
  2667. check2.regex.lastIndex = 0;
  2668. const testResult = check2.regex.test(input.data);
  2669. if (!testResult) {
  2670. ctx = this._getOrReturnCtx(input, ctx);
  2671. addIssueToContext(ctx, {
  2672. validation: "regex",
  2673. code: ZodIssueCode.invalid_string,
  2674. message: check2.message
  2675. });
  2676. status.dirty();
  2677. }
  2678. } else if (check2.kind === "trim") {
  2679. input.data = input.data.trim();
  2680. } else if (check2.kind === "includes") {
  2681. if (!input.data.includes(check2.value, check2.position)) {
  2682. ctx = this._getOrReturnCtx(input, ctx);
  2683. addIssueToContext(ctx, {
  2684. code: ZodIssueCode.invalid_string,
  2685. validation: { includes: check2.value, position: check2.position },
  2686. message: check2.message
  2687. });
  2688. status.dirty();
  2689. }
  2690. } else if (check2.kind === "toLowerCase") {
  2691. input.data = input.data.toLowerCase();
  2692. } else if (check2.kind === "toUpperCase") {
  2693. input.data = input.data.toUpperCase();
  2694. } else if (check2.kind === "startsWith") {
  2695. if (!input.data.startsWith(check2.value)) {
  2696. ctx = this._getOrReturnCtx(input, ctx);
  2697. addIssueToContext(ctx, {
  2698. code: ZodIssueCode.invalid_string,
  2699. validation: { startsWith: check2.value },
  2700. message: check2.message
  2701. });
  2702. status.dirty();
  2703. }
  2704. } else if (check2.kind === "endsWith") {
  2705. if (!input.data.endsWith(check2.value)) {
  2706. ctx = this._getOrReturnCtx(input, ctx);
  2707. addIssueToContext(ctx, {
  2708. code: ZodIssueCode.invalid_string,
  2709. validation: { endsWith: check2.value },
  2710. message: check2.message
  2711. });
  2712. status.dirty();
  2713. }
  2714. } else if (check2.kind === "datetime") {
  2715. const regex = datetimeRegex(check2);
  2716. if (!regex.test(input.data)) {
  2717. ctx = this._getOrReturnCtx(input, ctx);
  2718. addIssueToContext(ctx, {
  2719. code: ZodIssueCode.invalid_string,
  2720. validation: "datetime",
  2721. message: check2.message
  2722. });
  2723. status.dirty();
  2724. }
  2725. } else if (check2.kind === "date") {
  2726. const regex = dateRegex;
  2727. if (!regex.test(input.data)) {
  2728. ctx = this._getOrReturnCtx(input, ctx);
  2729. addIssueToContext(ctx, {
  2730. code: ZodIssueCode.invalid_string,
  2731. validation: "date",
  2732. message: check2.message
  2733. });
  2734. status.dirty();
  2735. }
  2736. } else if (check2.kind === "time") {
  2737. const regex = timeRegex(check2);
  2738. if (!regex.test(input.data)) {
  2739. ctx = this._getOrReturnCtx(input, ctx);
  2740. addIssueToContext(ctx, {
  2741. code: ZodIssueCode.invalid_string,
  2742. validation: "time",
  2743. message: check2.message
  2744. });
  2745. status.dirty();
  2746. }
  2747. } else if (check2.kind === "duration") {
  2748. if (!durationRegex.test(input.data)) {
  2749. ctx = this._getOrReturnCtx(input, ctx);
  2750. addIssueToContext(ctx, {
  2751. validation: "duration",
  2752. code: ZodIssueCode.invalid_string,
  2753. message: check2.message
  2754. });
  2755. status.dirty();
  2756. }
  2757. } else if (check2.kind === "ip") {
  2758. if (!isValidIP(input.data, check2.version)) {
  2759. ctx = this._getOrReturnCtx(input, ctx);
  2760. addIssueToContext(ctx, {
  2761. validation: "ip",
  2762. code: ZodIssueCode.invalid_string,
  2763. message: check2.message
  2764. });
  2765. status.dirty();
  2766. }
  2767. } else if (check2.kind === "jwt") {
  2768. if (!isValidJWT(input.data, check2.alg)) {
  2769. ctx = this._getOrReturnCtx(input, ctx);
  2770. addIssueToContext(ctx, {
  2771. validation: "jwt",
  2772. code: ZodIssueCode.invalid_string,
  2773. message: check2.message
  2774. });
  2775. status.dirty();
  2776. }
  2777. } else if (check2.kind === "cidr") {
  2778. if (!isValidCidr(input.data, check2.version)) {
  2779. ctx = this._getOrReturnCtx(input, ctx);
  2780. addIssueToContext(ctx, {
  2781. validation: "cidr",
  2782. code: ZodIssueCode.invalid_string,
  2783. message: check2.message
  2784. });
  2785. status.dirty();
  2786. }
  2787. } else if (check2.kind === "base64") {
  2788. if (!base64Regex.test(input.data)) {
  2789. ctx = this._getOrReturnCtx(input, ctx);
  2790. addIssueToContext(ctx, {
  2791. validation: "base64",
  2792. code: ZodIssueCode.invalid_string,
  2793. message: check2.message
  2794. });
  2795. status.dirty();
  2796. }
  2797. } else if (check2.kind === "base64url") {
  2798. if (!base64urlRegex.test(input.data)) {
  2799. ctx = this._getOrReturnCtx(input, ctx);
  2800. addIssueToContext(ctx, {
  2801. validation: "base64url",
  2802. code: ZodIssueCode.invalid_string,
  2803. message: check2.message
  2804. });
  2805. status.dirty();
  2806. }
  2807. } else {
  2808. util.assertNever(check2);
  2809. }
  2810. }
  2811. return { status: status.value, value: input.data };
  2812. }
  2813. _regex(regex, validation, message) {
  2814. return this.refinement((data) => regex.test(data), {
  2815. validation,
  2816. code: ZodIssueCode.invalid_string,
  2817. ...errorUtil.errToObj(message)
  2818. });
  2819. }
  2820. _addCheck(check2) {
  2821. return new _ZodString({
  2822. ...this._def,
  2823. checks: [...this._def.checks, check2]
  2824. });
  2825. }
  2826. email(message) {
  2827. return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  2828. }
  2829. url(message) {
  2830. return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  2831. }
  2832. emoji(message) {
  2833. return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  2834. }
  2835. uuid(message) {
  2836. return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  2837. }
  2838. nanoid(message) {
  2839. return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  2840. }
  2841. cuid(message) {
  2842. return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  2843. }
  2844. cuid2(message) {
  2845. return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  2846. }
  2847. ulid(message) {
  2848. return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  2849. }
  2850. base64(message) {
  2851. return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  2852. }
  2853. base64url(message) {
  2854. return this._addCheck({
  2855. kind: "base64url",
  2856. ...errorUtil.errToObj(message)
  2857. });
  2858. }
  2859. jwt(options) {
  2860. return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
  2861. }
  2862. ip(options) {
  2863. return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  2864. }
  2865. cidr(options) {
  2866. return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
  2867. }
  2868. datetime(options) {
  2869. if (typeof options === "string") {
  2870. return this._addCheck({
  2871. kind: "datetime",
  2872. precision: null,
  2873. offset: false,
  2874. local: false,
  2875. message: options
  2876. });
  2877. }
  2878. return this._addCheck({
  2879. kind: "datetime",
  2880. precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
  2881. offset: (options == null ? void 0 : options.offset) ?? false,
  2882. local: (options == null ? void 0 : options.local) ?? false,
  2883. ...errorUtil.errToObj(options == null ? void 0 : options.message)
  2884. });
  2885. }
  2886. date(message) {
  2887. return this._addCheck({ kind: "date", message });
  2888. }
  2889. time(options) {
  2890. if (typeof options === "string") {
  2891. return this._addCheck({
  2892. kind: "time",
  2893. precision: null,
  2894. message: options
  2895. });
  2896. }
  2897. return this._addCheck({
  2898. kind: "time",
  2899. precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
  2900. ...errorUtil.errToObj(options == null ? void 0 : options.message)
  2901. });
  2902. }
  2903. duration(message) {
  2904. return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  2905. }
  2906. regex(regex, message) {
  2907. return this._addCheck({
  2908. kind: "regex",
  2909. regex,
  2910. ...errorUtil.errToObj(message)
  2911. });
  2912. }
  2913. includes(value, options) {
  2914. return this._addCheck({
  2915. kind: "includes",
  2916. value,
  2917. position: options == null ? void 0 : options.position,
  2918. ...errorUtil.errToObj(options == null ? void 0 : options.message)
  2919. });
  2920. }
  2921. startsWith(value, message) {
  2922. return this._addCheck({
  2923. kind: "startsWith",
  2924. value,
  2925. ...errorUtil.errToObj(message)
  2926. });
  2927. }
  2928. endsWith(value, message) {
  2929. return this._addCheck({
  2930. kind: "endsWith",
  2931. value,
  2932. ...errorUtil.errToObj(message)
  2933. });
  2934. }
  2935. min(minLength, message) {
  2936. return this._addCheck({
  2937. kind: "min",
  2938. value: minLength,
  2939. ...errorUtil.errToObj(message)
  2940. });
  2941. }
  2942. max(maxLength, message) {
  2943. return this._addCheck({
  2944. kind: "max",
  2945. value: maxLength,
  2946. ...errorUtil.errToObj(message)
  2947. });
  2948. }
  2949. length(len, message) {
  2950. return this._addCheck({
  2951. kind: "length",
  2952. value: len,
  2953. ...errorUtil.errToObj(message)
  2954. });
  2955. }
  2956. /**
  2957. * Equivalent to `.min(1)`
  2958. */
  2959. nonempty(message) {
  2960. return this.min(1, errorUtil.errToObj(message));
  2961. }
  2962. trim() {
  2963. return new _ZodString({
  2964. ...this._def,
  2965. checks: [...this._def.checks, { kind: "trim" }]
  2966. });
  2967. }
  2968. toLowerCase() {
  2969. return new _ZodString({
  2970. ...this._def,
  2971. checks: [...this._def.checks, { kind: "toLowerCase" }]
  2972. });
  2973. }
  2974. toUpperCase() {
  2975. return new _ZodString({
  2976. ...this._def,
  2977. checks: [...this._def.checks, { kind: "toUpperCase" }]
  2978. });
  2979. }
  2980. get isDatetime() {
  2981. return !!this._def.checks.find((ch) => ch.kind === "datetime");
  2982. }
  2983. get isDate() {
  2984. return !!this._def.checks.find((ch) => ch.kind === "date");
  2985. }
  2986. get isTime() {
  2987. return !!this._def.checks.find((ch) => ch.kind === "time");
  2988. }
  2989. get isDuration() {
  2990. return !!this._def.checks.find((ch) => ch.kind === "duration");
  2991. }
  2992. get isEmail() {
  2993. return !!this._def.checks.find((ch) => ch.kind === "email");
  2994. }
  2995. get isURL() {
  2996. return !!this._def.checks.find((ch) => ch.kind === "url");
  2997. }
  2998. get isEmoji() {
  2999. return !!this._def.checks.find((ch) => ch.kind === "emoji");
  3000. }
  3001. get isUUID() {
  3002. return !!this._def.checks.find((ch) => ch.kind === "uuid");
  3003. }
  3004. get isNANOID() {
  3005. return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  3006. }
  3007. get isCUID() {
  3008. return !!this._def.checks.find((ch) => ch.kind === "cuid");
  3009. }
  3010. get isCUID2() {
  3011. return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  3012. }
  3013. get isULID() {
  3014. return !!this._def.checks.find((ch) => ch.kind === "ulid");
  3015. }
  3016. get isIP() {
  3017. return !!this._def.checks.find((ch) => ch.kind === "ip");
  3018. }
  3019. get isCIDR() {
  3020. return !!this._def.checks.find((ch) => ch.kind === "cidr");
  3021. }
  3022. get isBase64() {
  3023. return !!this._def.checks.find((ch) => ch.kind === "base64");
  3024. }
  3025. get isBase64url() {
  3026. return !!this._def.checks.find((ch) => ch.kind === "base64url");
  3027. }
  3028. get minLength() {
  3029. let min = null;
  3030. for (const ch of this._def.checks) {
  3031. if (ch.kind === "min") {
  3032. if (min === null || ch.value > min)
  3033. min = ch.value;
  3034. }
  3035. }
  3036. return min;
  3037. }
  3038. get maxLength() {
  3039. let max = null;
  3040. for (const ch of this._def.checks) {
  3041. if (ch.kind === "max") {
  3042. if (max === null || ch.value < max)
  3043. max = ch.value;
  3044. }
  3045. }
  3046. return max;
  3047. }
  3048. };
  3049. ZodString.create = (params) => {
  3050. return new ZodString({
  3051. checks: [],
  3052. typeName: ZodFirstPartyTypeKind.ZodString,
  3053. coerce: (params == null ? void 0 : params.coerce) ?? false,
  3054. ...processCreateParams(params)
  3055. });
  3056. };
  3057. ZodNumber = class _ZodNumber extends ZodType {
  3058. constructor() {
  3059. super(...arguments);
  3060. this.min = this.gte;
  3061. this.max = this.lte;
  3062. this.step = this.multipleOf;
  3063. }
  3064. _parse(input) {
  3065. if (this._def.coerce) {
  3066. input.data = Number(input.data);
  3067. }
  3068. const parsedType = this._getType(input);
  3069. if (parsedType !== ZodParsedType.number) {
  3070. const ctx2 = this._getOrReturnCtx(input);
  3071. addIssueToContext(ctx2, {
  3072. code: ZodIssueCode.invalid_type,
  3073. expected: ZodParsedType.number,
  3074. received: ctx2.parsedType
  3075. });
  3076. return INVALID;
  3077. }
  3078. let ctx = void 0;
  3079. const status = new ParseStatus();
  3080. for (const check2 of this._def.checks) {
  3081. if (check2.kind === "int") {
  3082. if (!util.isInteger(input.data)) {
  3083. ctx = this._getOrReturnCtx(input, ctx);
  3084. addIssueToContext(ctx, {
  3085. code: ZodIssueCode.invalid_type,
  3086. expected: "integer",
  3087. received: "float",
  3088. message: check2.message
  3089. });
  3090. status.dirty();
  3091. }
  3092. } else if (check2.kind === "min") {
  3093. const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
  3094. if (tooSmall) {
  3095. ctx = this._getOrReturnCtx(input, ctx);
  3096. addIssueToContext(ctx, {
  3097. code: ZodIssueCode.too_small,
  3098. minimum: check2.value,
  3099. type: "number",
  3100. inclusive: check2.inclusive,
  3101. exact: false,
  3102. message: check2.message
  3103. });
  3104. status.dirty();
  3105. }
  3106. } else if (check2.kind === "max") {
  3107. const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
  3108. if (tooBig) {
  3109. ctx = this._getOrReturnCtx(input, ctx);
  3110. addIssueToContext(ctx, {
  3111. code: ZodIssueCode.too_big,
  3112. maximum: check2.value,
  3113. type: "number",
  3114. inclusive: check2.inclusive,
  3115. exact: false,
  3116. message: check2.message
  3117. });
  3118. status.dirty();
  3119. }
  3120. } else if (check2.kind === "multipleOf") {
  3121. if (floatSafeRemainder(input.data, check2.value) !== 0) {
  3122. ctx = this._getOrReturnCtx(input, ctx);
  3123. addIssueToContext(ctx, {
  3124. code: ZodIssueCode.not_multiple_of,
  3125. multipleOf: check2.value,
  3126. message: check2.message
  3127. });
  3128. status.dirty();
  3129. }
  3130. } else if (check2.kind === "finite") {
  3131. if (!Number.isFinite(input.data)) {
  3132. ctx = this._getOrReturnCtx(input, ctx);
  3133. addIssueToContext(ctx, {
  3134. code: ZodIssueCode.not_finite,
  3135. message: check2.message
  3136. });
  3137. status.dirty();
  3138. }
  3139. } else {
  3140. util.assertNever(check2);
  3141. }
  3142. }
  3143. return { status: status.value, value: input.data };
  3144. }
  3145. gte(value, message) {
  3146. return this.setLimit("min", value, true, errorUtil.toString(message));
  3147. }
  3148. gt(value, message) {
  3149. return this.setLimit("min", value, false, errorUtil.toString(message));
  3150. }
  3151. lte(value, message) {
  3152. return this.setLimit("max", value, true, errorUtil.toString(message));
  3153. }
  3154. lt(value, message) {
  3155. return this.setLimit("max", value, false, errorUtil.toString(message));
  3156. }
  3157. setLimit(kind, value, inclusive, message) {
  3158. return new _ZodNumber({
  3159. ...this._def,
  3160. checks: [
  3161. ...this._def.checks,
  3162. {
  3163. kind,
  3164. value,
  3165. inclusive,
  3166. message: errorUtil.toString(message)
  3167. }
  3168. ]
  3169. });
  3170. }
  3171. _addCheck(check2) {
  3172. return new _ZodNumber({
  3173. ...this._def,
  3174. checks: [...this._def.checks, check2]
  3175. });
  3176. }
  3177. int(message) {
  3178. return this._addCheck({
  3179. kind: "int",
  3180. message: errorUtil.toString(message)
  3181. });
  3182. }
  3183. positive(message) {
  3184. return this._addCheck({
  3185. kind: "min",
  3186. value: 0,
  3187. inclusive: false,
  3188. message: errorUtil.toString(message)
  3189. });
  3190. }
  3191. negative(message) {
  3192. return this._addCheck({
  3193. kind: "max",
  3194. value: 0,
  3195. inclusive: false,
  3196. message: errorUtil.toString(message)
  3197. });
  3198. }
  3199. nonpositive(message) {
  3200. return this._addCheck({
  3201. kind: "max",
  3202. value: 0,
  3203. inclusive: true,
  3204. message: errorUtil.toString(message)
  3205. });
  3206. }
  3207. nonnegative(message) {
  3208. return this._addCheck({
  3209. kind: "min",
  3210. value: 0,
  3211. inclusive: true,
  3212. message: errorUtil.toString(message)
  3213. });
  3214. }
  3215. multipleOf(value, message) {
  3216. return this._addCheck({
  3217. kind: "multipleOf",
  3218. value,
  3219. message: errorUtil.toString(message)
  3220. });
  3221. }
  3222. finite(message) {
  3223. return this._addCheck({
  3224. kind: "finite",
  3225. message: errorUtil.toString(message)
  3226. });
  3227. }
  3228. safe(message) {
  3229. return this._addCheck({
  3230. kind: "min",
  3231. inclusive: true,
  3232. value: Number.MIN_SAFE_INTEGER,
  3233. message: errorUtil.toString(message)
  3234. })._addCheck({
  3235. kind: "max",
  3236. inclusive: true,
  3237. value: Number.MAX_SAFE_INTEGER,
  3238. message: errorUtil.toString(message)
  3239. });
  3240. }
  3241. get minValue() {
  3242. let min = null;
  3243. for (const ch of this._def.checks) {
  3244. if (ch.kind === "min") {
  3245. if (min === null || ch.value > min)
  3246. min = ch.value;
  3247. }
  3248. }
  3249. return min;
  3250. }
  3251. get maxValue() {
  3252. let max = null;
  3253. for (const ch of this._def.checks) {
  3254. if (ch.kind === "max") {
  3255. if (max === null || ch.value < max)
  3256. max = ch.value;
  3257. }
  3258. }
  3259. return max;
  3260. }
  3261. get isInt() {
  3262. return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  3263. }
  3264. get isFinite() {
  3265. let max = null;
  3266. let min = null;
  3267. for (const ch of this._def.checks) {
  3268. if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
  3269. return true;
  3270. } else if (ch.kind === "min") {
  3271. if (min === null || ch.value > min)
  3272. min = ch.value;
  3273. } else if (ch.kind === "max") {
  3274. if (max === null || ch.value < max)
  3275. max = ch.value;
  3276. }
  3277. }
  3278. return Number.isFinite(min) && Number.isFinite(max);
  3279. }
  3280. };
  3281. ZodNumber.create = (params) => {
  3282. return new ZodNumber({
  3283. checks: [],
  3284. typeName: ZodFirstPartyTypeKind.ZodNumber,
  3285. coerce: (params == null ? void 0 : params.coerce) || false,
  3286. ...processCreateParams(params)
  3287. });
  3288. };
  3289. ZodBigInt = class _ZodBigInt extends ZodType {
  3290. constructor() {
  3291. super(...arguments);
  3292. this.min = this.gte;
  3293. this.max = this.lte;
  3294. }
  3295. _parse(input) {
  3296. if (this._def.coerce) {
  3297. try {
  3298. input.data = BigInt(input.data);
  3299. } catch {
  3300. return this._getInvalidInput(input);
  3301. }
  3302. }
  3303. const parsedType = this._getType(input);
  3304. if (parsedType !== ZodParsedType.bigint) {
  3305. return this._getInvalidInput(input);
  3306. }
  3307. let ctx = void 0;
  3308. const status = new ParseStatus();
  3309. for (const check2 of this._def.checks) {
  3310. if (check2.kind === "min") {
  3311. const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
  3312. if (tooSmall) {
  3313. ctx = this._getOrReturnCtx(input, ctx);
  3314. addIssueToContext(ctx, {
  3315. code: ZodIssueCode.too_small,
  3316. type: "bigint",
  3317. minimum: check2.value,
  3318. inclusive: check2.inclusive,
  3319. message: check2.message
  3320. });
  3321. status.dirty();
  3322. }
  3323. } else if (check2.kind === "max") {
  3324. const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
  3325. if (tooBig) {
  3326. ctx = this._getOrReturnCtx(input, ctx);
  3327. addIssueToContext(ctx, {
  3328. code: ZodIssueCode.too_big,
  3329. type: "bigint",
  3330. maximum: check2.value,
  3331. inclusive: check2.inclusive,
  3332. message: check2.message
  3333. });
  3334. status.dirty();
  3335. }
  3336. } else if (check2.kind === "multipleOf") {
  3337. if (input.data % check2.value !== BigInt(0)) {
  3338. ctx = this._getOrReturnCtx(input, ctx);
  3339. addIssueToContext(ctx, {
  3340. code: ZodIssueCode.not_multiple_of,
  3341. multipleOf: check2.value,
  3342. message: check2.message
  3343. });
  3344. status.dirty();
  3345. }
  3346. } else {
  3347. util.assertNever(check2);
  3348. }
  3349. }
  3350. return { status: status.value, value: input.data };
  3351. }
  3352. _getInvalidInput(input) {
  3353. const ctx = this._getOrReturnCtx(input);
  3354. addIssueToContext(ctx, {
  3355. code: ZodIssueCode.invalid_type,
  3356. expected: ZodParsedType.bigint,
  3357. received: ctx.parsedType
  3358. });
  3359. return INVALID;
  3360. }
  3361. gte(value, message) {
  3362. return this.setLimit("min", value, true, errorUtil.toString(message));
  3363. }
  3364. gt(value, message) {
  3365. return this.setLimit("min", value, false, errorUtil.toString(message));
  3366. }
  3367. lte(value, message) {
  3368. return this.setLimit("max", value, true, errorUtil.toString(message));
  3369. }
  3370. lt(value, message) {
  3371. return this.setLimit("max", value, false, errorUtil.toString(message));
  3372. }
  3373. setLimit(kind, value, inclusive, message) {
  3374. return new _ZodBigInt({
  3375. ...this._def,
  3376. checks: [
  3377. ...this._def.checks,
  3378. {
  3379. kind,
  3380. value,
  3381. inclusive,
  3382. message: errorUtil.toString(message)
  3383. }
  3384. ]
  3385. });
  3386. }
  3387. _addCheck(check2) {
  3388. return new _ZodBigInt({
  3389. ...this._def,
  3390. checks: [...this._def.checks, check2]
  3391. });
  3392. }
  3393. positive(message) {
  3394. return this._addCheck({
  3395. kind: "min",
  3396. value: BigInt(0),
  3397. inclusive: false,
  3398. message: errorUtil.toString(message)
  3399. });
  3400. }
  3401. negative(message) {
  3402. return this._addCheck({
  3403. kind: "max",
  3404. value: BigInt(0),
  3405. inclusive: false,
  3406. message: errorUtil.toString(message)
  3407. });
  3408. }
  3409. nonpositive(message) {
  3410. return this._addCheck({
  3411. kind: "max",
  3412. value: BigInt(0),
  3413. inclusive: true,
  3414. message: errorUtil.toString(message)
  3415. });
  3416. }
  3417. nonnegative(message) {
  3418. return this._addCheck({
  3419. kind: "min",
  3420. value: BigInt(0),
  3421. inclusive: true,
  3422. message: errorUtil.toString(message)
  3423. });
  3424. }
  3425. multipleOf(value, message) {
  3426. return this._addCheck({
  3427. kind: "multipleOf",
  3428. value,
  3429. message: errorUtil.toString(message)
  3430. });
  3431. }
  3432. get minValue() {
  3433. let min = null;
  3434. for (const ch of this._def.checks) {
  3435. if (ch.kind === "min") {
  3436. if (min === null || ch.value > min)
  3437. min = ch.value;
  3438. }
  3439. }
  3440. return min;
  3441. }
  3442. get maxValue() {
  3443. let max = null;
  3444. for (const ch of this._def.checks) {
  3445. if (ch.kind === "max") {
  3446. if (max === null || ch.value < max)
  3447. max = ch.value;
  3448. }
  3449. }
  3450. return max;
  3451. }
  3452. };
  3453. ZodBigInt.create = (params) => {
  3454. return new ZodBigInt({
  3455. checks: [],
  3456. typeName: ZodFirstPartyTypeKind.ZodBigInt,
  3457. coerce: (params == null ? void 0 : params.coerce) ?? false,
  3458. ...processCreateParams(params)
  3459. });
  3460. };
  3461. ZodBoolean = class extends ZodType {
  3462. _parse(input) {
  3463. if (this._def.coerce) {
  3464. input.data = Boolean(input.data);
  3465. }
  3466. const parsedType = this._getType(input);
  3467. if (parsedType !== ZodParsedType.boolean) {
  3468. const ctx = this._getOrReturnCtx(input);
  3469. addIssueToContext(ctx, {
  3470. code: ZodIssueCode.invalid_type,
  3471. expected: ZodParsedType.boolean,
  3472. received: ctx.parsedType
  3473. });
  3474. return INVALID;
  3475. }
  3476. return OK(input.data);
  3477. }
  3478. };
  3479. ZodBoolean.create = (params) => {
  3480. return new ZodBoolean({
  3481. typeName: ZodFirstPartyTypeKind.ZodBoolean,
  3482. coerce: (params == null ? void 0 : params.coerce) || false,
  3483. ...processCreateParams(params)
  3484. });
  3485. };
  3486. ZodDate = class _ZodDate extends ZodType {
  3487. _parse(input) {
  3488. if (this._def.coerce) {
  3489. input.data = new Date(input.data);
  3490. }
  3491. const parsedType = this._getType(input);
  3492. if (parsedType !== ZodParsedType.date) {
  3493. const ctx2 = this._getOrReturnCtx(input);
  3494. addIssueToContext(ctx2, {
  3495. code: ZodIssueCode.invalid_type,
  3496. expected: ZodParsedType.date,
  3497. received: ctx2.parsedType
  3498. });
  3499. return INVALID;
  3500. }
  3501. if (Number.isNaN(input.data.getTime())) {
  3502. const ctx2 = this._getOrReturnCtx(input);
  3503. addIssueToContext(ctx2, {
  3504. code: ZodIssueCode.invalid_date
  3505. });
  3506. return INVALID;
  3507. }
  3508. const status = new ParseStatus();
  3509. let ctx = void 0;
  3510. for (const check2 of this._def.checks) {
  3511. if (check2.kind === "min") {
  3512. if (input.data.getTime() < check2.value) {
  3513. ctx = this._getOrReturnCtx(input, ctx);
  3514. addIssueToContext(ctx, {
  3515. code: ZodIssueCode.too_small,
  3516. message: check2.message,
  3517. inclusive: true,
  3518. exact: false,
  3519. minimum: check2.value,
  3520. type: "date"
  3521. });
  3522. status.dirty();
  3523. }
  3524. } else if (check2.kind === "max") {
  3525. if (input.data.getTime() > check2.value) {
  3526. ctx = this._getOrReturnCtx(input, ctx);
  3527. addIssueToContext(ctx, {
  3528. code: ZodIssueCode.too_big,
  3529. message: check2.message,
  3530. inclusive: true,
  3531. exact: false,
  3532. maximum: check2.value,
  3533. type: "date"
  3534. });
  3535. status.dirty();
  3536. }
  3537. } else {
  3538. util.assertNever(check2);
  3539. }
  3540. }
  3541. return {
  3542. status: status.value,
  3543. value: new Date(input.data.getTime())
  3544. };
  3545. }
  3546. _addCheck(check2) {
  3547. return new _ZodDate({
  3548. ...this._def,
  3549. checks: [...this._def.checks, check2]
  3550. });
  3551. }
  3552. min(minDate, message) {
  3553. return this._addCheck({
  3554. kind: "min",
  3555. value: minDate.getTime(),
  3556. message: errorUtil.toString(message)
  3557. });
  3558. }
  3559. max(maxDate, message) {
  3560. return this._addCheck({
  3561. kind: "max",
  3562. value: maxDate.getTime(),
  3563. message: errorUtil.toString(message)
  3564. });
  3565. }
  3566. get minDate() {
  3567. let min = null;
  3568. for (const ch of this._def.checks) {
  3569. if (ch.kind === "min") {
  3570. if (min === null || ch.value > min)
  3571. min = ch.value;
  3572. }
  3573. }
  3574. return min != null ? new Date(min) : null;
  3575. }
  3576. get maxDate() {
  3577. let max = null;
  3578. for (const ch of this._def.checks) {
  3579. if (ch.kind === "max") {
  3580. if (max === null || ch.value < max)
  3581. max = ch.value;
  3582. }
  3583. }
  3584. return max != null ? new Date(max) : null;
  3585. }
  3586. };
  3587. ZodDate.create = (params) => {
  3588. return new ZodDate({
  3589. checks: [],
  3590. coerce: (params == null ? void 0 : params.coerce) || false,
  3591. typeName: ZodFirstPartyTypeKind.ZodDate,
  3592. ...processCreateParams(params)
  3593. });
  3594. };
  3595. ZodSymbol = class extends ZodType {
  3596. _parse(input) {
  3597. const parsedType = this._getType(input);
  3598. if (parsedType !== ZodParsedType.symbol) {
  3599. const ctx = this._getOrReturnCtx(input);
  3600. addIssueToContext(ctx, {
  3601. code: ZodIssueCode.invalid_type,
  3602. expected: ZodParsedType.symbol,
  3603. received: ctx.parsedType
  3604. });
  3605. return INVALID;
  3606. }
  3607. return OK(input.data);
  3608. }
  3609. };
  3610. ZodSymbol.create = (params) => {
  3611. return new ZodSymbol({
  3612. typeName: ZodFirstPartyTypeKind.ZodSymbol,
  3613. ...processCreateParams(params)
  3614. });
  3615. };
  3616. ZodUndefined = class extends ZodType {
  3617. _parse(input) {
  3618. const parsedType = this._getType(input);
  3619. if (parsedType !== ZodParsedType.undefined) {
  3620. const ctx = this._getOrReturnCtx(input);
  3621. addIssueToContext(ctx, {
  3622. code: ZodIssueCode.invalid_type,
  3623. expected: ZodParsedType.undefined,
  3624. received: ctx.parsedType
  3625. });
  3626. return INVALID;
  3627. }
  3628. return OK(input.data);
  3629. }
  3630. };
  3631. ZodUndefined.create = (params) => {
  3632. return new ZodUndefined({
  3633. typeName: ZodFirstPartyTypeKind.ZodUndefined,
  3634. ...processCreateParams(params)
  3635. });
  3636. };
  3637. ZodNull = class extends ZodType {
  3638. _parse(input) {
  3639. const parsedType = this._getType(input);
  3640. if (parsedType !== ZodParsedType.null) {
  3641. const ctx = this._getOrReturnCtx(input);
  3642. addIssueToContext(ctx, {
  3643. code: ZodIssueCode.invalid_type,
  3644. expected: ZodParsedType.null,
  3645. received: ctx.parsedType
  3646. });
  3647. return INVALID;
  3648. }
  3649. return OK(input.data);
  3650. }
  3651. };
  3652. ZodNull.create = (params) => {
  3653. return new ZodNull({
  3654. typeName: ZodFirstPartyTypeKind.ZodNull,
  3655. ...processCreateParams(params)
  3656. });
  3657. };
  3658. ZodAny = class extends ZodType {
  3659. constructor() {
  3660. super(...arguments);
  3661. this._any = true;
  3662. }
  3663. _parse(input) {
  3664. return OK(input.data);
  3665. }
  3666. };
  3667. ZodAny.create = (params) => {
  3668. return new ZodAny({
  3669. typeName: ZodFirstPartyTypeKind.ZodAny,
  3670. ...processCreateParams(params)
  3671. });
  3672. };
  3673. ZodUnknown = class extends ZodType {
  3674. constructor() {
  3675. super(...arguments);
  3676. this._unknown = true;
  3677. }
  3678. _parse(input) {
  3679. return OK(input.data);
  3680. }
  3681. };
  3682. ZodUnknown.create = (params) => {
  3683. return new ZodUnknown({
  3684. typeName: ZodFirstPartyTypeKind.ZodUnknown,
  3685. ...processCreateParams(params)
  3686. });
  3687. };
  3688. ZodNever = class extends ZodType {
  3689. _parse(input) {
  3690. const ctx = this._getOrReturnCtx(input);
  3691. addIssueToContext(ctx, {
  3692. code: ZodIssueCode.invalid_type,
  3693. expected: ZodParsedType.never,
  3694. received: ctx.parsedType
  3695. });
  3696. return INVALID;
  3697. }
  3698. };
  3699. ZodNever.create = (params) => {
  3700. return new ZodNever({
  3701. typeName: ZodFirstPartyTypeKind.ZodNever,
  3702. ...processCreateParams(params)
  3703. });
  3704. };
  3705. ZodVoid = class extends ZodType {
  3706. _parse(input) {
  3707. const parsedType = this._getType(input);
  3708. if (parsedType !== ZodParsedType.undefined) {
  3709. const ctx = this._getOrReturnCtx(input);
  3710. addIssueToContext(ctx, {
  3711. code: ZodIssueCode.invalid_type,
  3712. expected: ZodParsedType.void,
  3713. received: ctx.parsedType
  3714. });
  3715. return INVALID;
  3716. }
  3717. return OK(input.data);
  3718. }
  3719. };
  3720. ZodVoid.create = (params) => {
  3721. return new ZodVoid({
  3722. typeName: ZodFirstPartyTypeKind.ZodVoid,
  3723. ...processCreateParams(params)
  3724. });
  3725. };
  3726. ZodArray = class _ZodArray extends ZodType {
  3727. _parse(input) {
  3728. const { ctx, status } = this._processInputParams(input);
  3729. const def = this._def;
  3730. if (ctx.parsedType !== ZodParsedType.array) {
  3731. addIssueToContext(ctx, {
  3732. code: ZodIssueCode.invalid_type,
  3733. expected: ZodParsedType.array,
  3734. received: ctx.parsedType
  3735. });
  3736. return INVALID;
  3737. }
  3738. if (def.exactLength !== null) {
  3739. const tooBig = ctx.data.length > def.exactLength.value;
  3740. const tooSmall = ctx.data.length < def.exactLength.value;
  3741. if (tooBig || tooSmall) {
  3742. addIssueToContext(ctx, {
  3743. code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
  3744. minimum: tooSmall ? def.exactLength.value : void 0,
  3745. maximum: tooBig ? def.exactLength.value : void 0,
  3746. type: "array",
  3747. inclusive: true,
  3748. exact: true,
  3749. message: def.exactLength.message
  3750. });
  3751. status.dirty();
  3752. }
  3753. }
  3754. if (def.minLength !== null) {
  3755. if (ctx.data.length < def.minLength.value) {
  3756. addIssueToContext(ctx, {
  3757. code: ZodIssueCode.too_small,
  3758. minimum: def.minLength.value,
  3759. type: "array",
  3760. inclusive: true,
  3761. exact: false,
  3762. message: def.minLength.message
  3763. });
  3764. status.dirty();
  3765. }
  3766. }
  3767. if (def.maxLength !== null) {
  3768. if (ctx.data.length > def.maxLength.value) {
  3769. addIssueToContext(ctx, {
  3770. code: ZodIssueCode.too_big,
  3771. maximum: def.maxLength.value,
  3772. type: "array",
  3773. inclusive: true,
  3774. exact: false,
  3775. message: def.maxLength.message
  3776. });
  3777. status.dirty();
  3778. }
  3779. }
  3780. if (ctx.common.async) {
  3781. return Promise.all([...ctx.data].map((item, i4) => {
  3782. return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i4));
  3783. })).then((result2) => {
  3784. return ParseStatus.mergeArray(status, result2);
  3785. });
  3786. }
  3787. const result = [...ctx.data].map((item, i4) => {
  3788. return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i4));
  3789. });
  3790. return ParseStatus.mergeArray(status, result);
  3791. }
  3792. get element() {
  3793. return this._def.type;
  3794. }
  3795. min(minLength, message) {
  3796. return new _ZodArray({
  3797. ...this._def,
  3798. minLength: { value: minLength, message: errorUtil.toString(message) }
  3799. });
  3800. }
  3801. max(maxLength, message) {
  3802. return new _ZodArray({
  3803. ...this._def,
  3804. maxLength: { value: maxLength, message: errorUtil.toString(message) }
  3805. });
  3806. }
  3807. length(len, message) {
  3808. return new _ZodArray({
  3809. ...this._def,
  3810. exactLength: { value: len, message: errorUtil.toString(message) }
  3811. });
  3812. }
  3813. nonempty(message) {
  3814. return this.min(1, message);
  3815. }
  3816. };
  3817. ZodArray.create = (schema6, params) => {
  3818. return new ZodArray({
  3819. type: schema6,
  3820. minLength: null,
  3821. maxLength: null,
  3822. exactLength: null,
  3823. typeName: ZodFirstPartyTypeKind.ZodArray,
  3824. ...processCreateParams(params)
  3825. });
  3826. };
  3827. ZodObject = class _ZodObject extends ZodType {
  3828. constructor() {
  3829. super(...arguments);
  3830. this._cached = null;
  3831. this.nonstrict = this.passthrough;
  3832. this.augment = this.extend;
  3833. }
  3834. _getCached() {
  3835. if (this._cached !== null)
  3836. return this._cached;
  3837. const shape = this._def.shape();
  3838. const keys = util.objectKeys(shape);
  3839. this._cached = { shape, keys };
  3840. return this._cached;
  3841. }
  3842. _parse(input) {
  3843. const parsedType = this._getType(input);
  3844. if (parsedType !== ZodParsedType.object) {
  3845. const ctx2 = this._getOrReturnCtx(input);
  3846. addIssueToContext(ctx2, {
  3847. code: ZodIssueCode.invalid_type,
  3848. expected: ZodParsedType.object,
  3849. received: ctx2.parsedType
  3850. });
  3851. return INVALID;
  3852. }
  3853. const { status, ctx } = this._processInputParams(input);
  3854. const { shape, keys: shapeKeys } = this._getCached();
  3855. const extraKeys = [];
  3856. if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
  3857. for (const key in ctx.data) {
  3858. if (!shapeKeys.includes(key)) {
  3859. extraKeys.push(key);
  3860. }
  3861. }
  3862. }
  3863. const pairs = [];
  3864. for (const key of shapeKeys) {
  3865. const keyValidator = shape[key];
  3866. const value = ctx.data[key];
  3867. pairs.push({
  3868. key: { status: "valid", value: key },
  3869. value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
  3870. alwaysSet: key in ctx.data
  3871. });
  3872. }
  3873. if (this._def.catchall instanceof ZodNever) {
  3874. const unknownKeys = this._def.unknownKeys;
  3875. if (unknownKeys === "passthrough") {
  3876. for (const key of extraKeys) {
  3877. pairs.push({
  3878. key: { status: "valid", value: key },
  3879. value: { status: "valid", value: ctx.data[key] }
  3880. });
  3881. }
  3882. } else if (unknownKeys === "strict") {
  3883. if (extraKeys.length > 0) {
  3884. addIssueToContext(ctx, {
  3885. code: ZodIssueCode.unrecognized_keys,
  3886. keys: extraKeys
  3887. });
  3888. status.dirty();
  3889. }
  3890. } else if (unknownKeys === "strip") {
  3891. } else {
  3892. throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
  3893. }
  3894. } else {
  3895. const catchall = this._def.catchall;
  3896. for (const key of extraKeys) {
  3897. const value = ctx.data[key];
  3898. pairs.push({
  3899. key: { status: "valid", value: key },
  3900. value: catchall._parse(
  3901. new ParseInputLazyPath(ctx, value, ctx.path, key)
  3902. //, ctx.child(key), value, getParsedType(value)
  3903. ),
  3904. alwaysSet: key in ctx.data
  3905. });
  3906. }
  3907. }
  3908. if (ctx.common.async) {
  3909. return Promise.resolve().then(async () => {
  3910. const syncPairs = [];
  3911. for (const pair of pairs) {
  3912. const key = await pair.key;
  3913. const value = await pair.value;
  3914. syncPairs.push({
  3915. key,
  3916. value,
  3917. alwaysSet: pair.alwaysSet
  3918. });
  3919. }
  3920. return syncPairs;
  3921. }).then((syncPairs) => {
  3922. return ParseStatus.mergeObjectSync(status, syncPairs);
  3923. });
  3924. } else {
  3925. return ParseStatus.mergeObjectSync(status, pairs);
  3926. }
  3927. }
  3928. get shape() {
  3929. return this._def.shape();
  3930. }
  3931. strict(message) {
  3932. errorUtil.errToObj;
  3933. return new _ZodObject({
  3934. ...this._def,
  3935. unknownKeys: "strict",
  3936. ...message !== void 0 ? {
  3937. errorMap: (issue, ctx) => {
  3938. var _a2, _b;
  3939. const defaultError = ((_b = (_a2 = this._def).errorMap) == null ? void 0 : _b.call(_a2, issue, ctx).message) ?? ctx.defaultError;
  3940. if (issue.code === "unrecognized_keys")
  3941. return {
  3942. message: errorUtil.errToObj(message).message ?? defaultError
  3943. };
  3944. return {
  3945. message: defaultError
  3946. };
  3947. }
  3948. } : {}
  3949. });
  3950. }
  3951. strip() {
  3952. return new _ZodObject({
  3953. ...this._def,
  3954. unknownKeys: "strip"
  3955. });
  3956. }
  3957. passthrough() {
  3958. return new _ZodObject({
  3959. ...this._def,
  3960. unknownKeys: "passthrough"
  3961. });
  3962. }
  3963. // const AugmentFactory =
  3964. // <Def extends ZodObjectDef>(def: Def) =>
  3965. // <Augmentation extends ZodRawShape>(
  3966. // augmentation: Augmentation
  3967. // ): ZodObject<
  3968. // extendShape<ReturnType<Def["shape"]>, Augmentation>,
  3969. // Def["unknownKeys"],
  3970. // Def["catchall"]
  3971. // > => {
  3972. // return new ZodObject({
  3973. // ...def,
  3974. // shape: () => ({
  3975. // ...def.shape(),
  3976. // ...augmentation,
  3977. // }),
  3978. // }) as any;
  3979. // };
  3980. extend(augmentation) {
  3981. return new _ZodObject({
  3982. ...this._def,
  3983. shape: () => ({
  3984. ...this._def.shape(),
  3985. ...augmentation
  3986. })
  3987. });
  3988. }
  3989. /**
  3990. * Prior to zod@1.0.12 there was a bug in the
  3991. * inferred type of merged objects. Please
  3992. * upgrade if you are experiencing issues.
  3993. */
  3994. merge(merging) {
  3995. const merged = new _ZodObject({
  3996. unknownKeys: merging._def.unknownKeys,
  3997. catchall: merging._def.catchall,
  3998. shape: () => ({
  3999. ...this._def.shape(),
  4000. ...merging._def.shape()
  4001. }),
  4002. typeName: ZodFirstPartyTypeKind.ZodObject
  4003. });
  4004. return merged;
  4005. }
  4006. // merge<
  4007. // Incoming extends AnyZodObject,
  4008. // Augmentation extends Incoming["shape"],
  4009. // NewOutput extends {
  4010. // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  4011. // ? Augmentation[k]["_output"]
  4012. // : k extends keyof Output
  4013. // ? Output[k]
  4014. // : never;
  4015. // },
  4016. // NewInput extends {
  4017. // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  4018. // ? Augmentation[k]["_input"]
  4019. // : k extends keyof Input
  4020. // ? Input[k]
  4021. // : never;
  4022. // }
  4023. // >(
  4024. // merging: Incoming
  4025. // ): ZodObject<
  4026. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  4027. // Incoming["_def"]["unknownKeys"],
  4028. // Incoming["_def"]["catchall"],
  4029. // NewOutput,
  4030. // NewInput
  4031. // > {
  4032. // const merged: any = new ZodObject({
  4033. // unknownKeys: merging._def.unknownKeys,
  4034. // catchall: merging._def.catchall,
  4035. // shape: () =>
  4036. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  4037. // typeName: ZodFirstPartyTypeKind.ZodObject,
  4038. // }) as any;
  4039. // return merged;
  4040. // }
  4041. setKey(key, schema6) {
  4042. return this.augment({ [key]: schema6 });
  4043. }
  4044. // merge<Incoming extends AnyZodObject>(
  4045. // merging: Incoming
  4046. // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  4047. // ZodObject<
  4048. // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  4049. // Incoming["_def"]["unknownKeys"],
  4050. // Incoming["_def"]["catchall"]
  4051. // > {
  4052. // // const mergedShape = objectUtil.mergeShapes(
  4053. // // this._def.shape(),
  4054. // // merging._def.shape()
  4055. // // );
  4056. // const merged: any = new ZodObject({
  4057. // unknownKeys: merging._def.unknownKeys,
  4058. // catchall: merging._def.catchall,
  4059. // shape: () =>
  4060. // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  4061. // typeName: ZodFirstPartyTypeKind.ZodObject,
  4062. // }) as any;
  4063. // return merged;
  4064. // }
  4065. catchall(index6) {
  4066. return new _ZodObject({
  4067. ...this._def,
  4068. catchall: index6
  4069. });
  4070. }
  4071. pick(mask) {
  4072. const shape = {};
  4073. for (const key of util.objectKeys(mask)) {
  4074. if (mask[key] && this.shape[key]) {
  4075. shape[key] = this.shape[key];
  4076. }
  4077. }
  4078. return new _ZodObject({
  4079. ...this._def,
  4080. shape: () => shape
  4081. });
  4082. }
  4083. omit(mask) {
  4084. const shape = {};
  4085. for (const key of util.objectKeys(this.shape)) {
  4086. if (!mask[key]) {
  4087. shape[key] = this.shape[key];
  4088. }
  4089. }
  4090. return new _ZodObject({
  4091. ...this._def,
  4092. shape: () => shape
  4093. });
  4094. }
  4095. /**
  4096. * @deprecated
  4097. */
  4098. deepPartial() {
  4099. return deepPartialify(this);
  4100. }
  4101. partial(mask) {
  4102. const newShape = {};
  4103. for (const key of util.objectKeys(this.shape)) {
  4104. const fieldSchema = this.shape[key];
  4105. if (mask && !mask[key]) {
  4106. newShape[key] = fieldSchema;
  4107. } else {
  4108. newShape[key] = fieldSchema.optional();
  4109. }
  4110. }
  4111. return new _ZodObject({
  4112. ...this._def,
  4113. shape: () => newShape
  4114. });
  4115. }
  4116. required(mask) {
  4117. const newShape = {};
  4118. for (const key of util.objectKeys(this.shape)) {
  4119. if (mask && !mask[key]) {
  4120. newShape[key] = this.shape[key];
  4121. } else {
  4122. const fieldSchema = this.shape[key];
  4123. let newField = fieldSchema;
  4124. while (newField instanceof ZodOptional) {
  4125. newField = newField._def.innerType;
  4126. }
  4127. newShape[key] = newField;
  4128. }
  4129. }
  4130. return new _ZodObject({
  4131. ...this._def,
  4132. shape: () => newShape
  4133. });
  4134. }
  4135. keyof() {
  4136. return createZodEnum(util.objectKeys(this.shape));
  4137. }
  4138. };
  4139. ZodObject.create = (shape, params) => {
  4140. return new ZodObject({
  4141. shape: () => shape,
  4142. unknownKeys: "strip",
  4143. catchall: ZodNever.create(),
  4144. typeName: ZodFirstPartyTypeKind.ZodObject,
  4145. ...processCreateParams(params)
  4146. });
  4147. };
  4148. ZodObject.strictCreate = (shape, params) => {
  4149. return new ZodObject({
  4150. shape: () => shape,
  4151. unknownKeys: "strict",
  4152. catchall: ZodNever.create(),
  4153. typeName: ZodFirstPartyTypeKind.ZodObject,
  4154. ...processCreateParams(params)
  4155. });
  4156. };
  4157. ZodObject.lazycreate = (shape, params) => {
  4158. return new ZodObject({
  4159. shape,
  4160. unknownKeys: "strip",
  4161. catchall: ZodNever.create(),
  4162. typeName: ZodFirstPartyTypeKind.ZodObject,
  4163. ...processCreateParams(params)
  4164. });
  4165. };
  4166. ZodUnion = class extends ZodType {
  4167. _parse(input) {
  4168. const { ctx } = this._processInputParams(input);
  4169. const options = this._def.options;
  4170. function handleResults(results) {
  4171. for (const result of results) {
  4172. if (result.result.status === "valid") {
  4173. return result.result;
  4174. }
  4175. }
  4176. for (const result of results) {
  4177. if (result.result.status === "dirty") {
  4178. ctx.common.issues.push(...result.ctx.common.issues);
  4179. return result.result;
  4180. }
  4181. }
  4182. const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
  4183. addIssueToContext(ctx, {
  4184. code: ZodIssueCode.invalid_union,
  4185. unionErrors
  4186. });
  4187. return INVALID;
  4188. }
  4189. if (ctx.common.async) {
  4190. return Promise.all(options.map(async (option) => {
  4191. const childCtx = {
  4192. ...ctx,
  4193. common: {
  4194. ...ctx.common,
  4195. issues: []
  4196. },
  4197. parent: null
  4198. };
  4199. return {
  4200. result: await option._parseAsync({
  4201. data: ctx.data,
  4202. path: ctx.path,
  4203. parent: childCtx
  4204. }),
  4205. ctx: childCtx
  4206. };
  4207. })).then(handleResults);
  4208. } else {
  4209. let dirty = void 0;
  4210. const issues = [];
  4211. for (const option of options) {
  4212. const childCtx = {
  4213. ...ctx,
  4214. common: {
  4215. ...ctx.common,
  4216. issues: []
  4217. },
  4218. parent: null
  4219. };
  4220. const result = option._parseSync({
  4221. data: ctx.data,
  4222. path: ctx.path,
  4223. parent: childCtx
  4224. });
  4225. if (result.status === "valid") {
  4226. return result;
  4227. } else if (result.status === "dirty" && !dirty) {
  4228. dirty = { result, ctx: childCtx };
  4229. }
  4230. if (childCtx.common.issues.length) {
  4231. issues.push(childCtx.common.issues);
  4232. }
  4233. }
  4234. if (dirty) {
  4235. ctx.common.issues.push(...dirty.ctx.common.issues);
  4236. return dirty.result;
  4237. }
  4238. const unionErrors = issues.map((issues2) => new ZodError(issues2));
  4239. addIssueToContext(ctx, {
  4240. code: ZodIssueCode.invalid_union,
  4241. unionErrors
  4242. });
  4243. return INVALID;
  4244. }
  4245. }
  4246. get options() {
  4247. return this._def.options;
  4248. }
  4249. };
  4250. ZodUnion.create = (types3, params) => {
  4251. return new ZodUnion({
  4252. options: types3,
  4253. typeName: ZodFirstPartyTypeKind.ZodUnion,
  4254. ...processCreateParams(params)
  4255. });
  4256. };
  4257. getDiscriminator = (type) => {
  4258. if (type instanceof ZodLazy) {
  4259. return getDiscriminator(type.schema);
  4260. } else if (type instanceof ZodEffects) {
  4261. return getDiscriminator(type.innerType());
  4262. } else if (type instanceof ZodLiteral) {
  4263. return [type.value];
  4264. } else if (type instanceof ZodEnum) {
  4265. return type.options;
  4266. } else if (type instanceof ZodNativeEnum) {
  4267. return util.objectValues(type.enum);
  4268. } else if (type instanceof ZodDefault) {
  4269. return getDiscriminator(type._def.innerType);
  4270. } else if (type instanceof ZodUndefined) {
  4271. return [void 0];
  4272. } else if (type instanceof ZodNull) {
  4273. return [null];
  4274. } else if (type instanceof ZodOptional) {
  4275. return [void 0, ...getDiscriminator(type.unwrap())];
  4276. } else if (type instanceof ZodNullable) {
  4277. return [null, ...getDiscriminator(type.unwrap())];
  4278. } else if (type instanceof ZodBranded) {
  4279. return getDiscriminator(type.unwrap());
  4280. } else if (type instanceof ZodReadonly) {
  4281. return getDiscriminator(type.unwrap());
  4282. } else if (type instanceof ZodCatch) {
  4283. return getDiscriminator(type._def.innerType);
  4284. } else {
  4285. return [];
  4286. }
  4287. };
  4288. ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
  4289. _parse(input) {
  4290. const { ctx } = this._processInputParams(input);
  4291. if (ctx.parsedType !== ZodParsedType.object) {
  4292. addIssueToContext(ctx, {
  4293. code: ZodIssueCode.invalid_type,
  4294. expected: ZodParsedType.object,
  4295. received: ctx.parsedType
  4296. });
  4297. return INVALID;
  4298. }
  4299. const discriminator = this.discriminator;
  4300. const discriminatorValue = ctx.data[discriminator];
  4301. const option = this.optionsMap.get(discriminatorValue);
  4302. if (!option) {
  4303. addIssueToContext(ctx, {
  4304. code: ZodIssueCode.invalid_union_discriminator,
  4305. options: Array.from(this.optionsMap.keys()),
  4306. path: [discriminator]
  4307. });
  4308. return INVALID;
  4309. }
  4310. if (ctx.common.async) {
  4311. return option._parseAsync({
  4312. data: ctx.data,
  4313. path: ctx.path,
  4314. parent: ctx
  4315. });
  4316. } else {
  4317. return option._parseSync({
  4318. data: ctx.data,
  4319. path: ctx.path,
  4320. parent: ctx
  4321. });
  4322. }
  4323. }
  4324. get discriminator() {
  4325. return this._def.discriminator;
  4326. }
  4327. get options() {
  4328. return this._def.options;
  4329. }
  4330. get optionsMap() {
  4331. return this._def.optionsMap;
  4332. }
  4333. /**
  4334. * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
  4335. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
  4336. * have a different value for each object in the union.
  4337. * @param discriminator the name of the discriminator property
  4338. * @param types an array of object schemas
  4339. * @param params
  4340. */
  4341. static create(discriminator, options, params) {
  4342. const optionsMap = /* @__PURE__ */ new Map();
  4343. for (const type of options) {
  4344. const discriminatorValues = getDiscriminator(type.shape[discriminator]);
  4345. if (!discriminatorValues.length) {
  4346. throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
  4347. }
  4348. for (const value of discriminatorValues) {
  4349. if (optionsMap.has(value)) {
  4350. throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
  4351. }
  4352. optionsMap.set(value, type);
  4353. }
  4354. }
  4355. return new _ZodDiscriminatedUnion({
  4356. typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
  4357. discriminator,
  4358. options,
  4359. optionsMap,
  4360. ...processCreateParams(params)
  4361. });
  4362. }
  4363. };
  4364. ZodIntersection = class extends ZodType {
  4365. _parse(input) {
  4366. const { status, ctx } = this._processInputParams(input);
  4367. const handleParsed = (parsedLeft, parsedRight) => {
  4368. if (isAborted(parsedLeft) || isAborted(parsedRight)) {
  4369. return INVALID;
  4370. }
  4371. const merged = mergeValues(parsedLeft.value, parsedRight.value);
  4372. if (!merged.valid) {
  4373. addIssueToContext(ctx, {
  4374. code: ZodIssueCode.invalid_intersection_types
  4375. });
  4376. return INVALID;
  4377. }
  4378. if (isDirty(parsedLeft) || isDirty(parsedRight)) {
  4379. status.dirty();
  4380. }
  4381. return { status: status.value, value: merged.data };
  4382. };
  4383. if (ctx.common.async) {
  4384. return Promise.all([
  4385. this._def.left._parseAsync({
  4386. data: ctx.data,
  4387. path: ctx.path,
  4388. parent: ctx
  4389. }),
  4390. this._def.right._parseAsync({
  4391. data: ctx.data,
  4392. path: ctx.path,
  4393. parent: ctx
  4394. })
  4395. ]).then(([left, right]) => handleParsed(left, right));
  4396. } else {
  4397. return handleParsed(this._def.left._parseSync({
  4398. data: ctx.data,
  4399. path: ctx.path,
  4400. parent: ctx
  4401. }), this._def.right._parseSync({
  4402. data: ctx.data,
  4403. path: ctx.path,
  4404. parent: ctx
  4405. }));
  4406. }
  4407. }
  4408. };
  4409. ZodIntersection.create = (left, right, params) => {
  4410. return new ZodIntersection({
  4411. left,
  4412. right,
  4413. typeName: ZodFirstPartyTypeKind.ZodIntersection,
  4414. ...processCreateParams(params)
  4415. });
  4416. };
  4417. ZodTuple = class _ZodTuple extends ZodType {
  4418. _parse(input) {
  4419. const { status, ctx } = this._processInputParams(input);
  4420. if (ctx.parsedType !== ZodParsedType.array) {
  4421. addIssueToContext(ctx, {
  4422. code: ZodIssueCode.invalid_type,
  4423. expected: ZodParsedType.array,
  4424. received: ctx.parsedType
  4425. });
  4426. return INVALID;
  4427. }
  4428. if (ctx.data.length < this._def.items.length) {
  4429. addIssueToContext(ctx, {
  4430. code: ZodIssueCode.too_small,
  4431. minimum: this._def.items.length,
  4432. inclusive: true,
  4433. exact: false,
  4434. type: "array"
  4435. });
  4436. return INVALID;
  4437. }
  4438. const rest = this._def.rest;
  4439. if (!rest && ctx.data.length > this._def.items.length) {
  4440. addIssueToContext(ctx, {
  4441. code: ZodIssueCode.too_big,
  4442. maximum: this._def.items.length,
  4443. inclusive: true,
  4444. exact: false,
  4445. type: "array"
  4446. });
  4447. status.dirty();
  4448. }
  4449. const items = [...ctx.data].map((item, itemIndex) => {
  4450. const schema6 = this._def.items[itemIndex] || this._def.rest;
  4451. if (!schema6)
  4452. return null;
  4453. return schema6._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
  4454. }).filter((x4) => !!x4);
  4455. if (ctx.common.async) {
  4456. return Promise.all(items).then((results) => {
  4457. return ParseStatus.mergeArray(status, results);
  4458. });
  4459. } else {
  4460. return ParseStatus.mergeArray(status, items);
  4461. }
  4462. }
  4463. get items() {
  4464. return this._def.items;
  4465. }
  4466. rest(rest) {
  4467. return new _ZodTuple({
  4468. ...this._def,
  4469. rest
  4470. });
  4471. }
  4472. };
  4473. ZodTuple.create = (schemas, params) => {
  4474. if (!Array.isArray(schemas)) {
  4475. throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  4476. }
  4477. return new ZodTuple({
  4478. items: schemas,
  4479. typeName: ZodFirstPartyTypeKind.ZodTuple,
  4480. rest: null,
  4481. ...processCreateParams(params)
  4482. });
  4483. };
  4484. ZodRecord = class _ZodRecord extends ZodType {
  4485. get keySchema() {
  4486. return this._def.keyType;
  4487. }
  4488. get valueSchema() {
  4489. return this._def.valueType;
  4490. }
  4491. _parse(input) {
  4492. const { status, ctx } = this._processInputParams(input);
  4493. if (ctx.parsedType !== ZodParsedType.object) {
  4494. addIssueToContext(ctx, {
  4495. code: ZodIssueCode.invalid_type,
  4496. expected: ZodParsedType.object,
  4497. received: ctx.parsedType
  4498. });
  4499. return INVALID;
  4500. }
  4501. const pairs = [];
  4502. const keyType = this._def.keyType;
  4503. const valueType = this._def.valueType;
  4504. for (const key in ctx.data) {
  4505. pairs.push({
  4506. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
  4507. value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
  4508. alwaysSet: key in ctx.data
  4509. });
  4510. }
  4511. if (ctx.common.async) {
  4512. return ParseStatus.mergeObjectAsync(status, pairs);
  4513. } else {
  4514. return ParseStatus.mergeObjectSync(status, pairs);
  4515. }
  4516. }
  4517. get element() {
  4518. return this._def.valueType;
  4519. }
  4520. static create(first, second, third) {
  4521. if (second instanceof ZodType) {
  4522. return new _ZodRecord({
  4523. keyType: first,
  4524. valueType: second,
  4525. typeName: ZodFirstPartyTypeKind.ZodRecord,
  4526. ...processCreateParams(third)
  4527. });
  4528. }
  4529. return new _ZodRecord({
  4530. keyType: ZodString.create(),
  4531. valueType: first,
  4532. typeName: ZodFirstPartyTypeKind.ZodRecord,
  4533. ...processCreateParams(second)
  4534. });
  4535. }
  4536. };
  4537. ZodMap = class extends ZodType {
  4538. get keySchema() {
  4539. return this._def.keyType;
  4540. }
  4541. get valueSchema() {
  4542. return this._def.valueType;
  4543. }
  4544. _parse(input) {
  4545. const { status, ctx } = this._processInputParams(input);
  4546. if (ctx.parsedType !== ZodParsedType.map) {
  4547. addIssueToContext(ctx, {
  4548. code: ZodIssueCode.invalid_type,
  4549. expected: ZodParsedType.map,
  4550. received: ctx.parsedType
  4551. });
  4552. return INVALID;
  4553. }
  4554. const keyType = this._def.keyType;
  4555. const valueType = this._def.valueType;
  4556. const pairs = [...ctx.data.entries()].map(([key, value], index6) => {
  4557. return {
  4558. key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index6, "key"])),
  4559. value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index6, "value"]))
  4560. };
  4561. });
  4562. if (ctx.common.async) {
  4563. const finalMap = /* @__PURE__ */ new Map();
  4564. return Promise.resolve().then(async () => {
  4565. for (const pair of pairs) {
  4566. const key = await pair.key;
  4567. const value = await pair.value;
  4568. if (key.status === "aborted" || value.status === "aborted") {
  4569. return INVALID;
  4570. }
  4571. if (key.status === "dirty" || value.status === "dirty") {
  4572. status.dirty();
  4573. }
  4574. finalMap.set(key.value, value.value);
  4575. }
  4576. return { status: status.value, value: finalMap };
  4577. });
  4578. } else {
  4579. const finalMap = /* @__PURE__ */ new Map();
  4580. for (const pair of pairs) {
  4581. const key = pair.key;
  4582. const value = pair.value;
  4583. if (key.status === "aborted" || value.status === "aborted") {
  4584. return INVALID;
  4585. }
  4586. if (key.status === "dirty" || value.status === "dirty") {
  4587. status.dirty();
  4588. }
  4589. finalMap.set(key.value, value.value);
  4590. }
  4591. return { status: status.value, value: finalMap };
  4592. }
  4593. }
  4594. };
  4595. ZodMap.create = (keyType, valueType, params) => {
  4596. return new ZodMap({
  4597. valueType,
  4598. keyType,
  4599. typeName: ZodFirstPartyTypeKind.ZodMap,
  4600. ...processCreateParams(params)
  4601. });
  4602. };
  4603. ZodSet = class _ZodSet extends ZodType {
  4604. _parse(input) {
  4605. const { status, ctx } = this._processInputParams(input);
  4606. if (ctx.parsedType !== ZodParsedType.set) {
  4607. addIssueToContext(ctx, {
  4608. code: ZodIssueCode.invalid_type,
  4609. expected: ZodParsedType.set,
  4610. received: ctx.parsedType
  4611. });
  4612. return INVALID;
  4613. }
  4614. const def = this._def;
  4615. if (def.minSize !== null) {
  4616. if (ctx.data.size < def.minSize.value) {
  4617. addIssueToContext(ctx, {
  4618. code: ZodIssueCode.too_small,
  4619. minimum: def.minSize.value,
  4620. type: "set",
  4621. inclusive: true,
  4622. exact: false,
  4623. message: def.minSize.message
  4624. });
  4625. status.dirty();
  4626. }
  4627. }
  4628. if (def.maxSize !== null) {
  4629. if (ctx.data.size > def.maxSize.value) {
  4630. addIssueToContext(ctx, {
  4631. code: ZodIssueCode.too_big,
  4632. maximum: def.maxSize.value,
  4633. type: "set",
  4634. inclusive: true,
  4635. exact: false,
  4636. message: def.maxSize.message
  4637. });
  4638. status.dirty();
  4639. }
  4640. }
  4641. const valueType = this._def.valueType;
  4642. function finalizeSet(elements2) {
  4643. const parsedSet = /* @__PURE__ */ new Set();
  4644. for (const element of elements2) {
  4645. if (element.status === "aborted")
  4646. return INVALID;
  4647. if (element.status === "dirty")
  4648. status.dirty();
  4649. parsedSet.add(element.value);
  4650. }
  4651. return { status: status.value, value: parsedSet };
  4652. }
  4653. const elements = [...ctx.data.values()].map((item, i4) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i4)));
  4654. if (ctx.common.async) {
  4655. return Promise.all(elements).then((elements2) => finalizeSet(elements2));
  4656. } else {
  4657. return finalizeSet(elements);
  4658. }
  4659. }
  4660. min(minSize, message) {
  4661. return new _ZodSet({
  4662. ...this._def,
  4663. minSize: { value: minSize, message: errorUtil.toString(message) }
  4664. });
  4665. }
  4666. max(maxSize, message) {
  4667. return new _ZodSet({
  4668. ...this._def,
  4669. maxSize: { value: maxSize, message: errorUtil.toString(message) }
  4670. });
  4671. }
  4672. size(size, message) {
  4673. return this.min(size, message).max(size, message);
  4674. }
  4675. nonempty(message) {
  4676. return this.min(1, message);
  4677. }
  4678. };
  4679. ZodSet.create = (valueType, params) => {
  4680. return new ZodSet({
  4681. valueType,
  4682. minSize: null,
  4683. maxSize: null,
  4684. typeName: ZodFirstPartyTypeKind.ZodSet,
  4685. ...processCreateParams(params)
  4686. });
  4687. };
  4688. ZodFunction = class _ZodFunction extends ZodType {
  4689. constructor() {
  4690. super(...arguments);
  4691. this.validate = this.implement;
  4692. }
  4693. _parse(input) {
  4694. const { ctx } = this._processInputParams(input);
  4695. if (ctx.parsedType !== ZodParsedType.function) {
  4696. addIssueToContext(ctx, {
  4697. code: ZodIssueCode.invalid_type,
  4698. expected: ZodParsedType.function,
  4699. received: ctx.parsedType
  4700. });
  4701. return INVALID;
  4702. }
  4703. function makeArgsIssue(args, error2) {
  4704. return makeIssue({
  4705. data: args,
  4706. path: ctx.path,
  4707. errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x4) => !!x4),
  4708. issueData: {
  4709. code: ZodIssueCode.invalid_arguments,
  4710. argumentsError: error2
  4711. }
  4712. });
  4713. }
  4714. function makeReturnsIssue(returns, error2) {
  4715. return makeIssue({
  4716. data: returns,
  4717. path: ctx.path,
  4718. errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x4) => !!x4),
  4719. issueData: {
  4720. code: ZodIssueCode.invalid_return_type,
  4721. returnTypeError: error2
  4722. }
  4723. });
  4724. }
  4725. const params = { errorMap: ctx.common.contextualErrorMap };
  4726. const fn = ctx.data;
  4727. if (this._def.returns instanceof ZodPromise) {
  4728. const me = this;
  4729. return OK(async function(...args) {
  4730. const error2 = new ZodError([]);
  4731. const parsedArgs = await me._def.args.parseAsync(args, params).catch((e4) => {
  4732. error2.addIssue(makeArgsIssue(args, e4));
  4733. throw error2;
  4734. });
  4735. const result = await Reflect.apply(fn, this, parsedArgs);
  4736. const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e4) => {
  4737. error2.addIssue(makeReturnsIssue(result, e4));
  4738. throw error2;
  4739. });
  4740. return parsedReturns;
  4741. });
  4742. } else {
  4743. const me = this;
  4744. return OK(function(...args) {
  4745. const parsedArgs = me._def.args.safeParse(args, params);
  4746. if (!parsedArgs.success) {
  4747. throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
  4748. }
  4749. const result = Reflect.apply(fn, this, parsedArgs.data);
  4750. const parsedReturns = me._def.returns.safeParse(result, params);
  4751. if (!parsedReturns.success) {
  4752. throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
  4753. }
  4754. return parsedReturns.data;
  4755. });
  4756. }
  4757. }
  4758. parameters() {
  4759. return this._def.args;
  4760. }
  4761. returnType() {
  4762. return this._def.returns;
  4763. }
  4764. args(...items) {
  4765. return new _ZodFunction({
  4766. ...this._def,
  4767. args: ZodTuple.create(items).rest(ZodUnknown.create())
  4768. });
  4769. }
  4770. returns(returnType) {
  4771. return new _ZodFunction({
  4772. ...this._def,
  4773. returns: returnType
  4774. });
  4775. }
  4776. implement(func) {
  4777. const validatedFunc = this.parse(func);
  4778. return validatedFunc;
  4779. }
  4780. strictImplement(func) {
  4781. const validatedFunc = this.parse(func);
  4782. return validatedFunc;
  4783. }
  4784. static create(args, returns, params) {
  4785. return new _ZodFunction({
  4786. args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
  4787. returns: returns || ZodUnknown.create(),
  4788. typeName: ZodFirstPartyTypeKind.ZodFunction,
  4789. ...processCreateParams(params)
  4790. });
  4791. }
  4792. };
  4793. ZodLazy = class extends ZodType {
  4794. get schema() {
  4795. return this._def.getter();
  4796. }
  4797. _parse(input) {
  4798. const { ctx } = this._processInputParams(input);
  4799. const lazySchema = this._def.getter();
  4800. return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  4801. }
  4802. };
  4803. ZodLazy.create = (getter, params) => {
  4804. return new ZodLazy({
  4805. getter,
  4806. typeName: ZodFirstPartyTypeKind.ZodLazy,
  4807. ...processCreateParams(params)
  4808. });
  4809. };
  4810. ZodLiteral = class extends ZodType {
  4811. _parse(input) {
  4812. if (input.data !== this._def.value) {
  4813. const ctx = this._getOrReturnCtx(input);
  4814. addIssueToContext(ctx, {
  4815. received: ctx.data,
  4816. code: ZodIssueCode.invalid_literal,
  4817. expected: this._def.value
  4818. });
  4819. return INVALID;
  4820. }
  4821. return { status: "valid", value: input.data };
  4822. }
  4823. get value() {
  4824. return this._def.value;
  4825. }
  4826. };
  4827. ZodLiteral.create = (value, params) => {
  4828. return new ZodLiteral({
  4829. value,
  4830. typeName: ZodFirstPartyTypeKind.ZodLiteral,
  4831. ...processCreateParams(params)
  4832. });
  4833. };
  4834. ZodEnum = class _ZodEnum extends ZodType {
  4835. _parse(input) {
  4836. if (typeof input.data !== "string") {
  4837. const ctx = this._getOrReturnCtx(input);
  4838. const expectedValues = this._def.values;
  4839. addIssueToContext(ctx, {
  4840. expected: util.joinValues(expectedValues),
  4841. received: ctx.parsedType,
  4842. code: ZodIssueCode.invalid_type
  4843. });
  4844. return INVALID;
  4845. }
  4846. if (!this._cache) {
  4847. this._cache = new Set(this._def.values);
  4848. }
  4849. if (!this._cache.has(input.data)) {
  4850. const ctx = this._getOrReturnCtx(input);
  4851. const expectedValues = this._def.values;
  4852. addIssueToContext(ctx, {
  4853. received: ctx.data,
  4854. code: ZodIssueCode.invalid_enum_value,
  4855. options: expectedValues
  4856. });
  4857. return INVALID;
  4858. }
  4859. return OK(input.data);
  4860. }
  4861. get options() {
  4862. return this._def.values;
  4863. }
  4864. get enum() {
  4865. const enumValues = {};
  4866. for (const val2 of this._def.values) {
  4867. enumValues[val2] = val2;
  4868. }
  4869. return enumValues;
  4870. }
  4871. get Values() {
  4872. const enumValues = {};
  4873. for (const val2 of this._def.values) {
  4874. enumValues[val2] = val2;
  4875. }
  4876. return enumValues;
  4877. }
  4878. get Enum() {
  4879. const enumValues = {};
  4880. for (const val2 of this._def.values) {
  4881. enumValues[val2] = val2;
  4882. }
  4883. return enumValues;
  4884. }
  4885. extract(values, newDef = this._def) {
  4886. return _ZodEnum.create(values, {
  4887. ...this._def,
  4888. ...newDef
  4889. });
  4890. }
  4891. exclude(values, newDef = this._def) {
  4892. return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
  4893. ...this._def,
  4894. ...newDef
  4895. });
  4896. }
  4897. };
  4898. ZodEnum.create = createZodEnum;
  4899. ZodNativeEnum = class extends ZodType {
  4900. _parse(input) {
  4901. const nativeEnumValues = util.getValidEnumValues(this._def.values);
  4902. const ctx = this._getOrReturnCtx(input);
  4903. if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
  4904. const expectedValues = util.objectValues(nativeEnumValues);
  4905. addIssueToContext(ctx, {
  4906. expected: util.joinValues(expectedValues),
  4907. received: ctx.parsedType,
  4908. code: ZodIssueCode.invalid_type
  4909. });
  4910. return INVALID;
  4911. }
  4912. if (!this._cache) {
  4913. this._cache = new Set(util.getValidEnumValues(this._def.values));
  4914. }
  4915. if (!this._cache.has(input.data)) {
  4916. const expectedValues = util.objectValues(nativeEnumValues);
  4917. addIssueToContext(ctx, {
  4918. received: ctx.data,
  4919. code: ZodIssueCode.invalid_enum_value,
  4920. options: expectedValues
  4921. });
  4922. return INVALID;
  4923. }
  4924. return OK(input.data);
  4925. }
  4926. get enum() {
  4927. return this._def.values;
  4928. }
  4929. };
  4930. ZodNativeEnum.create = (values, params) => {
  4931. return new ZodNativeEnum({
  4932. values,
  4933. typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
  4934. ...processCreateParams(params)
  4935. });
  4936. };
  4937. ZodPromise = class extends ZodType {
  4938. unwrap() {
  4939. return this._def.type;
  4940. }
  4941. _parse(input) {
  4942. const { ctx } = this._processInputParams(input);
  4943. if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
  4944. addIssueToContext(ctx, {
  4945. code: ZodIssueCode.invalid_type,
  4946. expected: ZodParsedType.promise,
  4947. received: ctx.parsedType
  4948. });
  4949. return INVALID;
  4950. }
  4951. const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
  4952. return OK(promisified.then((data) => {
  4953. return this._def.type.parseAsync(data, {
  4954. path: ctx.path,
  4955. errorMap: ctx.common.contextualErrorMap
  4956. });
  4957. }));
  4958. }
  4959. };
  4960. ZodPromise.create = (schema6, params) => {
  4961. return new ZodPromise({
  4962. type: schema6,
  4963. typeName: ZodFirstPartyTypeKind.ZodPromise,
  4964. ...processCreateParams(params)
  4965. });
  4966. };
  4967. ZodEffects = class extends ZodType {
  4968. innerType() {
  4969. return this._def.schema;
  4970. }
  4971. sourceType() {
  4972. return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  4973. }
  4974. _parse(input) {
  4975. const { status, ctx } = this._processInputParams(input);
  4976. const effect = this._def.effect || null;
  4977. const checkCtx = {
  4978. addIssue: (arg) => {
  4979. addIssueToContext(ctx, arg);
  4980. if (arg.fatal) {
  4981. status.abort();
  4982. } else {
  4983. status.dirty();
  4984. }
  4985. },
  4986. get path() {
  4987. return ctx.path;
  4988. }
  4989. };
  4990. checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
  4991. if (effect.type === "preprocess") {
  4992. const processed = effect.transform(ctx.data, checkCtx);
  4993. if (ctx.common.async) {
  4994. return Promise.resolve(processed).then(async (processed2) => {
  4995. if (status.value === "aborted")
  4996. return INVALID;
  4997. const result = await this._def.schema._parseAsync({
  4998. data: processed2,
  4999. path: ctx.path,
  5000. parent: ctx
  5001. });
  5002. if (result.status === "aborted")
  5003. return INVALID;
  5004. if (result.status === "dirty")
  5005. return DIRTY(result.value);
  5006. if (status.value === "dirty")
  5007. return DIRTY(result.value);
  5008. return result;
  5009. });
  5010. } else {
  5011. if (status.value === "aborted")
  5012. return INVALID;
  5013. const result = this._def.schema._parseSync({
  5014. data: processed,
  5015. path: ctx.path,
  5016. parent: ctx
  5017. });
  5018. if (result.status === "aborted")
  5019. return INVALID;
  5020. if (result.status === "dirty")
  5021. return DIRTY(result.value);
  5022. if (status.value === "dirty")
  5023. return DIRTY(result.value);
  5024. return result;
  5025. }
  5026. }
  5027. if (effect.type === "refinement") {
  5028. const executeRefinement = (acc) => {
  5029. const result = effect.refinement(acc, checkCtx);
  5030. if (ctx.common.async) {
  5031. return Promise.resolve(result);
  5032. }
  5033. if (result instanceof Promise) {
  5034. throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
  5035. }
  5036. return acc;
  5037. };
  5038. if (ctx.common.async === false) {
  5039. const inner = this._def.schema._parseSync({
  5040. data: ctx.data,
  5041. path: ctx.path,
  5042. parent: ctx
  5043. });
  5044. if (inner.status === "aborted")
  5045. return INVALID;
  5046. if (inner.status === "dirty")
  5047. status.dirty();
  5048. executeRefinement(inner.value);
  5049. return { status: status.value, value: inner.value };
  5050. } else {
  5051. return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
  5052. if (inner.status === "aborted")
  5053. return INVALID;
  5054. if (inner.status === "dirty")
  5055. status.dirty();
  5056. return executeRefinement(inner.value).then(() => {
  5057. return { status: status.value, value: inner.value };
  5058. });
  5059. });
  5060. }
  5061. }
  5062. if (effect.type === "transform") {
  5063. if (ctx.common.async === false) {
  5064. const base = this._def.schema._parseSync({
  5065. data: ctx.data,
  5066. path: ctx.path,
  5067. parent: ctx
  5068. });
  5069. if (!isValid(base))
  5070. return INVALID;
  5071. const result = effect.transform(base.value, checkCtx);
  5072. if (result instanceof Promise) {
  5073. throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
  5074. }
  5075. return { status: status.value, value: result };
  5076. } else {
  5077. return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
  5078. if (!isValid(base))
  5079. return INVALID;
  5080. return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
  5081. status: status.value,
  5082. value: result
  5083. }));
  5084. });
  5085. }
  5086. }
  5087. util.assertNever(effect);
  5088. }
  5089. };
  5090. ZodEffects.create = (schema6, effect, params) => {
  5091. return new ZodEffects({
  5092. schema: schema6,
  5093. typeName: ZodFirstPartyTypeKind.ZodEffects,
  5094. effect,
  5095. ...processCreateParams(params)
  5096. });
  5097. };
  5098. ZodEffects.createWithPreprocess = (preprocess, schema6, params) => {
  5099. return new ZodEffects({
  5100. schema: schema6,
  5101. effect: { type: "preprocess", transform: preprocess },
  5102. typeName: ZodFirstPartyTypeKind.ZodEffects,
  5103. ...processCreateParams(params)
  5104. });
  5105. };
  5106. ZodOptional = class extends ZodType {
  5107. _parse(input) {
  5108. const parsedType = this._getType(input);
  5109. if (parsedType === ZodParsedType.undefined) {
  5110. return OK(void 0);
  5111. }
  5112. return this._def.innerType._parse(input);
  5113. }
  5114. unwrap() {
  5115. return this._def.innerType;
  5116. }
  5117. };
  5118. ZodOptional.create = (type, params) => {
  5119. return new ZodOptional({
  5120. innerType: type,
  5121. typeName: ZodFirstPartyTypeKind.ZodOptional,
  5122. ...processCreateParams(params)
  5123. });
  5124. };
  5125. ZodNullable = class extends ZodType {
  5126. _parse(input) {
  5127. const parsedType = this._getType(input);
  5128. if (parsedType === ZodParsedType.null) {
  5129. return OK(null);
  5130. }
  5131. return this._def.innerType._parse(input);
  5132. }
  5133. unwrap() {
  5134. return this._def.innerType;
  5135. }
  5136. };
  5137. ZodNullable.create = (type, params) => {
  5138. return new ZodNullable({
  5139. innerType: type,
  5140. typeName: ZodFirstPartyTypeKind.ZodNullable,
  5141. ...processCreateParams(params)
  5142. });
  5143. };
  5144. ZodDefault = class extends ZodType {
  5145. _parse(input) {
  5146. const { ctx } = this._processInputParams(input);
  5147. let data = ctx.data;
  5148. if (ctx.parsedType === ZodParsedType.undefined) {
  5149. data = this._def.defaultValue();
  5150. }
  5151. return this._def.innerType._parse({
  5152. data,
  5153. path: ctx.path,
  5154. parent: ctx
  5155. });
  5156. }
  5157. removeDefault() {
  5158. return this._def.innerType;
  5159. }
  5160. };
  5161. ZodDefault.create = (type, params) => {
  5162. return new ZodDefault({
  5163. innerType: type,
  5164. typeName: ZodFirstPartyTypeKind.ZodDefault,
  5165. defaultValue: typeof params.default === "function" ? params.default : () => params.default,
  5166. ...processCreateParams(params)
  5167. });
  5168. };
  5169. ZodCatch = class extends ZodType {
  5170. _parse(input) {
  5171. const { ctx } = this._processInputParams(input);
  5172. const newCtx = {
  5173. ...ctx,
  5174. common: {
  5175. ...ctx.common,
  5176. issues: []
  5177. }
  5178. };
  5179. const result = this._def.innerType._parse({
  5180. data: newCtx.data,
  5181. path: newCtx.path,
  5182. parent: {
  5183. ...newCtx
  5184. }
  5185. });
  5186. if (isAsync(result)) {
  5187. return result.then((result2) => {
  5188. return {
  5189. status: "valid",
  5190. value: result2.status === "valid" ? result2.value : this._def.catchValue({
  5191. get error() {
  5192. return new ZodError(newCtx.common.issues);
  5193. },
  5194. input: newCtx.data
  5195. })
  5196. };
  5197. });
  5198. } else {
  5199. return {
  5200. status: "valid",
  5201. value: result.status === "valid" ? result.value : this._def.catchValue({
  5202. get error() {
  5203. return new ZodError(newCtx.common.issues);
  5204. },
  5205. input: newCtx.data
  5206. })
  5207. };
  5208. }
  5209. }
  5210. removeCatch() {
  5211. return this._def.innerType;
  5212. }
  5213. };
  5214. ZodCatch.create = (type, params) => {
  5215. return new ZodCatch({
  5216. innerType: type,
  5217. typeName: ZodFirstPartyTypeKind.ZodCatch,
  5218. catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
  5219. ...processCreateParams(params)
  5220. });
  5221. };
  5222. ZodNaN = class extends ZodType {
  5223. _parse(input) {
  5224. const parsedType = this._getType(input);
  5225. if (parsedType !== ZodParsedType.nan) {
  5226. const ctx = this._getOrReturnCtx(input);
  5227. addIssueToContext(ctx, {
  5228. code: ZodIssueCode.invalid_type,
  5229. expected: ZodParsedType.nan,
  5230. received: ctx.parsedType
  5231. });
  5232. return INVALID;
  5233. }
  5234. return { status: "valid", value: input.data };
  5235. }
  5236. };
  5237. ZodNaN.create = (params) => {
  5238. return new ZodNaN({
  5239. typeName: ZodFirstPartyTypeKind.ZodNaN,
  5240. ...processCreateParams(params)
  5241. });
  5242. };
  5243. BRAND = Symbol("zod_brand");
  5244. ZodBranded = class extends ZodType {
  5245. _parse(input) {
  5246. const { ctx } = this._processInputParams(input);
  5247. const data = ctx.data;
  5248. return this._def.type._parse({
  5249. data,
  5250. path: ctx.path,
  5251. parent: ctx
  5252. });
  5253. }
  5254. unwrap() {
  5255. return this._def.type;
  5256. }
  5257. };
  5258. ZodPipeline = class _ZodPipeline extends ZodType {
  5259. _parse(input) {
  5260. const { status, ctx } = this._processInputParams(input);
  5261. if (ctx.common.async) {
  5262. const handleAsync = async () => {
  5263. const inResult = await this._def.in._parseAsync({
  5264. data: ctx.data,
  5265. path: ctx.path,
  5266. parent: ctx
  5267. });
  5268. if (inResult.status === "aborted")
  5269. return INVALID;
  5270. if (inResult.status === "dirty") {
  5271. status.dirty();
  5272. return DIRTY(inResult.value);
  5273. } else {
  5274. return this._def.out._parseAsync({
  5275. data: inResult.value,
  5276. path: ctx.path,
  5277. parent: ctx
  5278. });
  5279. }
  5280. };
  5281. return handleAsync();
  5282. } else {
  5283. const inResult = this._def.in._parseSync({
  5284. data: ctx.data,
  5285. path: ctx.path,
  5286. parent: ctx
  5287. });
  5288. if (inResult.status === "aborted")
  5289. return INVALID;
  5290. if (inResult.status === "dirty") {
  5291. status.dirty();
  5292. return {
  5293. status: "dirty",
  5294. value: inResult.value
  5295. };
  5296. } else {
  5297. return this._def.out._parseSync({
  5298. data: inResult.value,
  5299. path: ctx.path,
  5300. parent: ctx
  5301. });
  5302. }
  5303. }
  5304. }
  5305. static create(a3, b3) {
  5306. return new _ZodPipeline({
  5307. in: a3,
  5308. out: b3,
  5309. typeName: ZodFirstPartyTypeKind.ZodPipeline
  5310. });
  5311. }
  5312. };
  5313. ZodReadonly = class extends ZodType {
  5314. _parse(input) {
  5315. const result = this._def.innerType._parse(input);
  5316. const freeze = (data) => {
  5317. if (isValid(data)) {
  5318. data.value = Object.freeze(data.value);
  5319. }
  5320. return data;
  5321. };
  5322. return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  5323. }
  5324. unwrap() {
  5325. return this._def.innerType;
  5326. }
  5327. };
  5328. ZodReadonly.create = (type, params) => {
  5329. return new ZodReadonly({
  5330. innerType: type,
  5331. typeName: ZodFirstPartyTypeKind.ZodReadonly,
  5332. ...processCreateParams(params)
  5333. });
  5334. };
  5335. late = {
  5336. object: ZodObject.lazycreate
  5337. };
  5338. (function(ZodFirstPartyTypeKind2) {
  5339. ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
  5340. ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
  5341. ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
  5342. ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
  5343. ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
  5344. ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
  5345. ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
  5346. ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
  5347. ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
  5348. ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
  5349. ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
  5350. ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
  5351. ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
  5352. ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
  5353. ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
  5354. ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
  5355. ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  5356. ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
  5357. ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
  5358. ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
  5359. ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
  5360. ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
  5361. ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
  5362. ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
  5363. ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
  5364. ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
  5365. ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
  5366. ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
  5367. ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
  5368. ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
  5369. ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
  5370. ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
  5371. ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
  5372. ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
  5373. ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
  5374. ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
  5375. })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
  5376. instanceOfType = (cls, params = {
  5377. message: `Input not instance of ${cls.name}`
  5378. }) => custom((data) => data instanceof cls, params);
  5379. stringType = ZodString.create;
  5380. numberType = ZodNumber.create;
  5381. nanType = ZodNaN.create;
  5382. bigIntType = ZodBigInt.create;
  5383. booleanType = ZodBoolean.create;
  5384. dateType = ZodDate.create;
  5385. symbolType = ZodSymbol.create;
  5386. undefinedType = ZodUndefined.create;
  5387. nullType = ZodNull.create;
  5388. anyType = ZodAny.create;
  5389. unknownType = ZodUnknown.create;
  5390. neverType = ZodNever.create;
  5391. voidType = ZodVoid.create;
  5392. arrayType = ZodArray.create;
  5393. objectType = ZodObject.create;
  5394. strictObjectType = ZodObject.strictCreate;
  5395. unionType = ZodUnion.create;
  5396. discriminatedUnionType = ZodDiscriminatedUnion.create;
  5397. intersectionType = ZodIntersection.create;
  5398. tupleType = ZodTuple.create;
  5399. recordType = ZodRecord.create;
  5400. mapType = ZodMap.create;
  5401. setType = ZodSet.create;
  5402. functionType = ZodFunction.create;
  5403. lazyType = ZodLazy.create;
  5404. literalType = ZodLiteral.create;
  5405. enumType = ZodEnum.create;
  5406. nativeEnumType = ZodNativeEnum.create;
  5407. promiseType = ZodPromise.create;
  5408. effectsType = ZodEffects.create;
  5409. optionalType = ZodOptional.create;
  5410. nullableType = ZodNullable.create;
  5411. preprocessType = ZodEffects.createWithPreprocess;
  5412. pipelineType = ZodPipeline.create;
  5413. ostring = () => stringType().optional();
  5414. onumber = () => numberType().optional();
  5415. oboolean = () => booleanType().optional();
  5416. coerce = {
  5417. string: (arg) => ZodString.create({ ...arg, coerce: true }),
  5418. number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
  5419. boolean: (arg) => ZodBoolean.create({
  5420. ...arg,
  5421. coerce: true
  5422. }),
  5423. bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
  5424. date: (arg) => ZodDate.create({ ...arg, coerce: true })
  5425. };
  5426. NEVER = INVALID;
  5427. }
  5428. });
  5429. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js
  5430. var external_exports = {};
  5431. __export(external_exports, {
  5432. BRAND: () => BRAND,
  5433. DIRTY: () => DIRTY,
  5434. EMPTY_PATH: () => EMPTY_PATH,
  5435. INVALID: () => INVALID,
  5436. NEVER: () => NEVER,
  5437. OK: () => OK,
  5438. ParseStatus: () => ParseStatus,
  5439. Schema: () => ZodType,
  5440. ZodAny: () => ZodAny,
  5441. ZodArray: () => ZodArray,
  5442. ZodBigInt: () => ZodBigInt,
  5443. ZodBoolean: () => ZodBoolean,
  5444. ZodBranded: () => ZodBranded,
  5445. ZodCatch: () => ZodCatch,
  5446. ZodDate: () => ZodDate,
  5447. ZodDefault: () => ZodDefault,
  5448. ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  5449. ZodEffects: () => ZodEffects,
  5450. ZodEnum: () => ZodEnum,
  5451. ZodError: () => ZodError,
  5452. ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  5453. ZodFunction: () => ZodFunction,
  5454. ZodIntersection: () => ZodIntersection,
  5455. ZodIssueCode: () => ZodIssueCode,
  5456. ZodLazy: () => ZodLazy,
  5457. ZodLiteral: () => ZodLiteral,
  5458. ZodMap: () => ZodMap,
  5459. ZodNaN: () => ZodNaN,
  5460. ZodNativeEnum: () => ZodNativeEnum,
  5461. ZodNever: () => ZodNever,
  5462. ZodNull: () => ZodNull,
  5463. ZodNullable: () => ZodNullable,
  5464. ZodNumber: () => ZodNumber,
  5465. ZodObject: () => ZodObject,
  5466. ZodOptional: () => ZodOptional,
  5467. ZodParsedType: () => ZodParsedType,
  5468. ZodPipeline: () => ZodPipeline,
  5469. ZodPromise: () => ZodPromise,
  5470. ZodReadonly: () => ZodReadonly,
  5471. ZodRecord: () => ZodRecord,
  5472. ZodSchema: () => ZodType,
  5473. ZodSet: () => ZodSet,
  5474. ZodString: () => ZodString,
  5475. ZodSymbol: () => ZodSymbol,
  5476. ZodTransformer: () => ZodEffects,
  5477. ZodTuple: () => ZodTuple,
  5478. ZodType: () => ZodType,
  5479. ZodUndefined: () => ZodUndefined,
  5480. ZodUnion: () => ZodUnion,
  5481. ZodUnknown: () => ZodUnknown,
  5482. ZodVoid: () => ZodVoid,
  5483. addIssueToContext: () => addIssueToContext,
  5484. any: () => anyType,
  5485. array: () => arrayType,
  5486. bigint: () => bigIntType,
  5487. boolean: () => booleanType,
  5488. coerce: () => coerce,
  5489. custom: () => custom,
  5490. date: () => dateType,
  5491. datetimeRegex: () => datetimeRegex,
  5492. defaultErrorMap: () => en_default,
  5493. discriminatedUnion: () => discriminatedUnionType,
  5494. effect: () => effectsType,
  5495. enum: () => enumType,
  5496. function: () => functionType,
  5497. getErrorMap: () => getErrorMap,
  5498. getParsedType: () => getParsedType,
  5499. instanceof: () => instanceOfType,
  5500. intersection: () => intersectionType,
  5501. isAborted: () => isAborted,
  5502. isAsync: () => isAsync,
  5503. isDirty: () => isDirty,
  5504. isValid: () => isValid,
  5505. late: () => late,
  5506. lazy: () => lazyType,
  5507. literal: () => literalType,
  5508. makeIssue: () => makeIssue,
  5509. map: () => mapType,
  5510. nan: () => nanType,
  5511. nativeEnum: () => nativeEnumType,
  5512. never: () => neverType,
  5513. null: () => nullType,
  5514. nullable: () => nullableType,
  5515. number: () => numberType,
  5516. object: () => objectType,
  5517. objectUtil: () => objectUtil,
  5518. oboolean: () => oboolean,
  5519. onumber: () => onumber,
  5520. optional: () => optionalType,
  5521. ostring: () => ostring,
  5522. pipeline: () => pipelineType,
  5523. preprocess: () => preprocessType,
  5524. promise: () => promiseType,
  5525. quotelessJson: () => quotelessJson,
  5526. record: () => recordType,
  5527. set: () => setType,
  5528. setErrorMap: () => setErrorMap,
  5529. strictObject: () => strictObjectType,
  5530. string: () => stringType,
  5531. symbol: () => symbolType,
  5532. transformer: () => effectsType,
  5533. tuple: () => tupleType,
  5534. undefined: () => undefinedType,
  5535. union: () => unionType,
  5536. unknown: () => unknownType,
  5537. util: () => util,
  5538. void: () => voidType
  5539. });
  5540. var init_external = __esm({
  5541. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js"() {
  5542. init_errors();
  5543. init_parseUtil();
  5544. init_typeAliases();
  5545. init_util();
  5546. init_types();
  5547. init_ZodError();
  5548. }
  5549. });
  5550. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js
  5551. var init_v3 = __esm({
  5552. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js"() {
  5553. init_external();
  5554. init_external();
  5555. }
  5556. });
  5557. // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js
  5558. var init_esm = __esm({
  5559. "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js"() {
  5560. init_v3();
  5561. init_v3();
  5562. }
  5563. });
  5564. // src/global.ts
  5565. function assertUnreachable(x4) {
  5566. throw new Error("Didn't expect to get here");
  5567. }
  5568. function softAssertUnreachable(x4) {
  5569. return null;
  5570. }
  5571. var originUUID, snapshotVersion, mapValues, mapKeys, mapEntries, customMapEntries;
  5572. var init_global = __esm({
  5573. "src/global.ts"() {
  5574. "use strict";
  5575. originUUID = "00000000-0000-0000-0000-000000000000";
  5576. snapshotVersion = "7";
  5577. mapValues = (obj, map2) => {
  5578. const result = Object.keys(obj).reduce(function(result2, key) {
  5579. result2[key] = map2(obj[key]);
  5580. return result2;
  5581. }, {});
  5582. return result;
  5583. };
  5584. mapKeys = (obj, map2) => {
  5585. const result = Object.fromEntries(
  5586. Object.entries(obj).map(([key, val2]) => {
  5587. const newKey = map2(key, val2);
  5588. return [newKey, val2];
  5589. })
  5590. );
  5591. return result;
  5592. };
  5593. mapEntries = (obj, map2) => {
  5594. const result = Object.fromEntries(
  5595. Object.entries(obj).map(([key, val2]) => {
  5596. const [newKey, newVal] = map2(key, val2);
  5597. return [newKey, newVal];
  5598. })
  5599. );
  5600. return result;
  5601. };
  5602. customMapEntries = (obj, map2) => {
  5603. const result = Object.fromEntries(
  5604. Object.entries(obj).map(([key, val2]) => {
  5605. const [newKey, newVal] = map2(key, val2);
  5606. return [newKey, newVal];
  5607. })
  5608. );
  5609. return result;
  5610. };
  5611. }
  5612. });
  5613. // src/serializer/mysqlSchema.ts
  5614. var index, fk, column, tableV3, compositePK, uniqueConstraint, checkConstraint, tableV4, table, viewMeta, view, kitInternals, dialect, schemaHash, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
  5615. var init_mysqlSchema = __esm({
  5616. "src/serializer/mysqlSchema.ts"() {
  5617. "use strict";
  5618. init_esm();
  5619. init_global();
  5620. index = objectType({
  5621. name: stringType(),
  5622. columns: stringType().array(),
  5623. isUnique: booleanType(),
  5624. using: enumType(["btree", "hash"]).optional(),
  5625. algorithm: enumType(["default", "inplace", "copy"]).optional(),
  5626. lock: enumType(["default", "none", "shared", "exclusive"]).optional()
  5627. }).strict();
  5628. fk = objectType({
  5629. name: stringType(),
  5630. tableFrom: stringType(),
  5631. columnsFrom: stringType().array(),
  5632. tableTo: stringType(),
  5633. columnsTo: stringType().array(),
  5634. onUpdate: stringType().optional(),
  5635. onDelete: stringType().optional()
  5636. }).strict();
  5637. column = objectType({
  5638. name: stringType(),
  5639. type: stringType(),
  5640. primaryKey: booleanType(),
  5641. notNull: booleanType(),
  5642. autoincrement: booleanType().optional(),
  5643. default: anyType().optional(),
  5644. onUpdate: anyType().optional(),
  5645. generated: objectType({
  5646. type: enumType(["stored", "virtual"]),
  5647. as: stringType()
  5648. }).optional()
  5649. }).strict();
  5650. tableV3 = objectType({
  5651. name: stringType(),
  5652. columns: recordType(stringType(), column),
  5653. indexes: recordType(stringType(), index),
  5654. foreignKeys: recordType(stringType(), fk)
  5655. }).strict();
  5656. compositePK = objectType({
  5657. name: stringType(),
  5658. columns: stringType().array()
  5659. }).strict();
  5660. uniqueConstraint = objectType({
  5661. name: stringType(),
  5662. columns: stringType().array()
  5663. }).strict();
  5664. checkConstraint = objectType({
  5665. name: stringType(),
  5666. value: stringType()
  5667. }).strict();
  5668. tableV4 = objectType({
  5669. name: stringType(),
  5670. schema: stringType().optional(),
  5671. columns: recordType(stringType(), column),
  5672. indexes: recordType(stringType(), index),
  5673. foreignKeys: recordType(stringType(), fk)
  5674. }).strict();
  5675. table = objectType({
  5676. name: stringType(),
  5677. columns: recordType(stringType(), column),
  5678. indexes: recordType(stringType(), index),
  5679. foreignKeys: recordType(stringType(), fk),
  5680. compositePrimaryKeys: recordType(stringType(), compositePK),
  5681. uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}),
  5682. checkConstraint: recordType(stringType(), checkConstraint).default({})
  5683. }).strict();
  5684. viewMeta = objectType({
  5685. algorithm: enumType(["undefined", "merge", "temptable"]),
  5686. sqlSecurity: enumType(["definer", "invoker"]),
  5687. withCheckOption: enumType(["local", "cascaded"]).optional()
  5688. }).strict();
  5689. view = objectType({
  5690. name: stringType(),
  5691. columns: recordType(stringType(), column),
  5692. definition: stringType().optional(),
  5693. isExisting: booleanType()
  5694. }).strict().merge(viewMeta);
  5695. kitInternals = objectType({
  5696. tables: recordType(
  5697. stringType(),
  5698. objectType({
  5699. columns: recordType(
  5700. stringType(),
  5701. objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
  5702. )
  5703. }).optional()
  5704. ).optional(),
  5705. indexes: recordType(
  5706. stringType(),
  5707. objectType({
  5708. columns: recordType(
  5709. stringType(),
  5710. objectType({ isExpression: booleanType().optional() }).optional()
  5711. )
  5712. }).optional()
  5713. ).optional()
  5714. }).optional();
  5715. dialect = literalType("mysql");
  5716. schemaHash = objectType({
  5717. id: stringType(),
  5718. prevId: stringType()
  5719. });
  5720. schemaInternalV3 = objectType({
  5721. version: literalType("3"),
  5722. dialect,
  5723. tables: recordType(stringType(), tableV3)
  5724. }).strict();
  5725. schemaInternalV4 = objectType({
  5726. version: literalType("4"),
  5727. dialect,
  5728. tables: recordType(stringType(), tableV4),
  5729. schemas: recordType(stringType(), stringType())
  5730. }).strict();
  5731. schemaInternalV5 = objectType({
  5732. version: literalType("5"),
  5733. dialect,
  5734. tables: recordType(stringType(), table),
  5735. schemas: recordType(stringType(), stringType()),
  5736. _meta: objectType({
  5737. schemas: recordType(stringType(), stringType()),
  5738. tables: recordType(stringType(), stringType()),
  5739. columns: recordType(stringType(), stringType())
  5740. }),
  5741. internal: kitInternals
  5742. }).strict();
  5743. schemaInternal = objectType({
  5744. version: literalType("5"),
  5745. dialect,
  5746. tables: recordType(stringType(), table),
  5747. views: recordType(stringType(), view).default({}),
  5748. _meta: objectType({
  5749. tables: recordType(stringType(), stringType()),
  5750. columns: recordType(stringType(), stringType())
  5751. }),
  5752. internal: kitInternals
  5753. }).strict();
  5754. schemaV3 = schemaInternalV3.merge(schemaHash);
  5755. schemaV4 = schemaInternalV4.merge(schemaHash);
  5756. schemaV5 = schemaInternalV5.merge(schemaHash);
  5757. schema = schemaInternal.merge(schemaHash);
  5758. tableSquashedV4 = objectType({
  5759. name: stringType(),
  5760. schema: stringType().optional(),
  5761. columns: recordType(stringType(), column),
  5762. indexes: recordType(stringType(), stringType()),
  5763. foreignKeys: recordType(stringType(), stringType())
  5764. }).strict();
  5765. tableSquashed = objectType({
  5766. name: stringType(),
  5767. columns: recordType(stringType(), column),
  5768. indexes: recordType(stringType(), stringType()),
  5769. foreignKeys: recordType(stringType(), stringType()),
  5770. compositePrimaryKeys: recordType(stringType(), stringType()),
  5771. uniqueConstraints: recordType(stringType(), stringType()).default({}),
  5772. checkConstraints: recordType(stringType(), stringType()).default({})
  5773. }).strict();
  5774. viewSquashed = view.omit({
  5775. algorithm: true,
  5776. sqlSecurity: true,
  5777. withCheckOption: true
  5778. }).extend({ meta: stringType() });
  5779. schemaSquashed = objectType({
  5780. version: literalType("5"),
  5781. dialect,
  5782. tables: recordType(stringType(), tableSquashed),
  5783. views: recordType(stringType(), viewSquashed)
  5784. }).strict();
  5785. schemaSquashedV4 = objectType({
  5786. version: literalType("4"),
  5787. dialect,
  5788. tables: recordType(stringType(), tableSquashedV4),
  5789. schemas: recordType(stringType(), stringType())
  5790. }).strict();
  5791. MySqlSquasher = {
  5792. squashIdx: (idx) => {
  5793. index.parse(idx);
  5794. return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
  5795. },
  5796. unsquashIdx: (input) => {
  5797. const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";");
  5798. const destructed = {
  5799. name,
  5800. columns: columnsString.split(","),
  5801. isUnique: isUnique === "true",
  5802. using: using ? using : void 0,
  5803. algorithm: algorithm ? algorithm : void 0,
  5804. lock: lock ? lock : void 0
  5805. };
  5806. return index.parse(destructed);
  5807. },
  5808. squashPK: (pk) => {
  5809. return `${pk.name};${pk.columns.join(",")}`;
  5810. },
  5811. unsquashPK: (pk) => {
  5812. const splitted = pk.split(";");
  5813. return { name: splitted[0], columns: splitted[1].split(",") };
  5814. },
  5815. squashUnique: (unq) => {
  5816. return `${unq.name};${unq.columns.join(",")}`;
  5817. },
  5818. unsquashUnique: (unq) => {
  5819. const [name, columns] = unq.split(";");
  5820. return { name, columns: columns.split(",") };
  5821. },
  5822. squashFK: (fk5) => {
  5823. return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
  5824. },
  5825. unsquashFK: (input) => {
  5826. const [
  5827. name,
  5828. tableFrom,
  5829. columnsFromStr,
  5830. tableTo,
  5831. columnsToStr,
  5832. onUpdate,
  5833. onDelete
  5834. ] = input.split(";");
  5835. const result = fk.parse({
  5836. name,
  5837. tableFrom,
  5838. columnsFrom: columnsFromStr.split(","),
  5839. tableTo,
  5840. columnsTo: columnsToStr.split(","),
  5841. onUpdate,
  5842. onDelete
  5843. });
  5844. return result;
  5845. },
  5846. squashCheck: (input) => {
  5847. return `${input.name};${input.value}`;
  5848. },
  5849. unsquashCheck: (input) => {
  5850. const [name, value] = input.split(";");
  5851. return { name, value };
  5852. },
  5853. squashView: (view5) => {
  5854. return `${view5.algorithm};${view5.sqlSecurity};${view5.withCheckOption}`;
  5855. },
  5856. unsquashView: (meta) => {
  5857. const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
  5858. const toReturn = {
  5859. algorithm,
  5860. sqlSecurity,
  5861. withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
  5862. };
  5863. return viewMeta.parse(toReturn);
  5864. }
  5865. };
  5866. squashMysqlScheme = (json) => {
  5867. const mappedTables = Object.fromEntries(
  5868. Object.entries(json.tables).map((it) => {
  5869. const squashedIndexes = mapValues(it[1].indexes, (index6) => {
  5870. return MySqlSquasher.squashIdx(index6);
  5871. });
  5872. const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => {
  5873. return MySqlSquasher.squashFK(fk5);
  5874. });
  5875. const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
  5876. return MySqlSquasher.squashPK(pk);
  5877. });
  5878. const squashedUniqueConstraints = mapValues(
  5879. it[1].uniqueConstraints,
  5880. (unq) => {
  5881. return MySqlSquasher.squashUnique(unq);
  5882. }
  5883. );
  5884. const squashedCheckConstraints = mapValues(it[1].checkConstraint, (check2) => {
  5885. return MySqlSquasher.squashCheck(check2);
  5886. });
  5887. return [
  5888. it[0],
  5889. {
  5890. name: it[1].name,
  5891. columns: it[1].columns,
  5892. indexes: squashedIndexes,
  5893. foreignKeys: squashedFKs,
  5894. compositePrimaryKeys: squashedPKs,
  5895. uniqueConstraints: squashedUniqueConstraints,
  5896. checkConstraints: squashedCheckConstraints
  5897. }
  5898. ];
  5899. })
  5900. );
  5901. const mappedViews = Object.fromEntries(
  5902. Object.entries(json.views).map(([key, value]) => {
  5903. const meta = MySqlSquasher.squashView(value);
  5904. return [key, {
  5905. name: value.name,
  5906. isExisting: value.isExisting,
  5907. columns: value.columns,
  5908. definition: value.definition,
  5909. meta
  5910. }];
  5911. })
  5912. );
  5913. return {
  5914. version: "5",
  5915. dialect: json.dialect,
  5916. tables: mappedTables,
  5917. views: mappedViews
  5918. };
  5919. };
  5920. mysqlSchema = schema;
  5921. mysqlSchemaV5 = schemaV5;
  5922. mysqlSchemaSquashed = schemaSquashed;
  5923. backwardCompatibleMysqlSchema = unionType([mysqlSchemaV5, schema]);
  5924. dryMySql = mysqlSchema.parse({
  5925. version: "5",
  5926. dialect: "mysql",
  5927. id: originUUID,
  5928. prevId: "",
  5929. tables: {},
  5930. schemas: {},
  5931. views: {},
  5932. _meta: {
  5933. schemas: {},
  5934. tables: {},
  5935. columns: {}
  5936. }
  5937. });
  5938. }
  5939. });
  5940. // src/serializer/pgSchema.ts
  5941. var indexV2, columnV2, tableV2, enumSchemaV1, enumSchema, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn, index2, indexV4, indexV5, indexV6, fk2, sequenceSchema, roleSchema, sequenceSquashed, columnV7, column2, checkConstraint2, columnSquashed, tableV32, compositePK2, uniqueConstraint2, policy, policySquashed, viewWithOption, matViewWithOption, mergedViewWithOption, view2, tableV42, tableV5, tableV6, tableV7, table2, schemaHash2, kitInternals2, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed2, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
  5942. var init_pgSchema = __esm({
  5943. "src/serializer/pgSchema.ts"() {
  5944. "use strict";
  5945. init_global();
  5946. init_esm();
  5947. indexV2 = objectType({
  5948. name: stringType(),
  5949. columns: recordType(
  5950. stringType(),
  5951. objectType({
  5952. name: stringType()
  5953. })
  5954. ),
  5955. isUnique: booleanType()
  5956. }).strict();
  5957. columnV2 = objectType({
  5958. name: stringType(),
  5959. type: stringType(),
  5960. primaryKey: booleanType(),
  5961. notNull: booleanType(),
  5962. default: anyType().optional(),
  5963. references: stringType().optional()
  5964. }).strict();
  5965. tableV2 = objectType({
  5966. name: stringType(),
  5967. columns: recordType(stringType(), columnV2),
  5968. indexes: recordType(stringType(), indexV2)
  5969. }).strict();
  5970. enumSchemaV1 = objectType({
  5971. name: stringType(),
  5972. values: recordType(stringType(), stringType())
  5973. }).strict();
  5974. enumSchema = objectType({
  5975. name: stringType(),
  5976. schema: stringType(),
  5977. values: stringType().array()
  5978. }).strict();
  5979. pgSchemaV2 = objectType({
  5980. version: literalType("2"),
  5981. tables: recordType(stringType(), tableV2),
  5982. enums: recordType(stringType(), enumSchemaV1)
  5983. }).strict();
  5984. references = objectType({
  5985. foreignKeyName: stringType(),
  5986. table: stringType(),
  5987. column: stringType(),
  5988. onDelete: stringType().optional(),
  5989. onUpdate: stringType().optional()
  5990. }).strict();
  5991. columnV1 = objectType({
  5992. name: stringType(),
  5993. type: stringType(),
  5994. primaryKey: booleanType(),
  5995. notNull: booleanType(),
  5996. default: anyType().optional(),
  5997. references: references.optional()
  5998. }).strict();
  5999. tableV1 = objectType({
  6000. name: stringType(),
  6001. columns: recordType(stringType(), columnV1),
  6002. indexes: recordType(stringType(), indexV2)
  6003. }).strict();
  6004. pgSchemaV1 = objectType({
  6005. version: literalType("1"),
  6006. tables: recordType(stringType(), tableV1),
  6007. enums: recordType(stringType(), enumSchemaV1)
  6008. }).strict();
  6009. indexColumn = objectType({
  6010. expression: stringType(),
  6011. isExpression: booleanType(),
  6012. asc: booleanType(),
  6013. nulls: stringType().optional(),
  6014. opclass: stringType().optional()
  6015. });
  6016. index2 = objectType({
  6017. name: stringType(),
  6018. columns: indexColumn.array(),
  6019. isUnique: booleanType(),
  6020. with: recordType(stringType(), anyType()).optional(),
  6021. method: stringType().default("btree"),
  6022. where: stringType().optional(),
  6023. concurrently: booleanType().default(false)
  6024. }).strict();
  6025. indexV4 = objectType({
  6026. name: stringType(),
  6027. columns: stringType().array(),
  6028. isUnique: booleanType(),
  6029. with: recordType(stringType(), stringType()).optional(),
  6030. method: stringType().default("btree"),
  6031. where: stringType().optional(),
  6032. concurrently: booleanType().default(false)
  6033. }).strict();
  6034. indexV5 = objectType({
  6035. name: stringType(),
  6036. columns: stringType().array(),
  6037. isUnique: booleanType(),
  6038. with: recordType(stringType(), stringType()).optional(),
  6039. method: stringType().default("btree"),
  6040. where: stringType().optional(),
  6041. concurrently: booleanType().default(false)
  6042. }).strict();
  6043. indexV6 = objectType({
  6044. name: stringType(),
  6045. columns: stringType().array(),
  6046. isUnique: booleanType(),
  6047. with: recordType(stringType(), stringType()).optional(),
  6048. method: stringType().default("btree"),
  6049. where: stringType().optional(),
  6050. concurrently: booleanType().default(false)
  6051. }).strict();
  6052. fk2 = objectType({
  6053. name: stringType(),
  6054. tableFrom: stringType(),
  6055. columnsFrom: stringType().array(),
  6056. tableTo: stringType(),
  6057. schemaTo: stringType().optional(),
  6058. columnsTo: stringType().array(),
  6059. onUpdate: stringType().optional(),
  6060. onDelete: stringType().optional()
  6061. }).strict();
  6062. sequenceSchema = objectType({
  6063. name: stringType(),
  6064. increment: stringType().optional(),
  6065. minValue: stringType().optional(),
  6066. maxValue: stringType().optional(),
  6067. startWith: stringType().optional(),
  6068. cache: stringType().optional(),
  6069. cycle: booleanType().optional(),
  6070. schema: stringType()
  6071. }).strict();
  6072. roleSchema = objectType({
  6073. name: stringType(),
  6074. createDb: booleanType().optional(),
  6075. createRole: booleanType().optional(),
  6076. inherit: booleanType().optional()
  6077. }).strict();
  6078. sequenceSquashed = objectType({
  6079. name: stringType(),
  6080. schema: stringType(),
  6081. values: stringType()
  6082. }).strict();
  6083. columnV7 = objectType({
  6084. name: stringType(),
  6085. type: stringType(),
  6086. typeSchema: stringType().optional(),
  6087. primaryKey: booleanType(),
  6088. notNull: booleanType(),
  6089. default: anyType().optional(),
  6090. isUnique: anyType().optional(),
  6091. uniqueName: stringType().optional(),
  6092. nullsNotDistinct: booleanType().optional()
  6093. }).strict();
  6094. column2 = objectType({
  6095. name: stringType(),
  6096. type: stringType(),
  6097. typeSchema: stringType().optional(),
  6098. primaryKey: booleanType(),
  6099. notNull: booleanType(),
  6100. default: anyType().optional(),
  6101. isUnique: anyType().optional(),
  6102. uniqueName: stringType().optional(),
  6103. nullsNotDistinct: booleanType().optional(),
  6104. generated: objectType({
  6105. type: literalType("stored"),
  6106. as: stringType()
  6107. }).optional(),
  6108. identity: sequenceSchema.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
  6109. }).strict();
  6110. checkConstraint2 = objectType({
  6111. name: stringType(),
  6112. value: stringType()
  6113. }).strict();
  6114. columnSquashed = objectType({
  6115. name: stringType(),
  6116. type: stringType(),
  6117. typeSchema: stringType().optional(),
  6118. primaryKey: booleanType(),
  6119. notNull: booleanType(),
  6120. default: anyType().optional(),
  6121. isUnique: anyType().optional(),
  6122. uniqueName: stringType().optional(),
  6123. nullsNotDistinct: booleanType().optional(),
  6124. generated: objectType({
  6125. type: literalType("stored"),
  6126. as: stringType()
  6127. }).optional(),
  6128. identity: stringType().optional()
  6129. }).strict();
  6130. tableV32 = objectType({
  6131. name: stringType(),
  6132. columns: recordType(stringType(), column2),
  6133. indexes: recordType(stringType(), index2),
  6134. foreignKeys: recordType(stringType(), fk2)
  6135. }).strict();
  6136. compositePK2 = objectType({
  6137. name: stringType(),
  6138. columns: stringType().array()
  6139. }).strict();
  6140. uniqueConstraint2 = objectType({
  6141. name: stringType(),
  6142. columns: stringType().array(),
  6143. nullsNotDistinct: booleanType()
  6144. }).strict();
  6145. policy = objectType({
  6146. name: stringType(),
  6147. as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
  6148. for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
  6149. to: stringType().array().optional(),
  6150. using: stringType().optional(),
  6151. withCheck: stringType().optional(),
  6152. on: stringType().optional(),
  6153. schema: stringType().optional()
  6154. }).strict();
  6155. policySquashed = objectType({
  6156. name: stringType(),
  6157. values: stringType()
  6158. }).strict();
  6159. viewWithOption = objectType({
  6160. checkOption: enumType(["local", "cascaded"]).optional(),
  6161. securityBarrier: booleanType().optional(),
  6162. securityInvoker: booleanType().optional()
  6163. }).strict();
  6164. matViewWithOption = objectType({
  6165. fillfactor: numberType().optional(),
  6166. toastTupleTarget: numberType().optional(),
  6167. parallelWorkers: numberType().optional(),
  6168. autovacuumEnabled: booleanType().optional(),
  6169. vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
  6170. vacuumTruncate: booleanType().optional(),
  6171. autovacuumVacuumThreshold: numberType().optional(),
  6172. autovacuumVacuumScaleFactor: numberType().optional(),
  6173. autovacuumVacuumCostDelay: numberType().optional(),
  6174. autovacuumVacuumCostLimit: numberType().optional(),
  6175. autovacuumFreezeMinAge: numberType().optional(),
  6176. autovacuumFreezeMaxAge: numberType().optional(),
  6177. autovacuumFreezeTableAge: numberType().optional(),
  6178. autovacuumMultixactFreezeMinAge: numberType().optional(),
  6179. autovacuumMultixactFreezeMaxAge: numberType().optional(),
  6180. autovacuumMultixactFreezeTableAge: numberType().optional(),
  6181. logAutovacuumMinDuration: numberType().optional(),
  6182. userCatalogTable: booleanType().optional()
  6183. }).strict();
  6184. mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
  6185. view2 = objectType({
  6186. name: stringType(),
  6187. schema: stringType(),
  6188. columns: recordType(stringType(), column2),
  6189. definition: stringType().optional(),
  6190. materialized: booleanType(),
  6191. with: mergedViewWithOption.optional(),
  6192. isExisting: booleanType(),
  6193. withNoData: booleanType().optional(),
  6194. using: stringType().optional(),
  6195. tablespace: stringType().optional()
  6196. }).strict();
  6197. tableV42 = objectType({
  6198. name: stringType(),
  6199. schema: stringType(),
  6200. columns: recordType(stringType(), column2),
  6201. indexes: recordType(stringType(), indexV4),
  6202. foreignKeys: recordType(stringType(), fk2)
  6203. }).strict();
  6204. tableV5 = objectType({
  6205. name: stringType(),
  6206. schema: stringType(),
  6207. columns: recordType(stringType(), column2),
  6208. indexes: recordType(stringType(), indexV5),
  6209. foreignKeys: recordType(stringType(), fk2),
  6210. compositePrimaryKeys: recordType(stringType(), compositePK2),
  6211. uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
  6212. }).strict();
  6213. tableV6 = objectType({
  6214. name: stringType(),
  6215. schema: stringType(),
  6216. columns: recordType(stringType(), column2),
  6217. indexes: recordType(stringType(), indexV6),
  6218. foreignKeys: recordType(stringType(), fk2),
  6219. compositePrimaryKeys: recordType(stringType(), compositePK2),
  6220. uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
  6221. }).strict();
  6222. tableV7 = objectType({
  6223. name: stringType(),
  6224. schema: stringType(),
  6225. columns: recordType(stringType(), columnV7),
  6226. indexes: recordType(stringType(), index2),
  6227. foreignKeys: recordType(stringType(), fk2),
  6228. compositePrimaryKeys: recordType(stringType(), compositePK2),
  6229. uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({})
  6230. }).strict();
  6231. table2 = objectType({
  6232. name: stringType(),
  6233. schema: stringType(),
  6234. columns: recordType(stringType(), column2),
  6235. indexes: recordType(stringType(), index2),
  6236. foreignKeys: recordType(stringType(), fk2),
  6237. compositePrimaryKeys: recordType(stringType(), compositePK2),
  6238. uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
  6239. policies: recordType(stringType(), policy).default({}),
  6240. checkConstraints: recordType(stringType(), checkConstraint2).default({}),
  6241. isRLSEnabled: booleanType().default(false)
  6242. }).strict();
  6243. schemaHash2 = objectType({
  6244. id: stringType(),
  6245. prevId: stringType()
  6246. });
  6247. kitInternals2 = objectType({
  6248. tables: recordType(
  6249. stringType(),
  6250. objectType({
  6251. columns: recordType(
  6252. stringType(),
  6253. objectType({
  6254. isArray: booleanType().optional(),
  6255. dimensions: numberType().optional(),
  6256. rawType: stringType().optional(),
  6257. isDefaultAnExpression: booleanType().optional()
  6258. }).optional()
  6259. )
  6260. }).optional()
  6261. )
  6262. }).optional();
  6263. pgSchemaInternalV3 = objectType({
  6264. version: literalType("3"),
  6265. dialect: literalType("pg"),
  6266. tables: recordType(stringType(), tableV32),
  6267. enums: recordType(stringType(), enumSchemaV1)
  6268. }).strict();
  6269. pgSchemaInternalV4 = objectType({
  6270. version: literalType("4"),
  6271. dialect: literalType("pg"),
  6272. tables: recordType(stringType(), tableV42),
  6273. enums: recordType(stringType(), enumSchemaV1),
  6274. schemas: recordType(stringType(), stringType())
  6275. }).strict();
  6276. pgSchemaInternalV5 = objectType({
  6277. version: literalType("5"),
  6278. dialect: literalType("pg"),
  6279. tables: recordType(stringType(), tableV5),
  6280. enums: recordType(stringType(), enumSchemaV1),
  6281. schemas: recordType(stringType(), stringType()),
  6282. _meta: objectType({
  6283. schemas: recordType(stringType(), stringType()),
  6284. tables: recordType(stringType(), stringType()),
  6285. columns: recordType(stringType(), stringType())
  6286. }),
  6287. internal: kitInternals2
  6288. }).strict();
  6289. pgSchemaInternalV6 = objectType({
  6290. version: literalType("6"),
  6291. dialect: literalType("postgresql"),
  6292. tables: recordType(stringType(), tableV6),
  6293. enums: recordType(stringType(), enumSchema),
  6294. schemas: recordType(stringType(), stringType()),
  6295. _meta: objectType({
  6296. schemas: recordType(stringType(), stringType()),
  6297. tables: recordType(stringType(), stringType()),
  6298. columns: recordType(stringType(), stringType())
  6299. }),
  6300. internal: kitInternals2
  6301. }).strict();
  6302. pgSchemaExternal = objectType({
  6303. version: literalType("5"),
  6304. dialect: literalType("pg"),
  6305. tables: arrayType(table2),
  6306. enums: arrayType(enumSchemaV1),
  6307. schemas: arrayType(objectType({ name: stringType() })),
  6308. _meta: objectType({
  6309. schemas: recordType(stringType(), stringType()),
  6310. tables: recordType(stringType(), stringType()),
  6311. columns: recordType(stringType(), stringType())
  6312. })
  6313. }).strict();
  6314. pgSchemaInternalV7 = objectType({
  6315. version: literalType("7"),
  6316. dialect: literalType("postgresql"),
  6317. tables: recordType(stringType(), tableV7),
  6318. enums: recordType(stringType(), enumSchema),
  6319. schemas: recordType(stringType(), stringType()),
  6320. sequences: recordType(stringType(), sequenceSchema),
  6321. _meta: objectType({
  6322. schemas: recordType(stringType(), stringType()),
  6323. tables: recordType(stringType(), stringType()),
  6324. columns: recordType(stringType(), stringType())
  6325. }),
  6326. internal: kitInternals2
  6327. }).strict();
  6328. pgSchemaInternal = objectType({
  6329. version: literalType("7"),
  6330. dialect: literalType("postgresql"),
  6331. tables: recordType(stringType(), table2),
  6332. enums: recordType(stringType(), enumSchema),
  6333. schemas: recordType(stringType(), stringType()),
  6334. views: recordType(stringType(), view2).default({}),
  6335. sequences: recordType(stringType(), sequenceSchema).default({}),
  6336. roles: recordType(stringType(), roleSchema).default({}),
  6337. policies: recordType(stringType(), policy).default({}),
  6338. _meta: objectType({
  6339. schemas: recordType(stringType(), stringType()),
  6340. tables: recordType(stringType(), stringType()),
  6341. columns: recordType(stringType(), stringType())
  6342. }),
  6343. internal: kitInternals2
  6344. }).strict();
  6345. tableSquashed2 = objectType({
  6346. name: stringType(),
  6347. schema: stringType(),
  6348. columns: recordType(stringType(), columnSquashed),
  6349. indexes: recordType(stringType(), stringType()),
  6350. foreignKeys: recordType(stringType(), stringType()),
  6351. compositePrimaryKeys: recordType(stringType(), stringType()),
  6352. uniqueConstraints: recordType(stringType(), stringType()),
  6353. policies: recordType(stringType(), stringType()),
  6354. checkConstraints: recordType(stringType(), stringType()),
  6355. isRLSEnabled: booleanType().default(false)
  6356. }).strict();
  6357. tableSquashedV42 = objectType({
  6358. name: stringType(),
  6359. schema: stringType(),
  6360. columns: recordType(stringType(), column2),
  6361. indexes: recordType(stringType(), stringType()),
  6362. foreignKeys: recordType(stringType(), stringType())
  6363. }).strict();
  6364. pgSchemaSquashedV4 = objectType({
  6365. version: literalType("4"),
  6366. dialect: literalType("pg"),
  6367. tables: recordType(stringType(), tableSquashedV42),
  6368. enums: recordType(stringType(), enumSchemaV1),
  6369. schemas: recordType(stringType(), stringType())
  6370. }).strict();
  6371. pgSchemaSquashedV6 = objectType({
  6372. version: literalType("6"),
  6373. dialect: literalType("postgresql"),
  6374. tables: recordType(stringType(), tableSquashed2),
  6375. enums: recordType(stringType(), enumSchema),
  6376. schemas: recordType(stringType(), stringType())
  6377. }).strict();
  6378. pgSchemaSquashed = objectType({
  6379. version: literalType("7"),
  6380. dialect: literalType("postgresql"),
  6381. tables: recordType(stringType(), tableSquashed2),
  6382. enums: recordType(stringType(), enumSchema),
  6383. schemas: recordType(stringType(), stringType()),
  6384. views: recordType(stringType(), view2),
  6385. sequences: recordType(stringType(), sequenceSquashed),
  6386. roles: recordType(stringType(), roleSchema).default({}),
  6387. policies: recordType(stringType(), policySquashed).default({})
  6388. }).strict();
  6389. pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash2);
  6390. pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash2);
  6391. pgSchemaV5 = pgSchemaInternalV5.merge(schemaHash2);
  6392. pgSchemaV6 = pgSchemaInternalV6.merge(schemaHash2);
  6393. pgSchemaV7 = pgSchemaInternalV7.merge(schemaHash2);
  6394. pgSchema = pgSchemaInternal.merge(schemaHash2);
  6395. backwardCompatiblePgSchema = unionType([
  6396. pgSchemaV5,
  6397. pgSchemaV6,
  6398. pgSchema
  6399. ]);
  6400. PgSquasher = {
  6401. squashIdx: (idx) => {
  6402. index2.parse(idx);
  6403. return `${idx.name};${idx.columns.map(
  6404. (c3) => `${c3.expression}--${c3.isExpression}--${c3.asc}--${c3.nulls}--${c3.opclass ? c3.opclass : ""}`
  6405. ).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
  6406. },
  6407. unsquashIdx: (input) => {
  6408. const [
  6409. name,
  6410. columnsString,
  6411. isUnique,
  6412. concurrently,
  6413. method,
  6414. where,
  6415. idxWith
  6416. ] = input.split(";");
  6417. const columnString = columnsString.split(",,");
  6418. const columns = [];
  6419. for (const column11 of columnString) {
  6420. const [expression, isExpression, asc, nulls, opclass] = column11.split("--");
  6421. columns.push({
  6422. nulls,
  6423. isExpression: isExpression === "true",
  6424. asc: asc === "true",
  6425. expression,
  6426. opclass: opclass === "undefined" ? void 0 : opclass
  6427. });
  6428. }
  6429. const result = index2.parse({
  6430. name,
  6431. columns,
  6432. isUnique: isUnique === "true",
  6433. concurrently: concurrently === "true",
  6434. method,
  6435. where: where === "undefined" ? void 0 : where,
  6436. with: !idxWith || idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
  6437. });
  6438. return result;
  6439. },
  6440. squashIdxPush: (idx) => {
  6441. index2.parse(idx);
  6442. return `${idx.name};${idx.columns.map((c3) => `${c3.isExpression ? "" : c3.expression}--${c3.asc}--${c3.nulls}`).join(",,")};${idx.isUnique};${idx.method};${JSON.stringify(idx.with)}`;
  6443. },
  6444. unsquashIdxPush: (input) => {
  6445. const [name, columnsString, isUnique, method, idxWith] = input.split(";");
  6446. const columnString = columnsString.split("--");
  6447. const columns = [];
  6448. for (const column11 of columnString) {
  6449. const [expression, asc, nulls, opclass] = column11.split(",");
  6450. columns.push({
  6451. nulls,
  6452. isExpression: expression === "",
  6453. asc: asc === "true",
  6454. expression
  6455. });
  6456. }
  6457. const result = index2.parse({
  6458. name,
  6459. columns,
  6460. isUnique: isUnique === "true",
  6461. concurrently: false,
  6462. method,
  6463. with: idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
  6464. });
  6465. return result;
  6466. },
  6467. squashFK: (fk5) => {
  6468. return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""};${fk5.schemaTo || "public"}`;
  6469. },
  6470. squashPolicy: (policy5) => {
  6471. var _a2;
  6472. return `${policy5.name}--${policy5.as}--${policy5.for}--${(_a2 = policy5.to) == null ? void 0 : _a2.join(",")}--${policy5.using}--${policy5.withCheck}--${policy5.on}`;
  6473. },
  6474. unsquashPolicy: (policy5) => {
  6475. const splitted = policy5.split("--");
  6476. return {
  6477. name: splitted[0],
  6478. as: splitted[1],
  6479. for: splitted[2],
  6480. to: splitted[3].split(","),
  6481. using: splitted[4] !== "undefined" ? splitted[4] : void 0,
  6482. withCheck: splitted[5] !== "undefined" ? splitted[5] : void 0,
  6483. on: splitted[6] !== "undefined" ? splitted[6] : void 0
  6484. };
  6485. },
  6486. squashPolicyPush: (policy5) => {
  6487. var _a2;
  6488. return `${policy5.name}--${policy5.as}--${policy5.for}--${(_a2 = policy5.to) == null ? void 0 : _a2.join(",")}--${policy5.on}`;
  6489. },
  6490. unsquashPolicyPush: (policy5) => {
  6491. const splitted = policy5.split("--");
  6492. return {
  6493. name: splitted[0],
  6494. as: splitted[1],
  6495. for: splitted[2],
  6496. to: splitted[3].split(","),
  6497. on: splitted[4] !== "undefined" ? splitted[4] : void 0
  6498. };
  6499. },
  6500. squashPK: (pk) => {
  6501. return `${pk.columns.join(",")};${pk.name}`;
  6502. },
  6503. unsquashPK: (pk) => {
  6504. const splitted = pk.split(";");
  6505. return { name: splitted[1], columns: splitted[0].split(",") };
  6506. },
  6507. squashUnique: (unq) => {
  6508. return `${unq.name};${unq.columns.join(",")};${unq.nullsNotDistinct}`;
  6509. },
  6510. unsquashUnique: (unq) => {
  6511. const [name, columns, nullsNotDistinct] = unq.split(";");
  6512. return {
  6513. name,
  6514. columns: columns.split(","),
  6515. nullsNotDistinct: nullsNotDistinct === "true"
  6516. };
  6517. },
  6518. unsquashFK: (input) => {
  6519. const [
  6520. name,
  6521. tableFrom,
  6522. columnsFromStr,
  6523. tableTo,
  6524. columnsToStr,
  6525. onUpdate,
  6526. onDelete,
  6527. schemaTo
  6528. ] = input.split(";");
  6529. const result = fk2.parse({
  6530. name,
  6531. tableFrom,
  6532. columnsFrom: columnsFromStr.split(","),
  6533. schemaTo,
  6534. tableTo,
  6535. columnsTo: columnsToStr.split(","),
  6536. onUpdate,
  6537. onDelete
  6538. });
  6539. return result;
  6540. },
  6541. squashSequence: (seq) => {
  6542. return `${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
  6543. },
  6544. unsquashSequence: (seq) => {
  6545. const splitted = seq.split(";");
  6546. return {
  6547. minValue: splitted[0] !== "undefined" ? splitted[0] : void 0,
  6548. maxValue: splitted[1] !== "undefined" ? splitted[1] : void 0,
  6549. increment: splitted[2] !== "undefined" ? splitted[2] : void 0,
  6550. startWith: splitted[3] !== "undefined" ? splitted[3] : void 0,
  6551. cache: splitted[4] !== "undefined" ? splitted[4] : void 0,
  6552. cycle: splitted[5] === "true"
  6553. };
  6554. },
  6555. squashIdentity: (seq) => {
  6556. return `${seq.name};${seq.type};${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
  6557. },
  6558. unsquashIdentity: (seq) => {
  6559. const splitted = seq.split(";");
  6560. return {
  6561. name: splitted[0],
  6562. type: splitted[1],
  6563. minValue: splitted[2] !== "undefined" ? splitted[2] : void 0,
  6564. maxValue: splitted[3] !== "undefined" ? splitted[3] : void 0,
  6565. increment: splitted[4] !== "undefined" ? splitted[4] : void 0,
  6566. startWith: splitted[5] !== "undefined" ? splitted[5] : void 0,
  6567. cache: splitted[6] !== "undefined" ? splitted[6] : void 0,
  6568. cycle: splitted[7] === "true"
  6569. };
  6570. },
  6571. squashCheck: (check2) => {
  6572. return `${check2.name};${check2.value}`;
  6573. },
  6574. unsquashCheck: (input) => {
  6575. const [
  6576. name,
  6577. value
  6578. ] = input.split(";");
  6579. return { name, value };
  6580. }
  6581. };
  6582. squashPgScheme = (json, action) => {
  6583. const mappedTables = Object.fromEntries(
  6584. Object.entries(json.tables).map((it) => {
  6585. const squashedIndexes = mapValues(it[1].indexes, (index6) => {
  6586. return action === "push" ? PgSquasher.squashIdxPush(index6) : PgSquasher.squashIdx(index6);
  6587. });
  6588. const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => {
  6589. return PgSquasher.squashFK(fk5);
  6590. });
  6591. const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
  6592. return PgSquasher.squashPK(pk);
  6593. });
  6594. const mappedColumns = Object.fromEntries(
  6595. Object.entries(it[1].columns).map((it2) => {
  6596. const mappedIdentity = it2[1].identity ? PgSquasher.squashIdentity(it2[1].identity) : void 0;
  6597. return [
  6598. it2[0],
  6599. {
  6600. ...it2[1],
  6601. identity: mappedIdentity
  6602. }
  6603. ];
  6604. })
  6605. );
  6606. const squashedUniqueConstraints = mapValues(
  6607. it[1].uniqueConstraints,
  6608. (unq) => {
  6609. return PgSquasher.squashUnique(unq);
  6610. }
  6611. );
  6612. const squashedPolicies = mapValues(it[1].policies, (policy5) => {
  6613. return action === "push" ? PgSquasher.squashPolicyPush(policy5) : PgSquasher.squashPolicy(policy5);
  6614. });
  6615. const squashedChecksContraints = mapValues(
  6616. it[1].checkConstraints,
  6617. (check2) => {
  6618. return PgSquasher.squashCheck(check2);
  6619. }
  6620. );
  6621. return [
  6622. it[0],
  6623. {
  6624. name: it[1].name,
  6625. schema: it[1].schema,
  6626. columns: mappedColumns,
  6627. indexes: squashedIndexes,
  6628. foreignKeys: squashedFKs,
  6629. compositePrimaryKeys: squashedPKs,
  6630. uniqueConstraints: squashedUniqueConstraints,
  6631. policies: squashedPolicies,
  6632. checkConstraints: squashedChecksContraints,
  6633. isRLSEnabled: it[1].isRLSEnabled ?? false
  6634. }
  6635. ];
  6636. })
  6637. );
  6638. const mappedSequences = Object.fromEntries(
  6639. Object.entries(json.sequences).map((it) => {
  6640. return [
  6641. it[0],
  6642. {
  6643. name: it[1].name,
  6644. schema: it[1].schema,
  6645. values: PgSquasher.squashSequence(it[1])
  6646. }
  6647. ];
  6648. })
  6649. );
  6650. const mappedPolicies = Object.fromEntries(
  6651. Object.entries(json.policies).map((it) => {
  6652. return [
  6653. it[0],
  6654. {
  6655. name: it[1].name,
  6656. values: action === "push" ? PgSquasher.squashPolicyPush(it[1]) : PgSquasher.squashPolicy(it[1])
  6657. }
  6658. ];
  6659. })
  6660. );
  6661. return {
  6662. version: "7",
  6663. dialect: json.dialect,
  6664. tables: mappedTables,
  6665. enums: json.enums,
  6666. schemas: json.schemas,
  6667. views: json.views,
  6668. policies: mappedPolicies,
  6669. sequences: mappedSequences,
  6670. roles: json.roles
  6671. };
  6672. };
  6673. dryPg = pgSchema.parse({
  6674. version: snapshotVersion,
  6675. dialect: "postgresql",
  6676. id: originUUID,
  6677. prevId: "",
  6678. tables: {},
  6679. enums: {},
  6680. schemas: {},
  6681. policies: {},
  6682. roles: {},
  6683. sequences: {},
  6684. _meta: {
  6685. schemas: {},
  6686. tables: {},
  6687. columns: {}
  6688. }
  6689. });
  6690. }
  6691. });
  6692. // src/serializer/singlestoreSchema.ts
  6693. var index3, column3, compositePK3, uniqueConstraint3, table3, viewMeta2, kitInternals3, dialect2, schemaHash3, schemaInternal2, schema2, tableSquashed3, schemaSquashed2, SingleStoreSquasher, squashSingleStoreScheme, singlestoreSchema, singlestoreSchemaSquashed, backwardCompatibleSingleStoreSchema, drySingleStore;
  6694. var init_singlestoreSchema = __esm({
  6695. "src/serializer/singlestoreSchema.ts"() {
  6696. "use strict";
  6697. init_esm();
  6698. init_global();
  6699. index3 = objectType({
  6700. name: stringType(),
  6701. columns: stringType().array(),
  6702. isUnique: booleanType(),
  6703. using: enumType(["btree", "hash"]).optional(),
  6704. algorithm: enumType(["default", "inplace", "copy"]).optional(),
  6705. lock: enumType(["default", "none", "shared", "exclusive"]).optional()
  6706. }).strict();
  6707. column3 = objectType({
  6708. name: stringType(),
  6709. type: stringType(),
  6710. primaryKey: booleanType(),
  6711. notNull: booleanType(),
  6712. autoincrement: booleanType().optional(),
  6713. default: anyType().optional(),
  6714. onUpdate: anyType().optional(),
  6715. generated: objectType({
  6716. type: enumType(["stored", "virtual"]),
  6717. as: stringType()
  6718. }).optional()
  6719. }).strict();
  6720. compositePK3 = objectType({
  6721. name: stringType(),
  6722. columns: stringType().array()
  6723. }).strict();
  6724. uniqueConstraint3 = objectType({
  6725. name: stringType(),
  6726. columns: stringType().array()
  6727. }).strict();
  6728. table3 = objectType({
  6729. name: stringType(),
  6730. columns: recordType(stringType(), column3),
  6731. indexes: recordType(stringType(), index3),
  6732. compositePrimaryKeys: recordType(stringType(), compositePK3),
  6733. uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
  6734. }).strict();
  6735. viewMeta2 = objectType({
  6736. algorithm: enumType(["undefined", "merge", "temptable"]),
  6737. sqlSecurity: enumType(["definer", "invoker"]),
  6738. withCheckOption: enumType(["local", "cascaded"]).optional()
  6739. }).strict();
  6740. kitInternals3 = objectType({
  6741. tables: recordType(
  6742. stringType(),
  6743. objectType({
  6744. columns: recordType(
  6745. stringType(),
  6746. objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
  6747. )
  6748. }).optional()
  6749. ).optional(),
  6750. indexes: recordType(
  6751. stringType(),
  6752. objectType({
  6753. columns: recordType(
  6754. stringType(),
  6755. objectType({ isExpression: booleanType().optional() }).optional()
  6756. )
  6757. }).optional()
  6758. ).optional()
  6759. }).optional();
  6760. dialect2 = literalType("singlestore");
  6761. schemaHash3 = objectType({
  6762. id: stringType(),
  6763. prevId: stringType()
  6764. });
  6765. schemaInternal2 = objectType({
  6766. version: literalType("1"),
  6767. dialect: dialect2,
  6768. tables: recordType(stringType(), table3),
  6769. /* views: record(string(), view).default({}), */
  6770. _meta: objectType({
  6771. tables: recordType(stringType(), stringType()),
  6772. columns: recordType(stringType(), stringType())
  6773. }),
  6774. internal: kitInternals3
  6775. }).strict();
  6776. schema2 = schemaInternal2.merge(schemaHash3);
  6777. tableSquashed3 = objectType({
  6778. name: stringType(),
  6779. columns: recordType(stringType(), column3),
  6780. indexes: recordType(stringType(), stringType()),
  6781. compositePrimaryKeys: recordType(stringType(), stringType()),
  6782. uniqueConstraints: recordType(stringType(), stringType()).default({})
  6783. }).strict();
  6784. schemaSquashed2 = objectType({
  6785. version: literalType("1"),
  6786. dialect: dialect2,
  6787. tables: recordType(stringType(), tableSquashed3)
  6788. /* views: record(string(), viewSquashed), */
  6789. }).strict();
  6790. SingleStoreSquasher = {
  6791. squashIdx: (idx) => {
  6792. index3.parse(idx);
  6793. return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
  6794. },
  6795. unsquashIdx: (input) => {
  6796. const [name, columnsString, isUnique, using, algorithm, lock] = input.split(";");
  6797. const destructed = {
  6798. name,
  6799. columns: columnsString.split(","),
  6800. isUnique: isUnique === "true",
  6801. using: using ? using : void 0,
  6802. algorithm: algorithm ? algorithm : void 0,
  6803. lock: lock ? lock : void 0
  6804. };
  6805. return index3.parse(destructed);
  6806. },
  6807. squashPK: (pk) => {
  6808. return `${pk.name};${pk.columns.join(",")}`;
  6809. },
  6810. unsquashPK: (pk) => {
  6811. const splitted = pk.split(";");
  6812. return { name: splitted[0], columns: splitted[1].split(",") };
  6813. },
  6814. squashUnique: (unq) => {
  6815. return `${unq.name};${unq.columns.join(",")}`;
  6816. },
  6817. unsquashUnique: (unq) => {
  6818. const [name, columns] = unq.split(";");
  6819. return { name, columns: columns.split(",") };
  6820. }
  6821. /* squashView: (view: View): string => {
  6822. return `${view.algorithm};${view.sqlSecurity};${view.withCheckOption}`;
  6823. },
  6824. unsquashView: (meta: string): SquasherViewMeta => {
  6825. const [algorithm, sqlSecurity, withCheckOption] = meta.split(';');
  6826. const toReturn = {
  6827. algorithm: algorithm,
  6828. sqlSecurity: sqlSecurity,
  6829. withCheckOption: withCheckOption !== 'undefined' ? withCheckOption : undefined,
  6830. };
  6831. return viewMeta.parse(toReturn);
  6832. }, */
  6833. };
  6834. squashSingleStoreScheme = (json) => {
  6835. const mappedTables = Object.fromEntries(
  6836. Object.entries(json.tables).map((it) => {
  6837. const squashedIndexes = mapValues(it[1].indexes, (index6) => {
  6838. return SingleStoreSquasher.squashIdx(index6);
  6839. });
  6840. const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
  6841. return SingleStoreSquasher.squashPK(pk);
  6842. });
  6843. const squashedUniqueConstraints = mapValues(
  6844. it[1].uniqueConstraints,
  6845. (unq) => {
  6846. return SingleStoreSquasher.squashUnique(unq);
  6847. }
  6848. );
  6849. return [
  6850. it[0],
  6851. {
  6852. name: it[1].name,
  6853. columns: it[1].columns,
  6854. indexes: squashedIndexes,
  6855. compositePrimaryKeys: squashedPKs,
  6856. uniqueConstraints: squashedUniqueConstraints
  6857. }
  6858. ];
  6859. })
  6860. );
  6861. return {
  6862. version: "1",
  6863. dialect: json.dialect,
  6864. tables: mappedTables
  6865. /* views: mappedViews, */
  6866. };
  6867. };
  6868. singlestoreSchema = schema2;
  6869. singlestoreSchemaSquashed = schemaSquashed2;
  6870. backwardCompatibleSingleStoreSchema = unionType([singlestoreSchema, schema2]);
  6871. drySingleStore = singlestoreSchema.parse({
  6872. version: "1",
  6873. dialect: "singlestore",
  6874. id: originUUID,
  6875. prevId: "",
  6876. tables: {},
  6877. schemas: {},
  6878. /* views: {}, */
  6879. _meta: {
  6880. schemas: {},
  6881. tables: {},
  6882. columns: {}
  6883. }
  6884. });
  6885. }
  6886. });
  6887. // src/serializer/sqliteSchema.ts
  6888. var index4, fk3, compositePK4, column4, tableV33, uniqueConstraint4, checkConstraint3, table4, view3, dialect3, schemaHash4, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals4, latestVersion, schemaInternal3, schemaV32, schemaV42, schemaV52, schema3, tableSquashed4, schemaSquashed3, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
  6889. var init_sqliteSchema = __esm({
  6890. "src/serializer/sqliteSchema.ts"() {
  6891. "use strict";
  6892. init_esm();
  6893. init_global();
  6894. index4 = objectType({
  6895. name: stringType(),
  6896. columns: stringType().array(),
  6897. where: stringType().optional(),
  6898. isUnique: booleanType()
  6899. }).strict();
  6900. fk3 = objectType({
  6901. name: stringType(),
  6902. tableFrom: stringType(),
  6903. columnsFrom: stringType().array(),
  6904. tableTo: stringType(),
  6905. columnsTo: stringType().array(),
  6906. onUpdate: stringType().optional(),
  6907. onDelete: stringType().optional()
  6908. }).strict();
  6909. compositePK4 = objectType({
  6910. columns: stringType().array(),
  6911. name: stringType().optional()
  6912. }).strict();
  6913. column4 = objectType({
  6914. name: stringType(),
  6915. type: stringType(),
  6916. primaryKey: booleanType(),
  6917. notNull: booleanType(),
  6918. autoincrement: booleanType().optional(),
  6919. default: anyType().optional(),
  6920. generated: objectType({
  6921. type: enumType(["stored", "virtual"]),
  6922. as: stringType()
  6923. }).optional()
  6924. }).strict();
  6925. tableV33 = objectType({
  6926. name: stringType(),
  6927. columns: recordType(stringType(), column4),
  6928. indexes: recordType(stringType(), index4),
  6929. foreignKeys: recordType(stringType(), fk3)
  6930. }).strict();
  6931. uniqueConstraint4 = objectType({
  6932. name: stringType(),
  6933. columns: stringType().array()
  6934. }).strict();
  6935. checkConstraint3 = objectType({
  6936. name: stringType(),
  6937. value: stringType()
  6938. }).strict();
  6939. table4 = objectType({
  6940. name: stringType(),
  6941. columns: recordType(stringType(), column4),
  6942. indexes: recordType(stringType(), index4),
  6943. foreignKeys: recordType(stringType(), fk3),
  6944. compositePrimaryKeys: recordType(stringType(), compositePK4),
  6945. uniqueConstraints: recordType(stringType(), uniqueConstraint4).default({}),
  6946. checkConstraints: recordType(stringType(), checkConstraint3).default({})
  6947. }).strict();
  6948. view3 = objectType({
  6949. name: stringType(),
  6950. columns: recordType(stringType(), column4),
  6951. definition: stringType().optional(),
  6952. isExisting: booleanType()
  6953. }).strict();
  6954. dialect3 = enumType(["sqlite"]);
  6955. schemaHash4 = objectType({
  6956. id: stringType(),
  6957. prevId: stringType()
  6958. }).strict();
  6959. schemaInternalV32 = objectType({
  6960. version: literalType("3"),
  6961. dialect: dialect3,
  6962. tables: recordType(stringType(), tableV33),
  6963. enums: objectType({})
  6964. }).strict();
  6965. schemaInternalV42 = objectType({
  6966. version: literalType("4"),
  6967. dialect: dialect3,
  6968. tables: recordType(stringType(), table4),
  6969. views: recordType(stringType(), view3).default({}),
  6970. enums: objectType({})
  6971. }).strict();
  6972. schemaInternalV52 = objectType({
  6973. version: literalType("5"),
  6974. dialect: dialect3,
  6975. tables: recordType(stringType(), table4),
  6976. enums: objectType({}),
  6977. _meta: objectType({
  6978. tables: recordType(stringType(), stringType()),
  6979. columns: recordType(stringType(), stringType())
  6980. })
  6981. }).strict();
  6982. kitInternals4 = objectType({
  6983. indexes: recordType(
  6984. stringType(),
  6985. objectType({
  6986. columns: recordType(
  6987. stringType(),
  6988. objectType({ isExpression: booleanType().optional() }).optional()
  6989. )
  6990. }).optional()
  6991. ).optional()
  6992. }).optional();
  6993. latestVersion = literalType("6");
  6994. schemaInternal3 = objectType({
  6995. version: latestVersion,
  6996. dialect: dialect3,
  6997. tables: recordType(stringType(), table4),
  6998. views: recordType(stringType(), view3).default({}),
  6999. enums: objectType({}),
  7000. _meta: objectType({
  7001. tables: recordType(stringType(), stringType()),
  7002. columns: recordType(stringType(), stringType())
  7003. }),
  7004. internal: kitInternals4
  7005. }).strict();
  7006. schemaV32 = schemaInternalV32.merge(schemaHash4).strict();
  7007. schemaV42 = schemaInternalV42.merge(schemaHash4).strict();
  7008. schemaV52 = schemaInternalV52.merge(schemaHash4).strict();
  7009. schema3 = schemaInternal3.merge(schemaHash4).strict();
  7010. tableSquashed4 = objectType({
  7011. name: stringType(),
  7012. columns: recordType(stringType(), column4),
  7013. indexes: recordType(stringType(), stringType()),
  7014. foreignKeys: recordType(stringType(), stringType()),
  7015. compositePrimaryKeys: recordType(stringType(), stringType()),
  7016. uniqueConstraints: recordType(stringType(), stringType()).default({}),
  7017. checkConstraints: recordType(stringType(), stringType()).default({})
  7018. }).strict();
  7019. schemaSquashed3 = objectType({
  7020. version: latestVersion,
  7021. dialect: dialect3,
  7022. tables: recordType(stringType(), tableSquashed4),
  7023. views: recordType(stringType(), view3),
  7024. enums: anyType()
  7025. }).strict();
  7026. SQLiteSquasher = {
  7027. squashIdx: (idx) => {
  7028. index4.parse(idx);
  7029. return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.where ?? ""}`;
  7030. },
  7031. unsquashIdx: (input) => {
  7032. const [name, columnsString, isUnique, where] = input.split(";");
  7033. const result = index4.parse({
  7034. name,
  7035. columns: columnsString.split(","),
  7036. isUnique: isUnique === "true",
  7037. where: where ?? void 0
  7038. });
  7039. return result;
  7040. },
  7041. squashUnique: (unq) => {
  7042. return `${unq.name};${unq.columns.join(",")}`;
  7043. },
  7044. unsquashUnique: (unq) => {
  7045. const [name, columns] = unq.split(";");
  7046. return { name, columns: columns.split(",") };
  7047. },
  7048. squashFK: (fk5) => {
  7049. return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
  7050. },
  7051. unsquashFK: (input) => {
  7052. const [
  7053. name,
  7054. tableFrom,
  7055. columnsFromStr,
  7056. tableTo,
  7057. columnsToStr,
  7058. onUpdate,
  7059. onDelete
  7060. ] = input.split(";");
  7061. const result = fk3.parse({
  7062. name,
  7063. tableFrom,
  7064. columnsFrom: columnsFromStr.split(","),
  7065. tableTo,
  7066. columnsTo: columnsToStr.split(","),
  7067. onUpdate,
  7068. onDelete
  7069. });
  7070. return result;
  7071. },
  7072. squashPushFK: (fk5) => {
  7073. return `${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
  7074. },
  7075. unsquashPushFK: (input) => {
  7076. const [
  7077. tableFrom,
  7078. columnsFromStr,
  7079. tableTo,
  7080. columnsToStr,
  7081. onUpdate,
  7082. onDelete
  7083. ] = input.split(";");
  7084. const result = fk3.parse({
  7085. name: "",
  7086. tableFrom,
  7087. columnsFrom: columnsFromStr.split(","),
  7088. tableTo,
  7089. columnsTo: columnsToStr.split(","),
  7090. onUpdate,
  7091. onDelete
  7092. });
  7093. return result;
  7094. },
  7095. squashPK: (pk) => {
  7096. return pk.columns.join(",");
  7097. },
  7098. unsquashPK: (pk) => {
  7099. return pk.split(",");
  7100. },
  7101. squashCheck: (check2) => {
  7102. return `${check2.name};${check2.value}`;
  7103. },
  7104. unsquashCheck: (input) => {
  7105. const [
  7106. name,
  7107. value
  7108. ] = input.split(";");
  7109. return { name, value };
  7110. }
  7111. };
  7112. squashSqliteScheme = (json, action) => {
  7113. const mappedTables = Object.fromEntries(
  7114. Object.entries(json.tables).map((it) => {
  7115. const squashedIndexes = mapValues(it[1].indexes, (index6) => {
  7116. return SQLiteSquasher.squashIdx(index6);
  7117. });
  7118. const squashedFKs = customMapEntries(
  7119. it[1].foreignKeys,
  7120. (key, value) => {
  7121. return action === "push" ? [
  7122. SQLiteSquasher.squashPushFK(value),
  7123. SQLiteSquasher.squashPushFK(value)
  7124. ] : [key, SQLiteSquasher.squashFK(value)];
  7125. }
  7126. );
  7127. const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
  7128. return SQLiteSquasher.squashPK(pk);
  7129. });
  7130. const squashedUniqueConstraints = mapValues(
  7131. it[1].uniqueConstraints,
  7132. (unq) => {
  7133. return SQLiteSquasher.squashUnique(unq);
  7134. }
  7135. );
  7136. const squashedCheckConstraints = mapValues(
  7137. it[1].checkConstraints,
  7138. (check2) => {
  7139. return SQLiteSquasher.squashCheck(check2);
  7140. }
  7141. );
  7142. return [
  7143. it[0],
  7144. {
  7145. name: it[1].name,
  7146. columns: it[1].columns,
  7147. indexes: squashedIndexes,
  7148. foreignKeys: squashedFKs,
  7149. compositePrimaryKeys: squashedPKs,
  7150. uniqueConstraints: squashedUniqueConstraints,
  7151. checkConstraints: squashedCheckConstraints
  7152. }
  7153. ];
  7154. })
  7155. );
  7156. return {
  7157. version: "6",
  7158. dialect: json.dialect,
  7159. tables: mappedTables,
  7160. views: json.views,
  7161. enums: json.enums
  7162. };
  7163. };
  7164. drySQLite = schema3.parse({
  7165. version: "6",
  7166. dialect: "sqlite",
  7167. id: originUUID,
  7168. prevId: "",
  7169. tables: {},
  7170. views: {},
  7171. enums: {},
  7172. _meta: {
  7173. tables: {},
  7174. columns: {}
  7175. }
  7176. });
  7177. sqliteSchemaV5 = schemaV52;
  7178. sqliteSchema = schema3;
  7179. SQLiteSchemaSquashed = schemaSquashed3;
  7180. backwardCompatibleSqliteSchema = unionType([sqliteSchemaV5, schema3]);
  7181. }
  7182. });
  7183. // src/schemaValidator.ts
  7184. var dialects, dialect4, commonSquashedSchema, commonSchema;
  7185. var init_schemaValidator = __esm({
  7186. "src/schemaValidator.ts"() {
  7187. "use strict";
  7188. init_esm();
  7189. init_mysqlSchema();
  7190. init_pgSchema();
  7191. init_singlestoreSchema();
  7192. init_sqliteSchema();
  7193. dialects = ["postgresql", "mysql", "sqlite", "turso", "singlestore", "gel"];
  7194. dialect4 = enumType(dialects);
  7195. commonSquashedSchema = unionType([
  7196. pgSchemaSquashed,
  7197. mysqlSchemaSquashed,
  7198. SQLiteSchemaSquashed,
  7199. singlestoreSchemaSquashed
  7200. ]);
  7201. commonSchema = unionType([pgSchema, mysqlSchema, sqliteSchema, singlestoreSchema]);
  7202. }
  7203. });
  7204. // ../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js
  7205. function camelCase(input, options) {
  7206. if (!(typeof input === "string" || Array.isArray(input))) {
  7207. throw new TypeError("Expected the input to be `string | string[]`");
  7208. }
  7209. options = {
  7210. pascalCase: false,
  7211. preserveConsecutiveUppercase: false,
  7212. ...options
  7213. };
  7214. if (Array.isArray(input)) {
  7215. input = input.map((x4) => x4.trim()).filter((x4) => x4.length).join("-");
  7216. } else {
  7217. input = input.trim();
  7218. }
  7219. if (input.length === 0) {
  7220. return "";
  7221. }
  7222. const toLowerCase = options.locale === false ? (string2) => string2.toLowerCase() : (string2) => string2.toLocaleLowerCase(options.locale);
  7223. const toUpperCase = options.locale === false ? (string2) => string2.toUpperCase() : (string2) => string2.toLocaleUpperCase(options.locale);
  7224. if (input.length === 1) {
  7225. if (SEPARATORS.test(input)) {
  7226. return "";
  7227. }
  7228. return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
  7229. }
  7230. const hasUpperCase = input !== toLowerCase(input);
  7231. if (hasUpperCase) {
  7232. input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);
  7233. }
  7234. input = input.replace(LEADING_SEPARATORS, "");
  7235. input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
  7236. if (options.pascalCase) {
  7237. input = toUpperCase(input.charAt(0)) + input.slice(1);
  7238. }
  7239. return postProcess(input, toUpperCase);
  7240. }
  7241. var UPPERCASE, LOWERCASE, LEADING_CAPITAL, IDENTIFIER, SEPARATORS, LEADING_SEPARATORS, SEPARATORS_AND_IDENTIFIER, NUMBERS_AND_IDENTIFIER, preserveCamelCase, preserveConsecutiveUppercase, postProcess;
  7242. var init_camelcase = __esm({
  7243. "../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js"() {
  7244. UPPERCASE = /[\p{Lu}]/u;
  7245. LOWERCASE = /[\p{Ll}]/u;
  7246. LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
  7247. IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
  7248. SEPARATORS = /[_.\- ]+/;
  7249. LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
  7250. SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
  7251. NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
  7252. preserveCamelCase = (string2, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
  7253. let isLastCharLower = false;
  7254. let isLastCharUpper = false;
  7255. let isLastLastCharUpper = false;
  7256. let isLastLastCharPreserved = false;
  7257. for (let index6 = 0; index6 < string2.length; index6++) {
  7258. const character = string2[index6];
  7259. isLastLastCharPreserved = index6 > 2 ? string2[index6 - 3] === "-" : true;
  7260. if (isLastCharLower && UPPERCASE.test(character)) {
  7261. string2 = string2.slice(0, index6) + "-" + string2.slice(index6);
  7262. isLastCharLower = false;
  7263. isLastLastCharUpper = isLastCharUpper;
  7264. isLastCharUpper = true;
  7265. index6++;
  7266. } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
  7267. string2 = string2.slice(0, index6 - 1) + "-" + string2.slice(index6 - 1);
  7268. isLastLastCharUpper = isLastCharUpper;
  7269. isLastCharUpper = false;
  7270. isLastCharLower = true;
  7271. } else {
  7272. isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
  7273. isLastLastCharUpper = isLastCharUpper;
  7274. isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
  7275. }
  7276. }
  7277. return string2;
  7278. };
  7279. preserveConsecutiveUppercase = (input, toLowerCase) => {
  7280. LEADING_CAPITAL.lastIndex = 0;
  7281. return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
  7282. };
  7283. postProcess = (input, toUpperCase) => {
  7284. SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
  7285. NUMBERS_AND_IDENTIFIER.lastIndex = 0;
  7286. return input.replace(SEPARATORS_AND_IDENTIFIER, (_3, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m4) => toUpperCase(m4));
  7287. };
  7288. }
  7289. });
  7290. // src/@types/utils.ts
  7291. var init_utils = __esm({
  7292. "src/@types/utils.ts"() {
  7293. "use strict";
  7294. init_camelcase();
  7295. String.prototype.trimChar = function(char) {
  7296. let start = 0;
  7297. let end = this.length;
  7298. while (start < end && this[start] === char) ++start;
  7299. while (end > start && this[end - 1] === char) --end;
  7300. return start > 0 || end < this.length ? this.substring(start, end) : this.toString();
  7301. };
  7302. String.prototype.squashSpaces = function() {
  7303. return this.replace(/ +/g, " ").trim();
  7304. };
  7305. String.prototype.camelCase = function() {
  7306. return camelCase(String(this));
  7307. };
  7308. String.prototype.capitalise = function() {
  7309. return this && this.length > 0 ? `${this[0].toUpperCase()}${this.slice(1)}` : String(this);
  7310. };
  7311. String.prototype.concatIf = function(it, condition) {
  7312. return condition ? `${this}${it}` : String(this);
  7313. };
  7314. String.prototype.snake_case = function() {
  7315. return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
  7316. };
  7317. Array.prototype.random = function() {
  7318. return this[~~(Math.random() * this.length)];
  7319. };
  7320. }
  7321. });
  7322. // src/cli/views.ts
  7323. var import_hanji, warning, err, info, grey, error, schema4, isRenamePromptItem, ResolveColumnSelect, tableKey, ResolveSelectNamed, ResolveSelect, ResolveSchemasSelect, Spinner, IntrospectProgress, MigrateProgress, ProgressView, DropMigrationView, trimmedRange;
  7324. var init_views = __esm({
  7325. "src/cli/views.ts"() {
  7326. "use strict";
  7327. init_source();
  7328. import_hanji = __toESM(require_hanji());
  7329. init_utils2();
  7330. warning = (msg) => {
  7331. (0, import_hanji.render)(`[${source_default.yellow("Warning")}] ${msg}`);
  7332. };
  7333. err = (msg) => {
  7334. (0, import_hanji.render)(`${source_default.bold.red("Error")} ${msg}`);
  7335. };
  7336. info = (msg, greyMsg = "") => {
  7337. return `${source_default.blue.bold("Info:")} ${msg} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
  7338. };
  7339. grey = (msg) => {
  7340. return source_default.grey(msg);
  7341. };
  7342. error = (error2, greyMsg = "") => {
  7343. return `${source_default.bgRed.bold(" Error ")} ${error2} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
  7344. };
  7345. schema4 = (schema6) => {
  7346. const tables = Object.values(schema6.tables);
  7347. let msg = source_default.bold(`${tables.length} tables
  7348. `);
  7349. msg += tables.map((t4) => {
  7350. const columnsCount = Object.values(t4.columns).length;
  7351. const indexesCount = Object.values(t4.indexes).length;
  7352. let foreignKeys = 0;
  7353. if (schema6.dialect !== "singlestore") {
  7354. foreignKeys = Object.values(t4.foreignKeys).length;
  7355. }
  7356. return `${source_default.bold.blue(t4.name)} ${source_default.gray(
  7357. `${columnsCount} columns ${indexesCount} indexes ${foreignKeys} fks`
  7358. )}`;
  7359. }).join("\n");
  7360. msg += "\n";
  7361. const enums = objectValues(
  7362. "enums" in schema6 ? "values" in schema6["enums"] ? schema6["enums"] : {} : {}
  7363. );
  7364. if (enums.length > 0) {
  7365. msg += "\n";
  7366. msg += source_default.bold(`${enums.length} enums
  7367. `);
  7368. msg += enums.map((it) => {
  7369. return `${source_default.bold.blue(it.name)} ${source_default.gray(
  7370. `[${Object.values(it.values).join(", ")}]`
  7371. )}`;
  7372. }).join("\n");
  7373. msg += "\n";
  7374. }
  7375. return msg;
  7376. };
  7377. isRenamePromptItem = (item) => {
  7378. return "from" in item && "to" in item;
  7379. };
  7380. ResolveColumnSelect = class extends import_hanji.Prompt {
  7381. constructor(tableName, base, data) {
  7382. super();
  7383. this.tableName = tableName;
  7384. this.base = base;
  7385. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  7386. this.data = new import_hanji.SelectState(data);
  7387. this.data.bind(this);
  7388. }
  7389. render(status) {
  7390. if (status === "submitted" || status === "aborted") {
  7391. return "\n";
  7392. }
  7393. let text = `
  7394. Is ${source_default.bold.blue(
  7395. this.base.name
  7396. )} column in ${source_default.bold.blue(
  7397. this.tableName
  7398. )} table created or renamed from another column?
  7399. `;
  7400. const isSelectedRenamed = isRenamePromptItem(
  7401. this.data.items[this.data.selectedIdx]
  7402. );
  7403. const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
  7404. const labelLength = this.data.items.filter((it) => isRenamePromptItem(it)).map((it) => {
  7405. return this.base.name.length + 3 + it["from"].name.length;
  7406. }).reduce((a3, b3) => {
  7407. if (a3 > b3) {
  7408. return a3;
  7409. }
  7410. return b3;
  7411. }, 0);
  7412. this.data.items.forEach((it, idx) => {
  7413. const isSelected = idx === this.data.selectedIdx;
  7414. const isRenamed = isRenamePromptItem(it);
  7415. const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
  7416. const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename column")}` : `${source_default.green("+")} ${title} ${source_default.gray("create column")}`;
  7417. text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
  7418. text += idx !== this.data.items.length - 1 ? "\n" : "";
  7419. });
  7420. return text;
  7421. }
  7422. result() {
  7423. return this.data.items[this.data.selectedIdx];
  7424. }
  7425. };
  7426. tableKey = (it) => {
  7427. return it.schema === "public" || !it.schema ? it.name : `${it.schema}.${it.name}`;
  7428. };
  7429. ResolveSelectNamed = class extends import_hanji.Prompt {
  7430. constructor(base, data, entityType) {
  7431. super();
  7432. this.base = base;
  7433. this.entityType = entityType;
  7434. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  7435. this.state = new import_hanji.SelectState(data);
  7436. this.state.bind(this);
  7437. }
  7438. render(status) {
  7439. if (status === "submitted" || status === "aborted") {
  7440. return "";
  7441. }
  7442. const key = this.base.name;
  7443. let text = `
  7444. Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
  7445. `;
  7446. const isSelectedRenamed = isRenamePromptItem(
  7447. this.state.items[this.state.selectedIdx]
  7448. );
  7449. const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
  7450. const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => {
  7451. const it = _3;
  7452. const keyFrom = it.from.name;
  7453. return key.length + 3 + keyFrom.length;
  7454. }).reduce((a3, b3) => {
  7455. if (a3 > b3) {
  7456. return a3;
  7457. }
  7458. return b3;
  7459. }, 0);
  7460. const entityType = this.entityType;
  7461. this.state.items.forEach((it, idx) => {
  7462. const isSelected = idx === this.state.selectedIdx;
  7463. const isRenamed = isRenamePromptItem(it);
  7464. const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
  7465. const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
  7466. text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
  7467. text += idx !== this.state.items.length - 1 ? "\n" : "";
  7468. });
  7469. return text;
  7470. }
  7471. result() {
  7472. return this.state.items[this.state.selectedIdx];
  7473. }
  7474. };
  7475. ResolveSelect = class extends import_hanji.Prompt {
  7476. constructor(base, data, entityType) {
  7477. super();
  7478. this.base = base;
  7479. this.entityType = entityType;
  7480. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  7481. this.state = new import_hanji.SelectState(data);
  7482. this.state.bind(this);
  7483. this.base = base;
  7484. }
  7485. render(status) {
  7486. if (status === "submitted" || status === "aborted") {
  7487. return "";
  7488. }
  7489. const key = tableKey(this.base);
  7490. let text = `
  7491. Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
  7492. `;
  7493. const isSelectedRenamed = isRenamePromptItem(
  7494. this.state.items[this.state.selectedIdx]
  7495. );
  7496. const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
  7497. const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_3) => {
  7498. const it = _3;
  7499. const keyFrom = tableKey(it.from);
  7500. return key.length + 3 + keyFrom.length;
  7501. }).reduce((a3, b3) => {
  7502. if (a3 > b3) {
  7503. return a3;
  7504. }
  7505. return b3;
  7506. }, 0);
  7507. const entityType = this.entityType;
  7508. this.state.items.forEach((it, idx) => {
  7509. const isSelected = idx === this.state.selectedIdx;
  7510. const isRenamed = isRenamePromptItem(it);
  7511. const title = isRenamed ? `${tableKey(it.from)} \u203A ${tableKey(it.to)}`.padEnd(labelLength, " ") : tableKey(it).padEnd(labelLength, " ");
  7512. const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
  7513. text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
  7514. text += idx !== this.state.items.length - 1 ? "\n" : "";
  7515. });
  7516. return text;
  7517. }
  7518. result() {
  7519. return this.state.items[this.state.selectedIdx];
  7520. }
  7521. };
  7522. ResolveSchemasSelect = class extends import_hanji.Prompt {
  7523. constructor(base, data) {
  7524. super();
  7525. this.base = base;
  7526. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  7527. this.state = new import_hanji.SelectState(data);
  7528. this.state.bind(this);
  7529. this.base = base;
  7530. }
  7531. render(status) {
  7532. if (status === "submitted" || status === "aborted") {
  7533. return "";
  7534. }
  7535. let text = `
  7536. Is ${source_default.bold.blue(
  7537. this.base.name
  7538. )} schema created or renamed from another schema?
  7539. `;
  7540. const isSelectedRenamed = isRenamePromptItem(
  7541. this.state.items[this.state.selectedIdx]
  7542. );
  7543. const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
  7544. const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((it) => {
  7545. return this.base.name.length + 3 + it["from"].name.length;
  7546. }).reduce((a3, b3) => {
  7547. if (a3 > b3) {
  7548. return a3;
  7549. }
  7550. return b3;
  7551. }, 0);
  7552. this.state.items.forEach((it, idx) => {
  7553. const isSelected = idx === this.state.selectedIdx;
  7554. const isRenamed = isRenamePromptItem(it);
  7555. const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
  7556. const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename schema")}` : `${source_default.green("+")} ${title} ${source_default.gray("create schema")}`;
  7557. text += isSelected ? `${selectedPrefix}${label}` : ` ${label}`;
  7558. text += idx !== this.state.items.length - 1 ? "\n" : "";
  7559. });
  7560. return text;
  7561. }
  7562. result() {
  7563. return this.state.items[this.state.selectedIdx];
  7564. }
  7565. };
  7566. Spinner = class {
  7567. constructor(frames) {
  7568. this.frames = frames;
  7569. this.offset = 0;
  7570. this.tick = () => {
  7571. this.iterator();
  7572. };
  7573. this.value = () => {
  7574. return this.frames[this.offset];
  7575. };
  7576. this.iterator = () => {
  7577. this.offset += 1;
  7578. this.offset %= frames.length - 1;
  7579. };
  7580. }
  7581. };
  7582. IntrospectProgress = class extends import_hanji.TaskView {
  7583. constructor(hasEnums = false) {
  7584. super();
  7585. this.hasEnums = hasEnums;
  7586. this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
  7587. this.state = {
  7588. tables: {
  7589. count: 0,
  7590. name: "tables",
  7591. status: "fetching"
  7592. },
  7593. columns: {
  7594. count: 0,
  7595. name: "columns",
  7596. status: "fetching"
  7597. },
  7598. enums: {
  7599. count: 0,
  7600. name: "enums",
  7601. status: "fetching"
  7602. },
  7603. indexes: {
  7604. count: 0,
  7605. name: "indexes",
  7606. status: "fetching"
  7607. },
  7608. fks: {
  7609. count: 0,
  7610. name: "foreign keys",
  7611. status: "fetching"
  7612. },
  7613. policies: {
  7614. count: 0,
  7615. name: "policies",
  7616. status: "fetching"
  7617. },
  7618. checks: {
  7619. count: 0,
  7620. name: "check constraints",
  7621. status: "fetching"
  7622. },
  7623. views: {
  7624. count: 0,
  7625. name: "views",
  7626. status: "fetching"
  7627. }
  7628. };
  7629. this.formatCount = (count) => {
  7630. const width = Math.max.apply(
  7631. null,
  7632. Object.values(this.state).map((it) => it.count.toFixed(0).length)
  7633. );
  7634. return count.toFixed(0).padEnd(width, " ");
  7635. };
  7636. this.statusText = (spinner, stage) => {
  7637. const { name, count } = stage;
  7638. const isDone = stage.status === "done";
  7639. const prefix2 = isDone ? `[${source_default.green("\u2713")}]` : `[${spinner}]`;
  7640. const formattedCount = this.formatCount(count);
  7641. const suffix = isDone ? `${formattedCount} ${name} fetched` : `${formattedCount} ${name} fetching`;
  7642. return `${prefix2} ${suffix}
  7643. `;
  7644. };
  7645. this.timeout = setInterval(() => {
  7646. this.spinner.tick();
  7647. this.requestLayout();
  7648. }, 128);
  7649. this.on("detach", () => clearInterval(this.timeout));
  7650. }
  7651. update(stage, count, status) {
  7652. this.state[stage].count = count;
  7653. this.state[stage].status = status;
  7654. this.requestLayout();
  7655. }
  7656. render() {
  7657. let info2 = "";
  7658. const spin = this.spinner.value();
  7659. info2 += this.statusText(spin, this.state.tables);
  7660. info2 += this.statusText(spin, this.state.columns);
  7661. info2 += this.hasEnums ? this.statusText(spin, this.state.enums) : "";
  7662. info2 += this.statusText(spin, this.state.indexes);
  7663. info2 += this.statusText(spin, this.state.fks);
  7664. info2 += this.statusText(spin, this.state.policies);
  7665. info2 += this.statusText(spin, this.state.checks);
  7666. info2 += this.statusText(spin, this.state.views);
  7667. return info2;
  7668. }
  7669. };
  7670. MigrateProgress = class extends import_hanji.TaskView {
  7671. constructor() {
  7672. super();
  7673. this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
  7674. this.timeout = setInterval(() => {
  7675. this.spinner.tick();
  7676. this.requestLayout();
  7677. }, 128);
  7678. this.on("detach", () => clearInterval(this.timeout));
  7679. }
  7680. render(status) {
  7681. if (status === "pending" || status === "rejected") {
  7682. const spin = this.spinner.value();
  7683. return `[${spin}] applying migrations...`;
  7684. }
  7685. return `[${source_default.green("\u2713")}] migrations applied successfully!`;
  7686. }
  7687. };
  7688. ProgressView = class extends import_hanji.TaskView {
  7689. constructor(progressText, successText) {
  7690. super();
  7691. this.progressText = progressText;
  7692. this.successText = successText;
  7693. this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
  7694. this.timeout = setInterval(() => {
  7695. this.spinner.tick();
  7696. this.requestLayout();
  7697. }, 128);
  7698. this.on("detach", () => clearInterval(this.timeout));
  7699. }
  7700. render(status) {
  7701. if (status === "pending" || status === "rejected") {
  7702. const spin = this.spinner.value();
  7703. return `[${spin}] ${this.progressText}
  7704. `;
  7705. }
  7706. return `[${source_default.green("\u2713")}] ${this.successText}
  7707. `;
  7708. }
  7709. };
  7710. DropMigrationView = class extends import_hanji.Prompt {
  7711. constructor(data) {
  7712. super();
  7713. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  7714. this.data = new import_hanji.SelectState(data);
  7715. this.data.selectedIdx = data.length - 1;
  7716. this.data.bind(this);
  7717. }
  7718. render(status) {
  7719. if (status === "submitted" || status === "aborted") {
  7720. return "\n";
  7721. }
  7722. let text = source_default.bold("Please select migration to drop:\n");
  7723. const selectedPrefix = source_default.yellow("\u276F ");
  7724. const data = trimmedRange(this.data.items, this.data.selectedIdx, 9);
  7725. const labelLength = data.trimmed.map((it) => it.tag.length).reduce((a3, b3) => {
  7726. if (a3 > b3) {
  7727. return a3;
  7728. }
  7729. return b3;
  7730. }, 0);
  7731. text += data.startTrimmed ? " ...\n" : "";
  7732. data.trimmed.forEach((it, idx) => {
  7733. const isSelected = idx === this.data.selectedIdx - data.offset;
  7734. let title = it.tag.padEnd(labelLength, " ");
  7735. title = isSelected ? source_default.yellow(title) : title;
  7736. text += isSelected ? `${selectedPrefix}${title}` : ` ${title}`;
  7737. text += idx !== this.data.items.length - 1 ? "\n" : "";
  7738. });
  7739. text += data.endTrimmed ? " ...\n" : "";
  7740. return text;
  7741. }
  7742. result() {
  7743. return this.data.items[this.data.selectedIdx];
  7744. }
  7745. };
  7746. trimmedRange = (arr, index6, limitLines) => {
  7747. const limit = limitLines - 2;
  7748. const sideLimit = Math.round(limit / 2);
  7749. const endTrimmed = arr.length - sideLimit > index6;
  7750. const startTrimmed = index6 > sideLimit - 1;
  7751. const paddingStart = Math.max(index6 + sideLimit - arr.length, 0);
  7752. const paddingEnd = Math.min(index6 - sideLimit + 1, 0);
  7753. const d1 = endTrimmed ? 1 : 0;
  7754. const d22 = startTrimmed ? 0 : 1;
  7755. const start = Math.max(0, index6 - sideLimit + d1 - paddingStart);
  7756. const end = Math.min(arr.length, index6 + sideLimit + d22 - paddingEnd);
  7757. return {
  7758. trimmed: arr.slice(start, end),
  7759. offset: start,
  7760. startTrimmed,
  7761. endTrimmed
  7762. };
  7763. };
  7764. }
  7765. });
  7766. // src/serializer/gelSchema.ts
  7767. var enumSchema2, enumSchemaV12, indexColumn2, index5, fk4, sequenceSchema2, roleSchema2, sequenceSquashed2, column5, checkConstraint4, columnSquashed2, compositePK5, uniqueConstraint5, policy2, policySquashed2, viewWithOption2, matViewWithOption2, mergedViewWithOption2, view4, table5, schemaHash5, kitInternals5, gelSchemaExternal, gelSchemaInternal, tableSquashed5, gelSchemaSquashed, gelSchema, backwardCompatibleGelSchema, dryGel;
  7768. var init_gelSchema = __esm({
  7769. "src/serializer/gelSchema.ts"() {
  7770. "use strict";
  7771. init_global();
  7772. init_esm();
  7773. enumSchema2 = objectType({
  7774. name: stringType(),
  7775. schema: stringType(),
  7776. values: stringType().array()
  7777. }).strict();
  7778. enumSchemaV12 = objectType({
  7779. name: stringType(),
  7780. values: recordType(stringType(), stringType())
  7781. }).strict();
  7782. indexColumn2 = objectType({
  7783. expression: stringType(),
  7784. isExpression: booleanType(),
  7785. asc: booleanType(),
  7786. nulls: stringType().optional(),
  7787. opclass: stringType().optional()
  7788. });
  7789. index5 = objectType({
  7790. name: stringType(),
  7791. columns: indexColumn2.array(),
  7792. isUnique: booleanType(),
  7793. with: recordType(stringType(), anyType()).optional(),
  7794. method: stringType().default("btree"),
  7795. where: stringType().optional(),
  7796. concurrently: booleanType().default(false)
  7797. }).strict();
  7798. fk4 = objectType({
  7799. name: stringType(),
  7800. tableFrom: stringType(),
  7801. columnsFrom: stringType().array(),
  7802. tableTo: stringType(),
  7803. schemaTo: stringType().optional(),
  7804. columnsTo: stringType().array(),
  7805. onUpdate: stringType().optional(),
  7806. onDelete: stringType().optional()
  7807. }).strict();
  7808. sequenceSchema2 = objectType({
  7809. name: stringType(),
  7810. increment: stringType().optional(),
  7811. minValue: stringType().optional(),
  7812. maxValue: stringType().optional(),
  7813. startWith: stringType().optional(),
  7814. cache: stringType().optional(),
  7815. cycle: booleanType().optional(),
  7816. schema: stringType()
  7817. }).strict();
  7818. roleSchema2 = objectType({
  7819. name: stringType(),
  7820. createDb: booleanType().optional(),
  7821. createRole: booleanType().optional(),
  7822. inherit: booleanType().optional()
  7823. }).strict();
  7824. sequenceSquashed2 = objectType({
  7825. name: stringType(),
  7826. schema: stringType(),
  7827. values: stringType()
  7828. }).strict();
  7829. column5 = objectType({
  7830. name: stringType(),
  7831. type: stringType(),
  7832. typeSchema: stringType().optional(),
  7833. primaryKey: booleanType(),
  7834. notNull: booleanType(),
  7835. default: anyType().optional(),
  7836. isUnique: anyType().optional(),
  7837. uniqueName: stringType().optional(),
  7838. nullsNotDistinct: booleanType().optional(),
  7839. generated: objectType({
  7840. type: literalType("stored"),
  7841. as: stringType()
  7842. }).optional(),
  7843. identity: sequenceSchema2.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
  7844. }).strict();
  7845. checkConstraint4 = objectType({
  7846. name: stringType(),
  7847. value: stringType()
  7848. }).strict();
  7849. columnSquashed2 = objectType({
  7850. name: stringType(),
  7851. type: stringType(),
  7852. typeSchema: stringType().optional(),
  7853. primaryKey: booleanType(),
  7854. notNull: booleanType(),
  7855. default: anyType().optional(),
  7856. isUnique: anyType().optional(),
  7857. uniqueName: stringType().optional(),
  7858. nullsNotDistinct: booleanType().optional(),
  7859. generated: objectType({
  7860. type: literalType("stored"),
  7861. as: stringType()
  7862. }).optional(),
  7863. identity: stringType().optional()
  7864. }).strict();
  7865. compositePK5 = objectType({
  7866. name: stringType(),
  7867. columns: stringType().array()
  7868. }).strict();
  7869. uniqueConstraint5 = objectType({
  7870. name: stringType(),
  7871. columns: stringType().array(),
  7872. nullsNotDistinct: booleanType()
  7873. }).strict();
  7874. policy2 = objectType({
  7875. name: stringType(),
  7876. as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
  7877. for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
  7878. to: stringType().array().optional(),
  7879. using: stringType().optional(),
  7880. withCheck: stringType().optional(),
  7881. on: stringType().optional(),
  7882. schema: stringType().optional()
  7883. }).strict();
  7884. policySquashed2 = objectType({
  7885. name: stringType(),
  7886. values: stringType()
  7887. }).strict();
  7888. viewWithOption2 = objectType({
  7889. checkOption: enumType(["local", "cascaded"]).optional(),
  7890. securityBarrier: booleanType().optional(),
  7891. securityInvoker: booleanType().optional()
  7892. }).strict();
  7893. matViewWithOption2 = objectType({
  7894. fillfactor: numberType().optional(),
  7895. toastTupleTarget: numberType().optional(),
  7896. parallelWorkers: numberType().optional(),
  7897. autovacuumEnabled: booleanType().optional(),
  7898. vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
  7899. vacuumTruncate: booleanType().optional(),
  7900. autovacuumVacuumThreshold: numberType().optional(),
  7901. autovacuumVacuumScaleFactor: numberType().optional(),
  7902. autovacuumVacuumCostDelay: numberType().optional(),
  7903. autovacuumVacuumCostLimit: numberType().optional(),
  7904. autovacuumFreezeMinAge: numberType().optional(),
  7905. autovacuumFreezeMaxAge: numberType().optional(),
  7906. autovacuumFreezeTableAge: numberType().optional(),
  7907. autovacuumMultixactFreezeMinAge: numberType().optional(),
  7908. autovacuumMultixactFreezeMaxAge: numberType().optional(),
  7909. autovacuumMultixactFreezeTableAge: numberType().optional(),
  7910. logAutovacuumMinDuration: numberType().optional(),
  7911. userCatalogTable: booleanType().optional()
  7912. }).strict();
  7913. mergedViewWithOption2 = viewWithOption2.merge(matViewWithOption2).strict();
  7914. view4 = objectType({
  7915. name: stringType(),
  7916. schema: stringType(),
  7917. columns: recordType(stringType(), column5),
  7918. definition: stringType().optional(),
  7919. materialized: booleanType(),
  7920. with: mergedViewWithOption2.optional(),
  7921. isExisting: booleanType(),
  7922. withNoData: booleanType().optional(),
  7923. using: stringType().optional(),
  7924. tablespace: stringType().optional()
  7925. }).strict();
  7926. table5 = objectType({
  7927. name: stringType(),
  7928. schema: stringType(),
  7929. columns: recordType(stringType(), column5),
  7930. indexes: recordType(stringType(), index5),
  7931. foreignKeys: recordType(stringType(), fk4),
  7932. compositePrimaryKeys: recordType(stringType(), compositePK5),
  7933. uniqueConstraints: recordType(stringType(), uniqueConstraint5).default({}),
  7934. policies: recordType(stringType(), policy2).default({}),
  7935. checkConstraints: recordType(stringType(), checkConstraint4).default({}),
  7936. isRLSEnabled: booleanType().default(false)
  7937. }).strict();
  7938. schemaHash5 = objectType({
  7939. id: stringType(),
  7940. prevId: stringType()
  7941. });
  7942. kitInternals5 = objectType({
  7943. tables: recordType(
  7944. stringType(),
  7945. objectType({
  7946. columns: recordType(
  7947. stringType(),
  7948. objectType({
  7949. isArray: booleanType().optional(),
  7950. dimensions: numberType().optional(),
  7951. rawType: stringType().optional(),
  7952. isDefaultAnExpression: booleanType().optional()
  7953. }).optional()
  7954. )
  7955. }).optional()
  7956. )
  7957. }).optional();
  7958. gelSchemaExternal = objectType({
  7959. version: literalType("1"),
  7960. dialect: literalType("gel"),
  7961. tables: arrayType(table5),
  7962. enums: arrayType(enumSchemaV12),
  7963. schemas: arrayType(objectType({ name: stringType() })),
  7964. _meta: objectType({
  7965. schemas: recordType(stringType(), stringType()),
  7966. tables: recordType(stringType(), stringType()),
  7967. columns: recordType(stringType(), stringType())
  7968. })
  7969. }).strict();
  7970. gelSchemaInternal = objectType({
  7971. version: literalType("1"),
  7972. dialect: literalType("gel"),
  7973. tables: recordType(stringType(), table5),
  7974. enums: recordType(stringType(), enumSchema2),
  7975. schemas: recordType(stringType(), stringType()),
  7976. views: recordType(stringType(), view4).default({}),
  7977. sequences: recordType(stringType(), sequenceSchema2).default({}),
  7978. roles: recordType(stringType(), roleSchema2).default({}),
  7979. policies: recordType(stringType(), policy2).default({}),
  7980. _meta: objectType({
  7981. schemas: recordType(stringType(), stringType()),
  7982. tables: recordType(stringType(), stringType()),
  7983. columns: recordType(stringType(), stringType())
  7984. }),
  7985. internal: kitInternals5
  7986. }).strict();
  7987. tableSquashed5 = objectType({
  7988. name: stringType(),
  7989. schema: stringType(),
  7990. columns: recordType(stringType(), columnSquashed2),
  7991. indexes: recordType(stringType(), stringType()),
  7992. foreignKeys: recordType(stringType(), stringType()),
  7993. compositePrimaryKeys: recordType(stringType(), stringType()),
  7994. uniqueConstraints: recordType(stringType(), stringType()),
  7995. policies: recordType(stringType(), stringType()),
  7996. checkConstraints: recordType(stringType(), stringType()),
  7997. isRLSEnabled: booleanType().default(false)
  7998. }).strict();
  7999. gelSchemaSquashed = objectType({
  8000. version: literalType("1"),
  8001. dialect: literalType("gel"),
  8002. tables: recordType(stringType(), tableSquashed5),
  8003. enums: recordType(stringType(), enumSchema2),
  8004. schemas: recordType(stringType(), stringType()),
  8005. views: recordType(stringType(), view4),
  8006. sequences: recordType(stringType(), sequenceSquashed2),
  8007. roles: recordType(stringType(), roleSchema2).default({}),
  8008. policies: recordType(stringType(), policySquashed2).default({})
  8009. }).strict();
  8010. gelSchema = gelSchemaInternal.merge(schemaHash5);
  8011. backwardCompatibleGelSchema = gelSchema;
  8012. dryGel = gelSchema.parse({
  8013. version: "1",
  8014. dialect: "gel",
  8015. id: originUUID,
  8016. prevId: "",
  8017. tables: {},
  8018. enums: {},
  8019. schemas: {},
  8020. policies: {},
  8021. roles: {},
  8022. sequences: {},
  8023. _meta: {
  8024. schemas: {},
  8025. tables: {},
  8026. columns: {}
  8027. }
  8028. });
  8029. }
  8030. });
  8031. // src/utils.ts
  8032. function isPgArrayType(sqlType) {
  8033. return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
  8034. }
  8035. function findAddedAndRemoved(columnNames1, columnNames2) {
  8036. const set1 = new Set(columnNames1);
  8037. const set2 = new Set(columnNames2);
  8038. const addedColumns = columnNames2.filter((it) => !set1.has(it));
  8039. const removedColumns = columnNames1.filter((it) => !set2.has(it));
  8040. return { addedColumns, removedColumns };
  8041. }
  8042. function escapeSingleQuotes(str) {
  8043. return str.replace(/'/g, "''");
  8044. }
  8045. function unescapeSingleQuotes(str, ignoreFirstAndLastChar) {
  8046. const regex = ignoreFirstAndLastChar ? /(?<!^)'(?!$)/g : /'/g;
  8047. return str.replace(/''/g, "'").replace(regex, "\\'");
  8048. }
  8049. var import_fs, import_path, import_url, copy, objectValues, assertV1OutFolder, dryJournal, prepareOutFolder, validatorForDialect, validateWithReport, prepareMigrationFolder, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey, normaliseSQLiteUrl, normalisePGliteUrl;
  8050. var init_utils2 = __esm({
  8051. "src/utils.ts"() {
  8052. "use strict";
  8053. init_source();
  8054. import_fs = require("fs");
  8055. import_path = require("path");
  8056. import_url = require("url");
  8057. init_views();
  8058. init_global();
  8059. init_gelSchema();
  8060. init_mysqlSchema();
  8061. init_pgSchema();
  8062. init_singlestoreSchema();
  8063. init_sqliteSchema();
  8064. copy = (it) => {
  8065. return JSON.parse(JSON.stringify(it));
  8066. };
  8067. objectValues = (obj) => {
  8068. return Object.values(obj);
  8069. };
  8070. assertV1OutFolder = (out) => {
  8071. if (!(0, import_fs.existsSync)(out)) return;
  8072. const oldMigrationFolders = (0, import_fs.readdirSync)(out).filter(
  8073. (it) => it.length === 14 && /^\d+$/.test(it)
  8074. );
  8075. if (oldMigrationFolders.length > 0) {
  8076. console.log(
  8077. `Your migrations folder format is outdated, please run ${source_default.green.bold(
  8078. `drizzle-kit up`
  8079. )}`
  8080. );
  8081. process.exit(1);
  8082. }
  8083. };
  8084. dryJournal = (dialect6) => {
  8085. return {
  8086. version: snapshotVersion,
  8087. dialect: dialect6,
  8088. entries: []
  8089. };
  8090. };
  8091. prepareOutFolder = (out, dialect6) => {
  8092. const meta = (0, import_path.join)(out, "meta");
  8093. const journalPath = (0, import_path.join)(meta, "_journal.json");
  8094. if (!(0, import_fs.existsSync)((0, import_path.join)(out, "meta"))) {
  8095. (0, import_fs.mkdirSync)(meta, { recursive: true });
  8096. (0, import_fs.writeFileSync)(journalPath, JSON.stringify(dryJournal(dialect6)));
  8097. }
  8098. const journal = JSON.parse((0, import_fs.readFileSync)(journalPath).toString());
  8099. const snapshots = (0, import_fs.readdirSync)(meta).filter((it) => !it.startsWith("_")).map((it) => (0, import_path.join)(meta, it));
  8100. snapshots.sort();
  8101. return { meta, snapshots, journal };
  8102. };
  8103. validatorForDialect = (dialect6) => {
  8104. switch (dialect6) {
  8105. case "postgresql":
  8106. return { validator: backwardCompatiblePgSchema, version: 7 };
  8107. case "sqlite":
  8108. return { validator: backwardCompatibleSqliteSchema, version: 6 };
  8109. case "turso":
  8110. return { validator: backwardCompatibleSqliteSchema, version: 6 };
  8111. case "mysql":
  8112. return { validator: backwardCompatibleMysqlSchema, version: 5 };
  8113. case "singlestore":
  8114. return { validator: backwardCompatibleSingleStoreSchema, version: 1 };
  8115. case "gel":
  8116. return { validator: backwardCompatibleGelSchema, version: 1 };
  8117. }
  8118. };
  8119. validateWithReport = (snapshots, dialect6) => {
  8120. const { validator: validator2, version: version3 } = validatorForDialect(dialect6);
  8121. const result = snapshots.reduce(
  8122. (accum, it) => {
  8123. const raw2 = JSON.parse((0, import_fs.readFileSync)(`./${it}`).toString());
  8124. accum.rawMap[it] = raw2;
  8125. if (raw2["version"] && Number(raw2["version"]) > version3) {
  8126. console.log(
  8127. info(
  8128. `${it} snapshot is of unsupported version, please update drizzle-kit`
  8129. )
  8130. );
  8131. process.exit(0);
  8132. }
  8133. const result2 = validator2.safeParse(raw2);
  8134. if (!result2.success) {
  8135. accum.malformed.push(it);
  8136. return accum;
  8137. }
  8138. const snapshot = result2.data;
  8139. if (snapshot.version !== String(version3)) {
  8140. accum.nonLatest.push(it);
  8141. return accum;
  8142. }
  8143. const idEntry = accum.idsMap[snapshot["prevId"]] ?? {
  8144. parent: it,
  8145. snapshots: []
  8146. };
  8147. idEntry.snapshots.push(it);
  8148. accum.idsMap[snapshot["prevId"]] = idEntry;
  8149. return accum;
  8150. },
  8151. {
  8152. malformed: [],
  8153. nonLatest: [],
  8154. idToNameMap: {},
  8155. idsMap: {},
  8156. rawMap: {}
  8157. }
  8158. );
  8159. return result;
  8160. };
  8161. prepareMigrationFolder = (outFolder = "drizzle", dialect6) => {
  8162. const { snapshots, journal } = prepareOutFolder(outFolder, dialect6);
  8163. const report = validateWithReport(snapshots, dialect6);
  8164. if (report.nonLatest.length > 0) {
  8165. console.log(
  8166. report.nonLatest.map((it) => {
  8167. return `${it}/snapshot.json is not of the latest version`;
  8168. }).concat(`Run ${source_default.green.bold(`drizzle-kit up`)}`).join("\n")
  8169. );
  8170. process.exit(0);
  8171. }
  8172. if (report.malformed.length) {
  8173. const message2 = report.malformed.map((it) => {
  8174. return `${it} data is malformed`;
  8175. }).join("\n");
  8176. console.log(message2);
  8177. }
  8178. const collisionEntries = Object.entries(report.idsMap).filter(
  8179. (it) => it[1].snapshots.length > 1
  8180. );
  8181. const message = collisionEntries.map((it) => {
  8182. const data = it[1];
  8183. return `[${data.snapshots.join(
  8184. ", "
  8185. )}] are pointing to a parent snapshot: ${data.parent}/snapshot.json which is a collision.`;
  8186. }).join("\n").trim();
  8187. if (message) {
  8188. console.log(source_default.red.bold("Error:"), message);
  8189. }
  8190. const abort = report.malformed.length || collisionEntries.length > 0;
  8191. if (abort) {
  8192. process.exit(0);
  8193. }
  8194. return { snapshots, journal };
  8195. };
  8196. prepareMigrationMeta = (schemas, tables, columns) => {
  8197. const _meta = {
  8198. schemas: {},
  8199. tables: {},
  8200. columns: {}
  8201. };
  8202. schemas.forEach((it) => {
  8203. const from = schemaRenameKey(it.from);
  8204. const to = schemaRenameKey(it.to);
  8205. _meta.schemas[from] = to;
  8206. });
  8207. tables.forEach((it) => {
  8208. const from = tableRenameKey(it.from);
  8209. const to = tableRenameKey(it.to);
  8210. _meta.tables[from] = to;
  8211. });
  8212. columns.forEach((it) => {
  8213. const from = columnRenameKey(it.from.table, it.from.schema, it.from.column);
  8214. const to = columnRenameKey(it.to.table, it.to.schema, it.to.column);
  8215. _meta.columns[from] = to;
  8216. });
  8217. return _meta;
  8218. };
  8219. schemaRenameKey = (it) => {
  8220. return it;
  8221. };
  8222. tableRenameKey = (it) => {
  8223. const out = it.schema ? `"${it.schema}"."${it.name}"` : `"${it.name}"`;
  8224. return out;
  8225. };
  8226. columnRenameKey = (table6, schema6, column11) => {
  8227. const out = schema6 ? `"${schema6}"."${table6}"."${column11}"` : `"${table6}"."${column11}"`;
  8228. return out;
  8229. };
  8230. normaliseSQLiteUrl = (it, type) => {
  8231. if (type === "libsql") {
  8232. if (it.startsWith("file:")) {
  8233. return it;
  8234. }
  8235. try {
  8236. const url = (0, import_url.parse)(it);
  8237. if (url.protocol === null) {
  8238. return `file:${it}`;
  8239. }
  8240. return it;
  8241. } catch (e4) {
  8242. return `file:${it}`;
  8243. }
  8244. }
  8245. if (type === "better-sqlite") {
  8246. if (it.startsWith("file:")) {
  8247. return it.substring(5);
  8248. }
  8249. return it;
  8250. }
  8251. assertUnreachable(type);
  8252. };
  8253. normalisePGliteUrl = (it) => {
  8254. if (it.startsWith("file:")) {
  8255. return it.substring(5);
  8256. }
  8257. return it;
  8258. };
  8259. }
  8260. });
  8261. // ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js
  8262. var require_old = __commonJS({
  8263. "../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js"(exports2) {
  8264. var pathModule = require("path");
  8265. var isWindows = process.platform === "win32";
  8266. var fs7 = require("fs");
  8267. var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
  8268. function rethrow() {
  8269. var callback;
  8270. if (DEBUG) {
  8271. var backtrace = new Error();
  8272. callback = debugCallback;
  8273. } else
  8274. callback = missingCallback;
  8275. return callback;
  8276. function debugCallback(err2) {
  8277. if (err2) {
  8278. backtrace.message = err2.message;
  8279. err2 = backtrace;
  8280. missingCallback(err2);
  8281. }
  8282. }
  8283. function missingCallback(err2) {
  8284. if (err2) {
  8285. if (process.throwDeprecation)
  8286. throw err2;
  8287. else if (!process.noDeprecation) {
  8288. var msg = "fs: missing callback " + (err2.stack || err2.message);
  8289. if (process.traceDeprecation)
  8290. console.trace(msg);
  8291. else
  8292. console.error(msg);
  8293. }
  8294. }
  8295. }
  8296. }
  8297. function maybeCallback(cb) {
  8298. return typeof cb === "function" ? cb : rethrow();
  8299. }
  8300. var normalize = pathModule.normalize;
  8301. if (isWindows) {
  8302. nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
  8303. } else {
  8304. nextPartRe = /(.*?)(?:[\/]+|$)/g;
  8305. }
  8306. var nextPartRe;
  8307. if (isWindows) {
  8308. splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
  8309. } else {
  8310. splitRootRe = /^[\/]*/;
  8311. }
  8312. var splitRootRe;
  8313. exports2.realpathSync = function realpathSync(p3, cache3) {
  8314. p3 = pathModule.resolve(p3);
  8315. if (cache3 && Object.prototype.hasOwnProperty.call(cache3, p3)) {
  8316. return cache3[p3];
  8317. }
  8318. var original = p3, seenLinks = {}, knownHard = {};
  8319. var pos;
  8320. var current;
  8321. var base;
  8322. var previous;
  8323. start();
  8324. function start() {
  8325. var m4 = splitRootRe.exec(p3);
  8326. pos = m4[0].length;
  8327. current = m4[0];
  8328. base = m4[0];
  8329. previous = "";
  8330. if (isWindows && !knownHard[base]) {
  8331. fs7.lstatSync(base);
  8332. knownHard[base] = true;
  8333. }
  8334. }
  8335. while (pos < p3.length) {
  8336. nextPartRe.lastIndex = pos;
  8337. var result = nextPartRe.exec(p3);
  8338. previous = current;
  8339. current += result[0];
  8340. base = previous + result[1];
  8341. pos = nextPartRe.lastIndex;
  8342. if (knownHard[base] || cache3 && cache3[base] === base) {
  8343. continue;
  8344. }
  8345. var resolvedLink;
  8346. if (cache3 && Object.prototype.hasOwnProperty.call(cache3, base)) {
  8347. resolvedLink = cache3[base];
  8348. } else {
  8349. var stat2 = fs7.lstatSync(base);
  8350. if (!stat2.isSymbolicLink()) {
  8351. knownHard[base] = true;
  8352. if (cache3) cache3[base] = base;
  8353. continue;
  8354. }
  8355. var linkTarget = null;
  8356. if (!isWindows) {
  8357. var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32);
  8358. if (seenLinks.hasOwnProperty(id)) {
  8359. linkTarget = seenLinks[id];
  8360. }
  8361. }
  8362. if (linkTarget === null) {
  8363. fs7.statSync(base);
  8364. linkTarget = fs7.readlinkSync(base);
  8365. }
  8366. resolvedLink = pathModule.resolve(previous, linkTarget);
  8367. if (cache3) cache3[base] = resolvedLink;
  8368. if (!isWindows) seenLinks[id] = linkTarget;
  8369. }
  8370. p3 = pathModule.resolve(resolvedLink, p3.slice(pos));
  8371. start();
  8372. }
  8373. if (cache3) cache3[original] = p3;
  8374. return p3;
  8375. };
  8376. exports2.realpath = function realpath(p3, cache3, cb) {
  8377. if (typeof cb !== "function") {
  8378. cb = maybeCallback(cache3);
  8379. cache3 = null;
  8380. }
  8381. p3 = pathModule.resolve(p3);
  8382. if (cache3 && Object.prototype.hasOwnProperty.call(cache3, p3)) {
  8383. return process.nextTick(cb.bind(null, null, cache3[p3]));
  8384. }
  8385. var original = p3, seenLinks = {}, knownHard = {};
  8386. var pos;
  8387. var current;
  8388. var base;
  8389. var previous;
  8390. start();
  8391. function start() {
  8392. var m4 = splitRootRe.exec(p3);
  8393. pos = m4[0].length;
  8394. current = m4[0];
  8395. base = m4[0];
  8396. previous = "";
  8397. if (isWindows && !knownHard[base]) {
  8398. fs7.lstat(base, function(err2) {
  8399. if (err2) return cb(err2);
  8400. knownHard[base] = true;
  8401. LOOP();
  8402. });
  8403. } else {
  8404. process.nextTick(LOOP);
  8405. }
  8406. }
  8407. function LOOP() {
  8408. if (pos >= p3.length) {
  8409. if (cache3) cache3[original] = p3;
  8410. return cb(null, p3);
  8411. }
  8412. nextPartRe.lastIndex = pos;
  8413. var result = nextPartRe.exec(p3);
  8414. previous = current;
  8415. current += result[0];
  8416. base = previous + result[1];
  8417. pos = nextPartRe.lastIndex;
  8418. if (knownHard[base] || cache3 && cache3[base] === base) {
  8419. return process.nextTick(LOOP);
  8420. }
  8421. if (cache3 && Object.prototype.hasOwnProperty.call(cache3, base)) {
  8422. return gotResolvedLink(cache3[base]);
  8423. }
  8424. return fs7.lstat(base, gotStat);
  8425. }
  8426. function gotStat(err2, stat2) {
  8427. if (err2) return cb(err2);
  8428. if (!stat2.isSymbolicLink()) {
  8429. knownHard[base] = true;
  8430. if (cache3) cache3[base] = base;
  8431. return process.nextTick(LOOP);
  8432. }
  8433. if (!isWindows) {
  8434. var id = stat2.dev.toString(32) + ":" + stat2.ino.toString(32);
  8435. if (seenLinks.hasOwnProperty(id)) {
  8436. return gotTarget(null, seenLinks[id], base);
  8437. }
  8438. }
  8439. fs7.stat(base, function(err3) {
  8440. if (err3) return cb(err3);
  8441. fs7.readlink(base, function(err4, target) {
  8442. if (!isWindows) seenLinks[id] = target;
  8443. gotTarget(err4, target);
  8444. });
  8445. });
  8446. }
  8447. function gotTarget(err2, target, base2) {
  8448. if (err2) return cb(err2);
  8449. var resolvedLink = pathModule.resolve(previous, target);
  8450. if (cache3) cache3[base2] = resolvedLink;
  8451. gotResolvedLink(resolvedLink);
  8452. }
  8453. function gotResolvedLink(resolvedLink) {
  8454. p3 = pathModule.resolve(resolvedLink, p3.slice(pos));
  8455. start();
  8456. }
  8457. };
  8458. }
  8459. });
  8460. // ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js
  8461. var require_fs = __commonJS({
  8462. "../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js"(exports2, module2) {
  8463. module2.exports = realpath;
  8464. realpath.realpath = realpath;
  8465. realpath.sync = realpathSync;
  8466. realpath.realpathSync = realpathSync;
  8467. realpath.monkeypatch = monkeypatch;
  8468. realpath.unmonkeypatch = unmonkeypatch;
  8469. var fs7 = require("fs");
  8470. var origRealpath = fs7.realpath;
  8471. var origRealpathSync = fs7.realpathSync;
  8472. var version3 = process.version;
  8473. var ok = /^v[0-5]\./.test(version3);
  8474. var old = require_old();
  8475. function newError(er) {
  8476. return er && er.syscall === "realpath" && (er.code === "ELOOP" || er.code === "ENOMEM" || er.code === "ENAMETOOLONG");
  8477. }
  8478. function realpath(p3, cache3, cb) {
  8479. if (ok) {
  8480. return origRealpath(p3, cache3, cb);
  8481. }
  8482. if (typeof cache3 === "function") {
  8483. cb = cache3;
  8484. cache3 = null;
  8485. }
  8486. origRealpath(p3, cache3, function(er, result) {
  8487. if (newError(er)) {
  8488. old.realpath(p3, cache3, cb);
  8489. } else {
  8490. cb(er, result);
  8491. }
  8492. });
  8493. }
  8494. function realpathSync(p3, cache3) {
  8495. if (ok) {
  8496. return origRealpathSync(p3, cache3);
  8497. }
  8498. try {
  8499. return origRealpathSync(p3, cache3);
  8500. } catch (er) {
  8501. if (newError(er)) {
  8502. return old.realpathSync(p3, cache3);
  8503. } else {
  8504. throw er;
  8505. }
  8506. }
  8507. }
  8508. function monkeypatch() {
  8509. fs7.realpath = realpath;
  8510. fs7.realpathSync = realpathSync;
  8511. }
  8512. function unmonkeypatch() {
  8513. fs7.realpath = origRealpath;
  8514. fs7.realpathSync = origRealpathSync;
  8515. }
  8516. }
  8517. });
  8518. // ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js
  8519. var require_path = __commonJS({
  8520. "../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js"(exports2, module2) {
  8521. var isWindows = typeof process === "object" && process && process.platform === "win32";
  8522. module2.exports = isWindows ? { sep: "\\" } : { sep: "/" };
  8523. }
  8524. });
  8525. // ../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
  8526. var require_balanced_match = __commonJS({
  8527. "../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports2, module2) {
  8528. "use strict";
  8529. module2.exports = balanced;
  8530. function balanced(a3, b3, str) {
  8531. if (a3 instanceof RegExp) a3 = maybeMatch(a3, str);
  8532. if (b3 instanceof RegExp) b3 = maybeMatch(b3, str);
  8533. var r4 = range(a3, b3, str);
  8534. return r4 && {
  8535. start: r4[0],
  8536. end: r4[1],
  8537. pre: str.slice(0, r4[0]),
  8538. body: str.slice(r4[0] + a3.length, r4[1]),
  8539. post: str.slice(r4[1] + b3.length)
  8540. };
  8541. }
  8542. function maybeMatch(reg, str) {
  8543. var m4 = str.match(reg);
  8544. return m4 ? m4[0] : null;
  8545. }
  8546. balanced.range = range;
  8547. function range(a3, b3, str) {
  8548. var begs, beg, left, right, result;
  8549. var ai = str.indexOf(a3);
  8550. var bi = str.indexOf(b3, ai + 1);
  8551. var i4 = ai;
  8552. if (ai >= 0 && bi > 0) {
  8553. if (a3 === b3) {
  8554. return [ai, bi];
  8555. }
  8556. begs = [];
  8557. left = str.length;
  8558. while (i4 >= 0 && !result) {
  8559. if (i4 == ai) {
  8560. begs.push(i4);
  8561. ai = str.indexOf(a3, i4 + 1);
  8562. } else if (begs.length == 1) {
  8563. result = [begs.pop(), bi];
  8564. } else {
  8565. beg = begs.pop();
  8566. if (beg < left) {
  8567. left = beg;
  8568. right = bi;
  8569. }
  8570. bi = str.indexOf(b3, i4 + 1);
  8571. }
  8572. i4 = ai < bi && ai >= 0 ? ai : bi;
  8573. }
  8574. if (begs.length) {
  8575. result = [left, right];
  8576. }
  8577. }
  8578. return result;
  8579. }
  8580. }
  8581. });
  8582. // ../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
  8583. var require_brace_expansion = __commonJS({
  8584. "../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports2, module2) {
  8585. var balanced = require_balanced_match();
  8586. module2.exports = expandTop;
  8587. var escSlash = "\0SLASH" + Math.random() + "\0";
  8588. var escOpen = "\0OPEN" + Math.random() + "\0";
  8589. var escClose = "\0CLOSE" + Math.random() + "\0";
  8590. var escComma = "\0COMMA" + Math.random() + "\0";
  8591. var escPeriod = "\0PERIOD" + Math.random() + "\0";
  8592. function numeric(str) {
  8593. return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
  8594. }
  8595. function escapeBraces(str) {
  8596. return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
  8597. }
  8598. function unescapeBraces(str) {
  8599. return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
  8600. }
  8601. function parseCommaParts(str) {
  8602. if (!str)
  8603. return [""];
  8604. var parts = [];
  8605. var m4 = balanced("{", "}", str);
  8606. if (!m4)
  8607. return str.split(",");
  8608. var pre = m4.pre;
  8609. var body = m4.body;
  8610. var post = m4.post;
  8611. var p3 = pre.split(",");
  8612. p3[p3.length - 1] += "{" + body + "}";
  8613. var postParts = parseCommaParts(post);
  8614. if (post.length) {
  8615. p3[p3.length - 1] += postParts.shift();
  8616. p3.push.apply(p3, postParts);
  8617. }
  8618. parts.push.apply(parts, p3);
  8619. return parts;
  8620. }
  8621. function expandTop(str) {
  8622. if (!str)
  8623. return [];
  8624. if (str.substr(0, 2) === "{}") {
  8625. str = "\\{\\}" + str.substr(2);
  8626. }
  8627. return expand2(escapeBraces(str), true).map(unescapeBraces);
  8628. }
  8629. function embrace(str) {
  8630. return "{" + str + "}";
  8631. }
  8632. function isPadded(el) {
  8633. return /^-?0\d/.test(el);
  8634. }
  8635. function lte(i4, y2) {
  8636. return i4 <= y2;
  8637. }
  8638. function gte(i4, y2) {
  8639. return i4 >= y2;
  8640. }
  8641. function expand2(str, isTop) {
  8642. var expansions = [];
  8643. var m4 = balanced("{", "}", str);
  8644. if (!m4) return [str];
  8645. var pre = m4.pre;
  8646. var post = m4.post.length ? expand2(m4.post, false) : [""];
  8647. if (/\$$/.test(m4.pre)) {
  8648. for (var k3 = 0; k3 < post.length; k3++) {
  8649. var expansion = pre + "{" + m4.body + "}" + post[k3];
  8650. expansions.push(expansion);
  8651. }
  8652. } else {
  8653. var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m4.body);
  8654. var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m4.body);
  8655. var isSequence = isNumericSequence || isAlphaSequence;
  8656. var isOptions = m4.body.indexOf(",") >= 0;
  8657. if (!isSequence && !isOptions) {
  8658. if (m4.post.match(/,.*\}/)) {
  8659. str = m4.pre + "{" + m4.body + escClose + m4.post;
  8660. return expand2(str);
  8661. }
  8662. return [str];
  8663. }
  8664. var n3;
  8665. if (isSequence) {
  8666. n3 = m4.body.split(/\.\./);
  8667. } else {
  8668. n3 = parseCommaParts(m4.body);
  8669. if (n3.length === 1) {
  8670. n3 = expand2(n3[0], false).map(embrace);
  8671. if (n3.length === 1) {
  8672. return post.map(function(p3) {
  8673. return m4.pre + n3[0] + p3;
  8674. });
  8675. }
  8676. }
  8677. }
  8678. var N;
  8679. if (isSequence) {
  8680. var x4 = numeric(n3[0]);
  8681. var y2 = numeric(n3[1]);
  8682. var width = Math.max(n3[0].length, n3[1].length);
  8683. var incr = n3.length == 3 ? Math.abs(numeric(n3[2])) : 1;
  8684. var test = lte;
  8685. var reverse = y2 < x4;
  8686. if (reverse) {
  8687. incr *= -1;
  8688. test = gte;
  8689. }
  8690. var pad = n3.some(isPadded);
  8691. N = [];
  8692. for (var i4 = x4; test(i4, y2); i4 += incr) {
  8693. var c3;
  8694. if (isAlphaSequence) {
  8695. c3 = String.fromCharCode(i4);
  8696. if (c3 === "\\")
  8697. c3 = "";
  8698. } else {
  8699. c3 = String(i4);
  8700. if (pad) {
  8701. var need = width - c3.length;
  8702. if (need > 0) {
  8703. var z2 = new Array(need + 1).join("0");
  8704. if (i4 < 0)
  8705. c3 = "-" + z2 + c3.slice(1);
  8706. else
  8707. c3 = z2 + c3;
  8708. }
  8709. }
  8710. }
  8711. N.push(c3);
  8712. }
  8713. } else {
  8714. N = [];
  8715. for (var j3 = 0; j3 < n3.length; j3++) {
  8716. N.push.apply(N, expand2(n3[j3], false));
  8717. }
  8718. }
  8719. for (var j3 = 0; j3 < N.length; j3++) {
  8720. for (var k3 = 0; k3 < post.length; k3++) {
  8721. var expansion = pre + N[j3] + post[k3];
  8722. if (!isTop || isSequence || expansion)
  8723. expansions.push(expansion);
  8724. }
  8725. }
  8726. }
  8727. return expansions;
  8728. }
  8729. }
  8730. });
  8731. // ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js
  8732. var require_minimatch = __commonJS({
  8733. "../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js"(exports2, module2) {
  8734. var minimatch2 = module2.exports = (p3, pattern, options = {}) => {
  8735. assertValidPattern2(pattern);
  8736. if (!options.nocomment && pattern.charAt(0) === "#") {
  8737. return false;
  8738. }
  8739. return new Minimatch2(pattern, options).match(p3);
  8740. };
  8741. module2.exports = minimatch2;
  8742. var path4 = require_path();
  8743. minimatch2.sep = path4.sep;
  8744. var GLOBSTAR2 = Symbol("globstar **");
  8745. minimatch2.GLOBSTAR = GLOBSTAR2;
  8746. var expand2 = require_brace_expansion();
  8747. var plTypes2 = {
  8748. "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
  8749. "?": { open: "(?:", close: ")?" },
  8750. "+": { open: "(?:", close: ")+" },
  8751. "*": { open: "(?:", close: ")*" },
  8752. "@": { open: "(?:", close: ")" }
  8753. };
  8754. var qmark2 = "[^/]";
  8755. var star2 = qmark2 + "*?";
  8756. var twoStarDot2 = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
  8757. var twoStarNoDot2 = "(?:(?!(?:\\/|^)\\.).)*?";
  8758. var charSet2 = (s4) => s4.split("").reduce((set, c3) => {
  8759. set[c3] = true;
  8760. return set;
  8761. }, {});
  8762. var reSpecials2 = charSet2("().*{}+?[]^$\\!");
  8763. var addPatternStartSet2 = charSet2("[.(");
  8764. var slashSplit = /\/+/;
  8765. minimatch2.filter = (pattern, options = {}) => (p3, i4, list) => minimatch2(p3, pattern, options);
  8766. var ext2 = (a3, b3 = {}) => {
  8767. const t4 = {};
  8768. Object.keys(a3).forEach((k3) => t4[k3] = a3[k3]);
  8769. Object.keys(b3).forEach((k3) => t4[k3] = b3[k3]);
  8770. return t4;
  8771. };
  8772. minimatch2.defaults = (def) => {
  8773. if (!def || typeof def !== "object" || !Object.keys(def).length) {
  8774. return minimatch2;
  8775. }
  8776. const orig = minimatch2;
  8777. const m4 = (p3, pattern, options) => orig(p3, pattern, ext2(def, options));
  8778. m4.Minimatch = class Minimatch extends orig.Minimatch {
  8779. constructor(pattern, options) {
  8780. super(pattern, ext2(def, options));
  8781. }
  8782. };
  8783. m4.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch;
  8784. m4.filter = (pattern, options) => orig.filter(pattern, ext2(def, options));
  8785. m4.defaults = (options) => orig.defaults(ext2(def, options));
  8786. m4.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options));
  8787. m4.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options));
  8788. m4.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options));
  8789. return m4;
  8790. };
  8791. minimatch2.braceExpand = (pattern, options) => braceExpand2(pattern, options);
  8792. var braceExpand2 = (pattern, options = {}) => {
  8793. assertValidPattern2(pattern);
  8794. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  8795. return [pattern];
  8796. }
  8797. return expand2(pattern);
  8798. };
  8799. var MAX_PATTERN_LENGTH2 = 1024 * 64;
  8800. var assertValidPattern2 = (pattern) => {
  8801. if (typeof pattern !== "string") {
  8802. throw new TypeError("invalid pattern");
  8803. }
  8804. if (pattern.length > MAX_PATTERN_LENGTH2) {
  8805. throw new TypeError("pattern is too long");
  8806. }
  8807. };
  8808. var SUBPARSE = Symbol("subparse");
  8809. minimatch2.makeRe = (pattern, options) => new Minimatch2(pattern, options || {}).makeRe();
  8810. minimatch2.match = (list, pattern, options = {}) => {
  8811. const mm = new Minimatch2(pattern, options);
  8812. list = list.filter((f5) => mm.match(f5));
  8813. if (mm.options.nonull && !list.length) {
  8814. list.push(pattern);
  8815. }
  8816. return list;
  8817. };
  8818. var globUnescape2 = (s4) => s4.replace(/\\(.)/g, "$1");
  8819. var charUnescape = (s4) => s4.replace(/\\([^-\]])/g, "$1");
  8820. var regExpEscape2 = (s4) => s4.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  8821. var braExpEscape = (s4) => s4.replace(/[[\]\\]/g, "\\$&");
  8822. var Minimatch2 = class {
  8823. constructor(pattern, options) {
  8824. assertValidPattern2(pattern);
  8825. if (!options) options = {};
  8826. this.options = options;
  8827. this.set = [];
  8828. this.pattern = pattern;
  8829. this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  8830. if (this.windowsPathsNoEscape) {
  8831. this.pattern = this.pattern.replace(/\\/g, "/");
  8832. }
  8833. this.regexp = null;
  8834. this.negate = false;
  8835. this.comment = false;
  8836. this.empty = false;
  8837. this.partial = !!options.partial;
  8838. this.make();
  8839. }
  8840. debug() {
  8841. }
  8842. make() {
  8843. const pattern = this.pattern;
  8844. const options = this.options;
  8845. if (!options.nocomment && pattern.charAt(0) === "#") {
  8846. this.comment = true;
  8847. return;
  8848. }
  8849. if (!pattern) {
  8850. this.empty = true;
  8851. return;
  8852. }
  8853. this.parseNegate();
  8854. let set = this.globSet = this.braceExpand();
  8855. if (options.debug) this.debug = (...args) => console.error(...args);
  8856. this.debug(this.pattern, set);
  8857. set = this.globParts = set.map((s4) => s4.split(slashSplit));
  8858. this.debug(this.pattern, set);
  8859. set = set.map((s4, si, set2) => s4.map(this.parse, this));
  8860. this.debug(this.pattern, set);
  8861. set = set.filter((s4) => s4.indexOf(false) === -1);
  8862. this.debug(this.pattern, set);
  8863. this.set = set;
  8864. }
  8865. parseNegate() {
  8866. if (this.options.nonegate) return;
  8867. const pattern = this.pattern;
  8868. let negate = false;
  8869. let negateOffset = 0;
  8870. for (let i4 = 0; i4 < pattern.length && pattern.charAt(i4) === "!"; i4++) {
  8871. negate = !negate;
  8872. negateOffset++;
  8873. }
  8874. if (negateOffset) this.pattern = pattern.slice(negateOffset);
  8875. this.negate = negate;
  8876. }
  8877. // set partial to true to test if, for example,
  8878. // "/a/b" matches the start of "/*/b/*/d"
  8879. // Partial means, if you run out of file before you run
  8880. // out of pattern, then that's fine, as long as all
  8881. // the parts match.
  8882. matchOne(file, pattern, partial) {
  8883. var options = this.options;
  8884. this.debug(
  8885. "matchOne",
  8886. { "this": this, file, pattern }
  8887. );
  8888. this.debug("matchOne", file.length, pattern.length);
  8889. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  8890. this.debug("matchOne loop");
  8891. var p3 = pattern[pi];
  8892. var f5 = file[fi];
  8893. this.debug(pattern, p3, f5);
  8894. if (p3 === false) return false;
  8895. if (p3 === GLOBSTAR2) {
  8896. this.debug("GLOBSTAR", [pattern, p3, f5]);
  8897. var fr = fi;
  8898. var pr = pi + 1;
  8899. if (pr === pl) {
  8900. this.debug("** at the end");
  8901. for (; fi < fl; fi++) {
  8902. if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
  8903. }
  8904. return true;
  8905. }
  8906. while (fr < fl) {
  8907. var swallowee = file[fr];
  8908. this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
  8909. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  8910. this.debug("globstar found match!", fr, fl, swallowee);
  8911. return true;
  8912. } else {
  8913. if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
  8914. this.debug("dot detected!", file, fr, pattern, pr);
  8915. break;
  8916. }
  8917. this.debug("globstar swallow a segment, and continue");
  8918. fr++;
  8919. }
  8920. }
  8921. if (partial) {
  8922. this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
  8923. if (fr === fl) return true;
  8924. }
  8925. return false;
  8926. }
  8927. var hit;
  8928. if (typeof p3 === "string") {
  8929. hit = f5 === p3;
  8930. this.debug("string match", p3, f5, hit);
  8931. } else {
  8932. hit = f5.match(p3);
  8933. this.debug("pattern match", p3, f5, hit);
  8934. }
  8935. if (!hit) return false;
  8936. }
  8937. if (fi === fl && pi === pl) {
  8938. return true;
  8939. } else if (fi === fl) {
  8940. return partial;
  8941. } else if (pi === pl) {
  8942. return fi === fl - 1 && file[fi] === "";
  8943. }
  8944. throw new Error("wtf?");
  8945. }
  8946. braceExpand() {
  8947. return braceExpand2(this.pattern, this.options);
  8948. }
  8949. parse(pattern, isSub) {
  8950. assertValidPattern2(pattern);
  8951. const options = this.options;
  8952. if (pattern === "**") {
  8953. if (!options.noglobstar)
  8954. return GLOBSTAR2;
  8955. else
  8956. pattern = "*";
  8957. }
  8958. if (pattern === "") return "";
  8959. let re = "";
  8960. let hasMagic = false;
  8961. let escaping = false;
  8962. const patternListStack = [];
  8963. const negativeLists = [];
  8964. let stateChar;
  8965. let inClass = false;
  8966. let reClassStart = -1;
  8967. let classStart = -1;
  8968. let cs;
  8969. let pl;
  8970. let sp;
  8971. let dotTravAllowed = pattern.charAt(0) === ".";
  8972. let dotFileAllowed = options.dot || dotTravAllowed;
  8973. const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
  8974. const subPatternStart = (p3) => p3.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
  8975. const clearStateChar = () => {
  8976. if (stateChar) {
  8977. switch (stateChar) {
  8978. case "*":
  8979. re += star2;
  8980. hasMagic = true;
  8981. break;
  8982. case "?":
  8983. re += qmark2;
  8984. hasMagic = true;
  8985. break;
  8986. default:
  8987. re += "\\" + stateChar;
  8988. break;
  8989. }
  8990. this.debug("clearStateChar %j %j", stateChar, re);
  8991. stateChar = false;
  8992. }
  8993. };
  8994. for (let i4 = 0, c3; i4 < pattern.length && (c3 = pattern.charAt(i4)); i4++) {
  8995. this.debug("%s %s %s %j", pattern, i4, re, c3);
  8996. if (escaping) {
  8997. if (c3 === "/") {
  8998. return false;
  8999. }
  9000. if (reSpecials2[c3]) {
  9001. re += "\\";
  9002. }
  9003. re += c3;
  9004. escaping = false;
  9005. continue;
  9006. }
  9007. switch (c3) {
  9008. /* istanbul ignore next */
  9009. case "/": {
  9010. return false;
  9011. }
  9012. case "\\":
  9013. if (inClass && pattern.charAt(i4 + 1) === "-") {
  9014. re += c3;
  9015. continue;
  9016. }
  9017. clearStateChar();
  9018. escaping = true;
  9019. continue;
  9020. // the various stateChar values
  9021. // for the "extglob" stuff.
  9022. case "?":
  9023. case "*":
  9024. case "+":
  9025. case "@":
  9026. case "!":
  9027. this.debug("%s %s %s %j <-- stateChar", pattern, i4, re, c3);
  9028. if (inClass) {
  9029. this.debug(" in class");
  9030. if (c3 === "!" && i4 === classStart + 1) c3 = "^";
  9031. re += c3;
  9032. continue;
  9033. }
  9034. this.debug("call clearStateChar %j", stateChar);
  9035. clearStateChar();
  9036. stateChar = c3;
  9037. if (options.noext) clearStateChar();
  9038. continue;
  9039. case "(": {
  9040. if (inClass) {
  9041. re += "(";
  9042. continue;
  9043. }
  9044. if (!stateChar) {
  9045. re += "\\(";
  9046. continue;
  9047. }
  9048. const plEntry = {
  9049. type: stateChar,
  9050. start: i4 - 1,
  9051. reStart: re.length,
  9052. open: plTypes2[stateChar].open,
  9053. close: plTypes2[stateChar].close
  9054. };
  9055. this.debug(this.pattern, " ", plEntry);
  9056. patternListStack.push(plEntry);
  9057. re += plEntry.open;
  9058. if (plEntry.start === 0 && plEntry.type !== "!") {
  9059. dotTravAllowed = true;
  9060. re += subPatternStart(pattern.slice(i4 + 1));
  9061. }
  9062. this.debug("plType %j %j", stateChar, re);
  9063. stateChar = false;
  9064. continue;
  9065. }
  9066. case ")": {
  9067. const plEntry = patternListStack[patternListStack.length - 1];
  9068. if (inClass || !plEntry) {
  9069. re += "\\)";
  9070. continue;
  9071. }
  9072. patternListStack.pop();
  9073. clearStateChar();
  9074. hasMagic = true;
  9075. pl = plEntry;
  9076. re += pl.close;
  9077. if (pl.type === "!") {
  9078. negativeLists.push(Object.assign(pl, { reEnd: re.length }));
  9079. }
  9080. continue;
  9081. }
  9082. case "|": {
  9083. const plEntry = patternListStack[patternListStack.length - 1];
  9084. if (inClass || !plEntry) {
  9085. re += "\\|";
  9086. continue;
  9087. }
  9088. clearStateChar();
  9089. re += "|";
  9090. if (plEntry.start === 0 && plEntry.type !== "!") {
  9091. dotTravAllowed = true;
  9092. re += subPatternStart(pattern.slice(i4 + 1));
  9093. }
  9094. continue;
  9095. }
  9096. // these are mostly the same in regexp and glob
  9097. case "[":
  9098. clearStateChar();
  9099. if (inClass) {
  9100. re += "\\" + c3;
  9101. continue;
  9102. }
  9103. inClass = true;
  9104. classStart = i4;
  9105. reClassStart = re.length;
  9106. re += c3;
  9107. continue;
  9108. case "]":
  9109. if (i4 === classStart + 1 || !inClass) {
  9110. re += "\\" + c3;
  9111. continue;
  9112. }
  9113. cs = pattern.substring(classStart + 1, i4);
  9114. try {
  9115. RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
  9116. re += c3;
  9117. } catch (er) {
  9118. re = re.substring(0, reClassStart) + "(?:$.)";
  9119. }
  9120. hasMagic = true;
  9121. inClass = false;
  9122. continue;
  9123. default:
  9124. clearStateChar();
  9125. if (reSpecials2[c3] && !(c3 === "^" && inClass)) {
  9126. re += "\\";
  9127. }
  9128. re += c3;
  9129. break;
  9130. }
  9131. }
  9132. if (inClass) {
  9133. cs = pattern.slice(classStart + 1);
  9134. sp = this.parse(cs, SUBPARSE);
  9135. re = re.substring(0, reClassStart) + "\\[" + sp[0];
  9136. hasMagic = hasMagic || sp[1];
  9137. }
  9138. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  9139. let tail;
  9140. tail = re.slice(pl.reStart + pl.open.length);
  9141. this.debug("setting tail", re, pl);
  9142. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => {
  9143. if (!$2) {
  9144. $2 = "\\";
  9145. }
  9146. return $1 + $1 + $2 + "|";
  9147. });
  9148. this.debug("tail=%j\n %s", tail, tail, pl, re);
  9149. const t4 = pl.type === "*" ? star2 : pl.type === "?" ? qmark2 : "\\" + pl.type;
  9150. hasMagic = true;
  9151. re = re.slice(0, pl.reStart) + t4 + "\\(" + tail;
  9152. }
  9153. clearStateChar();
  9154. if (escaping) {
  9155. re += "\\\\";
  9156. }
  9157. const addPatternStart = addPatternStartSet2[re.charAt(0)];
  9158. for (let n3 = negativeLists.length - 1; n3 > -1; n3--) {
  9159. const nl = negativeLists[n3];
  9160. const nlBefore = re.slice(0, nl.reStart);
  9161. const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  9162. let nlAfter = re.slice(nl.reEnd);
  9163. const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
  9164. const closeParensBefore = nlBefore.split(")").length;
  9165. const openParensBefore = nlBefore.split("(").length - closeParensBefore;
  9166. let cleanAfter = nlAfter;
  9167. for (let i4 = 0; i4 < openParensBefore; i4++) {
  9168. cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
  9169. }
  9170. nlAfter = cleanAfter;
  9171. const dollar = nlAfter === "" && isSub !== SUBPARSE ? "(?:$|\\/)" : "";
  9172. re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  9173. }
  9174. if (re !== "" && hasMagic) {
  9175. re = "(?=.)" + re;
  9176. }
  9177. if (addPatternStart) {
  9178. re = patternStart() + re;
  9179. }
  9180. if (isSub === SUBPARSE) {
  9181. return [re, hasMagic];
  9182. }
  9183. if (options.nocase && !hasMagic) {
  9184. hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
  9185. }
  9186. if (!hasMagic) {
  9187. return globUnescape2(pattern);
  9188. }
  9189. const flags = options.nocase ? "i" : "";
  9190. try {
  9191. return Object.assign(new RegExp("^" + re + "$", flags), {
  9192. _glob: pattern,
  9193. _src: re
  9194. });
  9195. } catch (er) {
  9196. return new RegExp("$.");
  9197. }
  9198. }
  9199. makeRe() {
  9200. if (this.regexp || this.regexp === false) return this.regexp;
  9201. const set = this.set;
  9202. if (!set.length) {
  9203. this.regexp = false;
  9204. return this.regexp;
  9205. }
  9206. const options = this.options;
  9207. const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot2 : twoStarNoDot2;
  9208. const flags = options.nocase ? "i" : "";
  9209. let re = set.map((pattern) => {
  9210. pattern = pattern.map(
  9211. (p3) => typeof p3 === "string" ? regExpEscape2(p3) : p3 === GLOBSTAR2 ? GLOBSTAR2 : p3._src
  9212. ).reduce((set2, p3) => {
  9213. if (!(set2[set2.length - 1] === GLOBSTAR2 && p3 === GLOBSTAR2)) {
  9214. set2.push(p3);
  9215. }
  9216. return set2;
  9217. }, []);
  9218. pattern.forEach((p3, i4) => {
  9219. if (p3 !== GLOBSTAR2 || pattern[i4 - 1] === GLOBSTAR2) {
  9220. return;
  9221. }
  9222. if (i4 === 0) {
  9223. if (pattern.length > 1) {
  9224. pattern[i4 + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i4 + 1];
  9225. } else {
  9226. pattern[i4] = twoStar;
  9227. }
  9228. } else if (i4 === pattern.length - 1) {
  9229. pattern[i4 - 1] += "(?:\\/|" + twoStar + ")?";
  9230. } else {
  9231. pattern[i4 - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i4 + 1];
  9232. pattern[i4 + 1] = GLOBSTAR2;
  9233. }
  9234. });
  9235. return pattern.filter((p3) => p3 !== GLOBSTAR2).join("/");
  9236. }).join("|");
  9237. re = "^(?:" + re + ")$";
  9238. if (this.negate) re = "^(?!" + re + ").*$";
  9239. try {
  9240. this.regexp = new RegExp(re, flags);
  9241. } catch (ex) {
  9242. this.regexp = false;
  9243. }
  9244. return this.regexp;
  9245. }
  9246. match(f5, partial = this.partial) {
  9247. this.debug("match", f5, this.pattern);
  9248. if (this.comment) return false;
  9249. if (this.empty) return f5 === "";
  9250. if (f5 === "/" && partial) return true;
  9251. const options = this.options;
  9252. if (path4.sep !== "/") {
  9253. f5 = f5.split(path4.sep).join("/");
  9254. }
  9255. f5 = f5.split(slashSplit);
  9256. this.debug(this.pattern, "split", f5);
  9257. const set = this.set;
  9258. this.debug(this.pattern, "set", set);
  9259. let filename;
  9260. for (let i4 = f5.length - 1; i4 >= 0; i4--) {
  9261. filename = f5[i4];
  9262. if (filename) break;
  9263. }
  9264. for (let i4 = 0; i4 < set.length; i4++) {
  9265. const pattern = set[i4];
  9266. let file = f5;
  9267. if (options.matchBase && pattern.length === 1) {
  9268. file = [filename];
  9269. }
  9270. const hit = this.matchOne(file, pattern, partial);
  9271. if (hit) {
  9272. if (options.flipNegate) return true;
  9273. return !this.negate;
  9274. }
  9275. }
  9276. if (options.flipNegate) return false;
  9277. return this.negate;
  9278. }
  9279. static defaults(def) {
  9280. return minimatch2.defaults(def).Minimatch;
  9281. }
  9282. };
  9283. minimatch2.Minimatch = Minimatch2;
  9284. }
  9285. });
  9286. // ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js
  9287. var require_inherits_browser = __commonJS({
  9288. "../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js"(exports2, module2) {
  9289. if (typeof Object.create === "function") {
  9290. module2.exports = function inherits(ctor, superCtor) {
  9291. if (superCtor) {
  9292. ctor.super_ = superCtor;
  9293. ctor.prototype = Object.create(superCtor.prototype, {
  9294. constructor: {
  9295. value: ctor,
  9296. enumerable: false,
  9297. writable: true,
  9298. configurable: true
  9299. }
  9300. });
  9301. }
  9302. };
  9303. } else {
  9304. module2.exports = function inherits(ctor, superCtor) {
  9305. if (superCtor) {
  9306. ctor.super_ = superCtor;
  9307. var TempCtor = function() {
  9308. };
  9309. TempCtor.prototype = superCtor.prototype;
  9310. ctor.prototype = new TempCtor();
  9311. ctor.prototype.constructor = ctor;
  9312. }
  9313. };
  9314. }
  9315. }
  9316. });
  9317. // ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js
  9318. var require_inherits = __commonJS({
  9319. "../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js"(exports2, module2) {
  9320. try {
  9321. util2 = require("util");
  9322. if (typeof util2.inherits !== "function") throw "";
  9323. module2.exports = util2.inherits;
  9324. } catch (e4) {
  9325. module2.exports = require_inherits_browser();
  9326. }
  9327. var util2;
  9328. }
  9329. });
  9330. // ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js
  9331. var require_common = __commonJS({
  9332. "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js"(exports2) {
  9333. exports2.setopts = setopts;
  9334. exports2.ownProp = ownProp;
  9335. exports2.makeAbs = makeAbs;
  9336. exports2.finish = finish;
  9337. exports2.mark = mark;
  9338. exports2.isIgnored = isIgnored;
  9339. exports2.childrenIgnored = childrenIgnored;
  9340. function ownProp(obj, field) {
  9341. return Object.prototype.hasOwnProperty.call(obj, field);
  9342. }
  9343. var fs7 = require("fs");
  9344. var path4 = require("path");
  9345. var minimatch2 = require_minimatch();
  9346. var isAbsolute = require("path").isAbsolute;
  9347. var Minimatch2 = minimatch2.Minimatch;
  9348. function alphasort(a3, b3) {
  9349. return a3.localeCompare(b3, "en");
  9350. }
  9351. function setupIgnores(self2, options) {
  9352. self2.ignore = options.ignore || [];
  9353. if (!Array.isArray(self2.ignore))
  9354. self2.ignore = [self2.ignore];
  9355. if (self2.ignore.length) {
  9356. self2.ignore = self2.ignore.map(ignoreMap);
  9357. }
  9358. }
  9359. function ignoreMap(pattern) {
  9360. var gmatcher = null;
  9361. if (pattern.slice(-3) === "/**") {
  9362. var gpattern = pattern.replace(/(\/\*\*)+$/, "");
  9363. gmatcher = new Minimatch2(gpattern, { dot: true });
  9364. }
  9365. return {
  9366. matcher: new Minimatch2(pattern, { dot: true }),
  9367. gmatcher
  9368. };
  9369. }
  9370. function setopts(self2, pattern, options) {
  9371. if (!options)
  9372. options = {};
  9373. if (options.matchBase && -1 === pattern.indexOf("/")) {
  9374. if (options.noglobstar) {
  9375. throw new Error("base matching requires globstar");
  9376. }
  9377. pattern = "**/" + pattern;
  9378. }
  9379. self2.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  9380. if (self2.windowsPathsNoEscape) {
  9381. pattern = pattern.replace(/\\/g, "/");
  9382. }
  9383. self2.silent = !!options.silent;
  9384. self2.pattern = pattern;
  9385. self2.strict = options.strict !== false;
  9386. self2.realpath = !!options.realpath;
  9387. self2.realpathCache = options.realpathCache || /* @__PURE__ */ Object.create(null);
  9388. self2.follow = !!options.follow;
  9389. self2.dot = !!options.dot;
  9390. self2.mark = !!options.mark;
  9391. self2.nodir = !!options.nodir;
  9392. if (self2.nodir)
  9393. self2.mark = true;
  9394. self2.sync = !!options.sync;
  9395. self2.nounique = !!options.nounique;
  9396. self2.nonull = !!options.nonull;
  9397. self2.nosort = !!options.nosort;
  9398. self2.nocase = !!options.nocase;
  9399. self2.stat = !!options.stat;
  9400. self2.noprocess = !!options.noprocess;
  9401. self2.absolute = !!options.absolute;
  9402. self2.fs = options.fs || fs7;
  9403. self2.maxLength = options.maxLength || Infinity;
  9404. self2.cache = options.cache || /* @__PURE__ */ Object.create(null);
  9405. self2.statCache = options.statCache || /* @__PURE__ */ Object.create(null);
  9406. self2.symlinks = options.symlinks || /* @__PURE__ */ Object.create(null);
  9407. setupIgnores(self2, options);
  9408. self2.changedCwd = false;
  9409. var cwd = process.cwd();
  9410. if (!ownProp(options, "cwd"))
  9411. self2.cwd = path4.resolve(cwd);
  9412. else {
  9413. self2.cwd = path4.resolve(options.cwd);
  9414. self2.changedCwd = self2.cwd !== cwd;
  9415. }
  9416. self2.root = options.root || path4.resolve(self2.cwd, "/");
  9417. self2.root = path4.resolve(self2.root);
  9418. self2.cwdAbs = isAbsolute(self2.cwd) ? self2.cwd : makeAbs(self2, self2.cwd);
  9419. self2.nomount = !!options.nomount;
  9420. if (process.platform === "win32") {
  9421. self2.root = self2.root.replace(/\\/g, "/");
  9422. self2.cwd = self2.cwd.replace(/\\/g, "/");
  9423. self2.cwdAbs = self2.cwdAbs.replace(/\\/g, "/");
  9424. }
  9425. options.nonegate = true;
  9426. options.nocomment = true;
  9427. self2.minimatch = new Minimatch2(pattern, options);
  9428. self2.options = self2.minimatch.options;
  9429. }
  9430. function finish(self2) {
  9431. var nou = self2.nounique;
  9432. var all = nou ? [] : /* @__PURE__ */ Object.create(null);
  9433. for (var i4 = 0, l3 = self2.matches.length; i4 < l3; i4++) {
  9434. var matches = self2.matches[i4];
  9435. if (!matches || Object.keys(matches).length === 0) {
  9436. if (self2.nonull) {
  9437. var literal = self2.minimatch.globSet[i4];
  9438. if (nou)
  9439. all.push(literal);
  9440. else
  9441. all[literal] = true;
  9442. }
  9443. } else {
  9444. var m4 = Object.keys(matches);
  9445. if (nou)
  9446. all.push.apply(all, m4);
  9447. else
  9448. m4.forEach(function(m5) {
  9449. all[m5] = true;
  9450. });
  9451. }
  9452. }
  9453. if (!nou)
  9454. all = Object.keys(all);
  9455. if (!self2.nosort)
  9456. all = all.sort(alphasort);
  9457. if (self2.mark) {
  9458. for (var i4 = 0; i4 < all.length; i4++) {
  9459. all[i4] = self2._mark(all[i4]);
  9460. }
  9461. if (self2.nodir) {
  9462. all = all.filter(function(e4) {
  9463. var notDir = !/\/$/.test(e4);
  9464. var c3 = self2.cache[e4] || self2.cache[makeAbs(self2, e4)];
  9465. if (notDir && c3)
  9466. notDir = c3 !== "DIR" && !Array.isArray(c3);
  9467. return notDir;
  9468. });
  9469. }
  9470. }
  9471. if (self2.ignore.length)
  9472. all = all.filter(function(m5) {
  9473. return !isIgnored(self2, m5);
  9474. });
  9475. self2.found = all;
  9476. }
  9477. function mark(self2, p3) {
  9478. var abs = makeAbs(self2, p3);
  9479. var c3 = self2.cache[abs];
  9480. var m4 = p3;
  9481. if (c3) {
  9482. var isDir = c3 === "DIR" || Array.isArray(c3);
  9483. var slash = p3.slice(-1) === "/";
  9484. if (isDir && !slash)
  9485. m4 += "/";
  9486. else if (!isDir && slash)
  9487. m4 = m4.slice(0, -1);
  9488. if (m4 !== p3) {
  9489. var mabs = makeAbs(self2, m4);
  9490. self2.statCache[mabs] = self2.statCache[abs];
  9491. self2.cache[mabs] = self2.cache[abs];
  9492. }
  9493. }
  9494. return m4;
  9495. }
  9496. function makeAbs(self2, f5) {
  9497. var abs = f5;
  9498. if (f5.charAt(0) === "/") {
  9499. abs = path4.join(self2.root, f5);
  9500. } else if (isAbsolute(f5) || f5 === "") {
  9501. abs = f5;
  9502. } else if (self2.changedCwd) {
  9503. abs = path4.resolve(self2.cwd, f5);
  9504. } else {
  9505. abs = path4.resolve(f5);
  9506. }
  9507. if (process.platform === "win32")
  9508. abs = abs.replace(/\\/g, "/");
  9509. return abs;
  9510. }
  9511. function isIgnored(self2, path5) {
  9512. if (!self2.ignore.length)
  9513. return false;
  9514. return self2.ignore.some(function(item) {
  9515. return item.matcher.match(path5) || !!(item.gmatcher && item.gmatcher.match(path5));
  9516. });
  9517. }
  9518. function childrenIgnored(self2, path5) {
  9519. if (!self2.ignore.length)
  9520. return false;
  9521. return self2.ignore.some(function(item) {
  9522. return !!(item.gmatcher && item.gmatcher.match(path5));
  9523. });
  9524. }
  9525. }
  9526. });
  9527. // ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js
  9528. var require_sync = __commonJS({
  9529. "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js"(exports2, module2) {
  9530. module2.exports = globSync;
  9531. globSync.GlobSync = GlobSync;
  9532. var rp = require_fs();
  9533. var minimatch2 = require_minimatch();
  9534. var Minimatch2 = minimatch2.Minimatch;
  9535. var Glob = require_glob().Glob;
  9536. var util2 = require("util");
  9537. var path4 = require("path");
  9538. var assert = require("assert");
  9539. var isAbsolute = require("path").isAbsolute;
  9540. var common = require_common();
  9541. var setopts = common.setopts;
  9542. var ownProp = common.ownProp;
  9543. var childrenIgnored = common.childrenIgnored;
  9544. var isIgnored = common.isIgnored;
  9545. function globSync(pattern, options) {
  9546. if (typeof options === "function" || arguments.length === 3)
  9547. throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
  9548. return new GlobSync(pattern, options).found;
  9549. }
  9550. function GlobSync(pattern, options) {
  9551. if (!pattern)
  9552. throw new Error("must provide pattern");
  9553. if (typeof options === "function" || arguments.length === 3)
  9554. throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
  9555. if (!(this instanceof GlobSync))
  9556. return new GlobSync(pattern, options);
  9557. setopts(this, pattern, options);
  9558. if (this.noprocess)
  9559. return this;
  9560. var n3 = this.minimatch.set.length;
  9561. this.matches = new Array(n3);
  9562. for (var i4 = 0; i4 < n3; i4++) {
  9563. this._process(this.minimatch.set[i4], i4, false);
  9564. }
  9565. this._finish();
  9566. }
  9567. GlobSync.prototype._finish = function() {
  9568. assert.ok(this instanceof GlobSync);
  9569. if (this.realpath) {
  9570. var self2 = this;
  9571. this.matches.forEach(function(matchset, index6) {
  9572. var set = self2.matches[index6] = /* @__PURE__ */ Object.create(null);
  9573. for (var p3 in matchset) {
  9574. try {
  9575. p3 = self2._makeAbs(p3);
  9576. var real = rp.realpathSync(p3, self2.realpathCache);
  9577. set[real] = true;
  9578. } catch (er) {
  9579. if (er.syscall === "stat")
  9580. set[self2._makeAbs(p3)] = true;
  9581. else
  9582. throw er;
  9583. }
  9584. }
  9585. });
  9586. }
  9587. common.finish(this);
  9588. };
  9589. GlobSync.prototype._process = function(pattern, index6, inGlobStar) {
  9590. assert.ok(this instanceof GlobSync);
  9591. var n3 = 0;
  9592. while (typeof pattern[n3] === "string") {
  9593. n3++;
  9594. }
  9595. var prefix2;
  9596. switch (n3) {
  9597. // if not, then this is rather simple
  9598. case pattern.length:
  9599. this._processSimple(pattern.join("/"), index6);
  9600. return;
  9601. case 0:
  9602. prefix2 = null;
  9603. break;
  9604. default:
  9605. prefix2 = pattern.slice(0, n3).join("/");
  9606. break;
  9607. }
  9608. var remain = pattern.slice(n3);
  9609. var read;
  9610. if (prefix2 === null)
  9611. read = ".";
  9612. else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p3) {
  9613. return typeof p3 === "string" ? p3 : "[*]";
  9614. }).join("/"))) {
  9615. if (!prefix2 || !isAbsolute(prefix2))
  9616. prefix2 = "/" + prefix2;
  9617. read = prefix2;
  9618. } else
  9619. read = prefix2;
  9620. var abs = this._makeAbs(read);
  9621. if (childrenIgnored(this, read))
  9622. return;
  9623. var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
  9624. if (isGlobStar)
  9625. this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar);
  9626. else
  9627. this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar);
  9628. };
  9629. GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar) {
  9630. var entries = this._readdir(abs, inGlobStar);
  9631. if (!entries)
  9632. return;
  9633. var pn = remain[0];
  9634. var negate = !!this.minimatch.negate;
  9635. var rawGlob = pn._glob;
  9636. var dotOk = this.dot || rawGlob.charAt(0) === ".";
  9637. var matchedEntries = [];
  9638. for (var i4 = 0; i4 < entries.length; i4++) {
  9639. var e4 = entries[i4];
  9640. if (e4.charAt(0) !== "." || dotOk) {
  9641. var m4;
  9642. if (negate && !prefix2) {
  9643. m4 = !e4.match(pn);
  9644. } else {
  9645. m4 = e4.match(pn);
  9646. }
  9647. if (m4)
  9648. matchedEntries.push(e4);
  9649. }
  9650. }
  9651. var len = matchedEntries.length;
  9652. if (len === 0)
  9653. return;
  9654. if (remain.length === 1 && !this.mark && !this.stat) {
  9655. if (!this.matches[index6])
  9656. this.matches[index6] = /* @__PURE__ */ Object.create(null);
  9657. for (var i4 = 0; i4 < len; i4++) {
  9658. var e4 = matchedEntries[i4];
  9659. if (prefix2) {
  9660. if (prefix2.slice(-1) !== "/")
  9661. e4 = prefix2 + "/" + e4;
  9662. else
  9663. e4 = prefix2 + e4;
  9664. }
  9665. if (e4.charAt(0) === "/" && !this.nomount) {
  9666. e4 = path4.join(this.root, e4);
  9667. }
  9668. this._emitMatch(index6, e4);
  9669. }
  9670. return;
  9671. }
  9672. remain.shift();
  9673. for (var i4 = 0; i4 < len; i4++) {
  9674. var e4 = matchedEntries[i4];
  9675. var newPattern;
  9676. if (prefix2)
  9677. newPattern = [prefix2, e4];
  9678. else
  9679. newPattern = [e4];
  9680. this._process(newPattern.concat(remain), index6, inGlobStar);
  9681. }
  9682. };
  9683. GlobSync.prototype._emitMatch = function(index6, e4) {
  9684. if (isIgnored(this, e4))
  9685. return;
  9686. var abs = this._makeAbs(e4);
  9687. if (this.mark)
  9688. e4 = this._mark(e4);
  9689. if (this.absolute) {
  9690. e4 = abs;
  9691. }
  9692. if (this.matches[index6][e4])
  9693. return;
  9694. if (this.nodir) {
  9695. var c3 = this.cache[abs];
  9696. if (c3 === "DIR" || Array.isArray(c3))
  9697. return;
  9698. }
  9699. this.matches[index6][e4] = true;
  9700. if (this.stat)
  9701. this._stat(e4);
  9702. };
  9703. GlobSync.prototype._readdirInGlobStar = function(abs) {
  9704. if (this.follow)
  9705. return this._readdir(abs, false);
  9706. var entries;
  9707. var lstat;
  9708. var stat2;
  9709. try {
  9710. lstat = this.fs.lstatSync(abs);
  9711. } catch (er) {
  9712. if (er.code === "ENOENT") {
  9713. return null;
  9714. }
  9715. }
  9716. var isSym = lstat && lstat.isSymbolicLink();
  9717. this.symlinks[abs] = isSym;
  9718. if (!isSym && lstat && !lstat.isDirectory())
  9719. this.cache[abs] = "FILE";
  9720. else
  9721. entries = this._readdir(abs, false);
  9722. return entries;
  9723. };
  9724. GlobSync.prototype._readdir = function(abs, inGlobStar) {
  9725. var entries;
  9726. if (inGlobStar && !ownProp(this.symlinks, abs))
  9727. return this._readdirInGlobStar(abs);
  9728. if (ownProp(this.cache, abs)) {
  9729. var c3 = this.cache[abs];
  9730. if (!c3 || c3 === "FILE")
  9731. return null;
  9732. if (Array.isArray(c3))
  9733. return c3;
  9734. }
  9735. try {
  9736. return this._readdirEntries(abs, this.fs.readdirSync(abs));
  9737. } catch (er) {
  9738. this._readdirError(abs, er);
  9739. return null;
  9740. }
  9741. };
  9742. GlobSync.prototype._readdirEntries = function(abs, entries) {
  9743. if (!this.mark && !this.stat) {
  9744. for (var i4 = 0; i4 < entries.length; i4++) {
  9745. var e4 = entries[i4];
  9746. if (abs === "/")
  9747. e4 = abs + e4;
  9748. else
  9749. e4 = abs + "/" + e4;
  9750. this.cache[e4] = true;
  9751. }
  9752. }
  9753. this.cache[abs] = entries;
  9754. return entries;
  9755. };
  9756. GlobSync.prototype._readdirError = function(f5, er) {
  9757. switch (er.code) {
  9758. case "ENOTSUP":
  9759. // https://github.com/isaacs/node-glob/issues/205
  9760. case "ENOTDIR":
  9761. var abs = this._makeAbs(f5);
  9762. this.cache[abs] = "FILE";
  9763. if (abs === this.cwdAbs) {
  9764. var error2 = new Error(er.code + " invalid cwd " + this.cwd);
  9765. error2.path = this.cwd;
  9766. error2.code = er.code;
  9767. throw error2;
  9768. }
  9769. break;
  9770. case "ENOENT":
  9771. // not terribly unusual
  9772. case "ELOOP":
  9773. case "ENAMETOOLONG":
  9774. case "UNKNOWN":
  9775. this.cache[this._makeAbs(f5)] = false;
  9776. break;
  9777. default:
  9778. this.cache[this._makeAbs(f5)] = false;
  9779. if (this.strict)
  9780. throw er;
  9781. if (!this.silent)
  9782. console.error("glob error", er);
  9783. break;
  9784. }
  9785. };
  9786. GlobSync.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar) {
  9787. var entries = this._readdir(abs, inGlobStar);
  9788. if (!entries)
  9789. return;
  9790. var remainWithoutGlobStar = remain.slice(1);
  9791. var gspref = prefix2 ? [prefix2] : [];
  9792. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  9793. this._process(noGlobStar, index6, false);
  9794. var len = entries.length;
  9795. var isSym = this.symlinks[abs];
  9796. if (isSym && inGlobStar)
  9797. return;
  9798. for (var i4 = 0; i4 < len; i4++) {
  9799. var e4 = entries[i4];
  9800. if (e4.charAt(0) === "." && !this.dot)
  9801. continue;
  9802. var instead = gspref.concat(entries[i4], remainWithoutGlobStar);
  9803. this._process(instead, index6, true);
  9804. var below = gspref.concat(entries[i4], remain);
  9805. this._process(below, index6, true);
  9806. }
  9807. };
  9808. GlobSync.prototype._processSimple = function(prefix2, index6) {
  9809. var exists = this._stat(prefix2);
  9810. if (!this.matches[index6])
  9811. this.matches[index6] = /* @__PURE__ */ Object.create(null);
  9812. if (!exists)
  9813. return;
  9814. if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
  9815. var trail = /[\/\\]$/.test(prefix2);
  9816. if (prefix2.charAt(0) === "/") {
  9817. prefix2 = path4.join(this.root, prefix2);
  9818. } else {
  9819. prefix2 = path4.resolve(this.root, prefix2);
  9820. if (trail)
  9821. prefix2 += "/";
  9822. }
  9823. }
  9824. if (process.platform === "win32")
  9825. prefix2 = prefix2.replace(/\\/g, "/");
  9826. this._emitMatch(index6, prefix2);
  9827. };
  9828. GlobSync.prototype._stat = function(f5) {
  9829. var abs = this._makeAbs(f5);
  9830. var needDir = f5.slice(-1) === "/";
  9831. if (f5.length > this.maxLength)
  9832. return false;
  9833. if (!this.stat && ownProp(this.cache, abs)) {
  9834. var c3 = this.cache[abs];
  9835. if (Array.isArray(c3))
  9836. c3 = "DIR";
  9837. if (!needDir || c3 === "DIR")
  9838. return c3;
  9839. if (needDir && c3 === "FILE")
  9840. return false;
  9841. }
  9842. var exists;
  9843. var stat2 = this.statCache[abs];
  9844. if (!stat2) {
  9845. var lstat;
  9846. try {
  9847. lstat = this.fs.lstatSync(abs);
  9848. } catch (er) {
  9849. if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
  9850. this.statCache[abs] = false;
  9851. return false;
  9852. }
  9853. }
  9854. if (lstat && lstat.isSymbolicLink()) {
  9855. try {
  9856. stat2 = this.fs.statSync(abs);
  9857. } catch (er) {
  9858. stat2 = lstat;
  9859. }
  9860. } else {
  9861. stat2 = lstat;
  9862. }
  9863. }
  9864. this.statCache[abs] = stat2;
  9865. var c3 = true;
  9866. if (stat2)
  9867. c3 = stat2.isDirectory() ? "DIR" : "FILE";
  9868. this.cache[abs] = this.cache[abs] || c3;
  9869. if (needDir && c3 === "FILE")
  9870. return false;
  9871. return c3;
  9872. };
  9873. GlobSync.prototype._mark = function(p3) {
  9874. return common.mark(this, p3);
  9875. };
  9876. GlobSync.prototype._makeAbs = function(f5) {
  9877. return common.makeAbs(this, f5);
  9878. };
  9879. }
  9880. });
  9881. // ../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js
  9882. var require_wrappy = __commonJS({
  9883. "../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js"(exports2, module2) {
  9884. module2.exports = wrappy;
  9885. function wrappy(fn, cb) {
  9886. if (fn && cb) return wrappy(fn)(cb);
  9887. if (typeof fn !== "function")
  9888. throw new TypeError("need wrapper function");
  9889. Object.keys(fn).forEach(function(k3) {
  9890. wrapper[k3] = fn[k3];
  9891. });
  9892. return wrapper;
  9893. function wrapper() {
  9894. var args = new Array(arguments.length);
  9895. for (var i4 = 0; i4 < args.length; i4++) {
  9896. args[i4] = arguments[i4];
  9897. }
  9898. var ret = fn.apply(this, args);
  9899. var cb2 = args[args.length - 1];
  9900. if (typeof ret === "function" && ret !== cb2) {
  9901. Object.keys(cb2).forEach(function(k3) {
  9902. ret[k3] = cb2[k3];
  9903. });
  9904. }
  9905. return ret;
  9906. }
  9907. }
  9908. }
  9909. });
  9910. // ../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js
  9911. var require_once = __commonJS({
  9912. "../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js"(exports2, module2) {
  9913. var wrappy = require_wrappy();
  9914. module2.exports = wrappy(once);
  9915. module2.exports.strict = wrappy(onceStrict);
  9916. once.proto = once(function() {
  9917. Object.defineProperty(Function.prototype, "once", {
  9918. value: function() {
  9919. return once(this);
  9920. },
  9921. configurable: true
  9922. });
  9923. Object.defineProperty(Function.prototype, "onceStrict", {
  9924. value: function() {
  9925. return onceStrict(this);
  9926. },
  9927. configurable: true
  9928. });
  9929. });
  9930. function once(fn) {
  9931. var f5 = function() {
  9932. if (f5.called) return f5.value;
  9933. f5.called = true;
  9934. return f5.value = fn.apply(this, arguments);
  9935. };
  9936. f5.called = false;
  9937. return f5;
  9938. }
  9939. function onceStrict(fn) {
  9940. var f5 = function() {
  9941. if (f5.called)
  9942. throw new Error(f5.onceError);
  9943. f5.called = true;
  9944. return f5.value = fn.apply(this, arguments);
  9945. };
  9946. var name = fn.name || "Function wrapped with `once`";
  9947. f5.onceError = name + " shouldn't be called more than once";
  9948. f5.called = false;
  9949. return f5;
  9950. }
  9951. }
  9952. });
  9953. // ../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js
  9954. var require_inflight = __commonJS({
  9955. "../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js"(exports2, module2) {
  9956. var wrappy = require_wrappy();
  9957. var reqs = /* @__PURE__ */ Object.create(null);
  9958. var once = require_once();
  9959. module2.exports = wrappy(inflight);
  9960. function inflight(key, cb) {
  9961. if (reqs[key]) {
  9962. reqs[key].push(cb);
  9963. return null;
  9964. } else {
  9965. reqs[key] = [cb];
  9966. return makeres(key);
  9967. }
  9968. }
  9969. function makeres(key) {
  9970. return once(function RES() {
  9971. var cbs = reqs[key];
  9972. var len = cbs.length;
  9973. var args = slice(arguments);
  9974. try {
  9975. for (var i4 = 0; i4 < len; i4++) {
  9976. cbs[i4].apply(null, args);
  9977. }
  9978. } finally {
  9979. if (cbs.length > len) {
  9980. cbs.splice(0, len);
  9981. process.nextTick(function() {
  9982. RES.apply(null, args);
  9983. });
  9984. } else {
  9985. delete reqs[key];
  9986. }
  9987. }
  9988. });
  9989. }
  9990. function slice(args) {
  9991. var length = args.length;
  9992. var array2 = [];
  9993. for (var i4 = 0; i4 < length; i4++) array2[i4] = args[i4];
  9994. return array2;
  9995. }
  9996. }
  9997. });
  9998. // ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js
  9999. var require_glob = __commonJS({
  10000. "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js"(exports2, module2) {
  10001. module2.exports = glob2;
  10002. var rp = require_fs();
  10003. var minimatch2 = require_minimatch();
  10004. var Minimatch2 = minimatch2.Minimatch;
  10005. var inherits = require_inherits();
  10006. var EE = require("events").EventEmitter;
  10007. var path4 = require("path");
  10008. var assert = require("assert");
  10009. var isAbsolute = require("path").isAbsolute;
  10010. var globSync = require_sync();
  10011. var common = require_common();
  10012. var setopts = common.setopts;
  10013. var ownProp = common.ownProp;
  10014. var inflight = require_inflight();
  10015. var util2 = require("util");
  10016. var childrenIgnored = common.childrenIgnored;
  10017. var isIgnored = common.isIgnored;
  10018. var once = require_once();
  10019. function glob2(pattern, options, cb) {
  10020. if (typeof options === "function") cb = options, options = {};
  10021. if (!options) options = {};
  10022. if (options.sync) {
  10023. if (cb)
  10024. throw new TypeError("callback provided to sync glob");
  10025. return globSync(pattern, options);
  10026. }
  10027. return new Glob(pattern, options, cb);
  10028. }
  10029. glob2.sync = globSync;
  10030. var GlobSync = glob2.GlobSync = globSync.GlobSync;
  10031. glob2.glob = glob2;
  10032. function extend(origin, add) {
  10033. if (add === null || typeof add !== "object") {
  10034. return origin;
  10035. }
  10036. var keys = Object.keys(add);
  10037. var i4 = keys.length;
  10038. while (i4--) {
  10039. origin[keys[i4]] = add[keys[i4]];
  10040. }
  10041. return origin;
  10042. }
  10043. glob2.hasMagic = function(pattern, options_) {
  10044. var options = extend({}, options_);
  10045. options.noprocess = true;
  10046. var g3 = new Glob(pattern, options);
  10047. var set = g3.minimatch.set;
  10048. if (!pattern)
  10049. return false;
  10050. if (set.length > 1)
  10051. return true;
  10052. for (var j3 = 0; j3 < set[0].length; j3++) {
  10053. if (typeof set[0][j3] !== "string")
  10054. return true;
  10055. }
  10056. return false;
  10057. };
  10058. glob2.Glob = Glob;
  10059. inherits(Glob, EE);
  10060. function Glob(pattern, options, cb) {
  10061. if (typeof options === "function") {
  10062. cb = options;
  10063. options = null;
  10064. }
  10065. if (options && options.sync) {
  10066. if (cb)
  10067. throw new TypeError("callback provided to sync glob");
  10068. return new GlobSync(pattern, options);
  10069. }
  10070. if (!(this instanceof Glob))
  10071. return new Glob(pattern, options, cb);
  10072. setopts(this, pattern, options);
  10073. this._didRealPath = false;
  10074. var n3 = this.minimatch.set.length;
  10075. this.matches = new Array(n3);
  10076. if (typeof cb === "function") {
  10077. cb = once(cb);
  10078. this.on("error", cb);
  10079. this.on("end", function(matches) {
  10080. cb(null, matches);
  10081. });
  10082. }
  10083. var self2 = this;
  10084. this._processing = 0;
  10085. this._emitQueue = [];
  10086. this._processQueue = [];
  10087. this.paused = false;
  10088. if (this.noprocess)
  10089. return this;
  10090. if (n3 === 0)
  10091. return done();
  10092. var sync2 = true;
  10093. for (var i4 = 0; i4 < n3; i4++) {
  10094. this._process(this.minimatch.set[i4], i4, false, done);
  10095. }
  10096. sync2 = false;
  10097. function done() {
  10098. --self2._processing;
  10099. if (self2._processing <= 0) {
  10100. if (sync2) {
  10101. process.nextTick(function() {
  10102. self2._finish();
  10103. });
  10104. } else {
  10105. self2._finish();
  10106. }
  10107. }
  10108. }
  10109. }
  10110. Glob.prototype._finish = function() {
  10111. assert(this instanceof Glob);
  10112. if (this.aborted)
  10113. return;
  10114. if (this.realpath && !this._didRealpath)
  10115. return this._realpath();
  10116. common.finish(this);
  10117. this.emit("end", this.found);
  10118. };
  10119. Glob.prototype._realpath = function() {
  10120. if (this._didRealpath)
  10121. return;
  10122. this._didRealpath = true;
  10123. var n3 = this.matches.length;
  10124. if (n3 === 0)
  10125. return this._finish();
  10126. var self2 = this;
  10127. for (var i4 = 0; i4 < this.matches.length; i4++)
  10128. this._realpathSet(i4, next);
  10129. function next() {
  10130. if (--n3 === 0)
  10131. self2._finish();
  10132. }
  10133. };
  10134. Glob.prototype._realpathSet = function(index6, cb) {
  10135. var matchset = this.matches[index6];
  10136. if (!matchset)
  10137. return cb();
  10138. var found = Object.keys(matchset);
  10139. var self2 = this;
  10140. var n3 = found.length;
  10141. if (n3 === 0)
  10142. return cb();
  10143. var set = this.matches[index6] = /* @__PURE__ */ Object.create(null);
  10144. found.forEach(function(p3, i4) {
  10145. p3 = self2._makeAbs(p3);
  10146. rp.realpath(p3, self2.realpathCache, function(er, real) {
  10147. if (!er)
  10148. set[real] = true;
  10149. else if (er.syscall === "stat")
  10150. set[p3] = true;
  10151. else
  10152. self2.emit("error", er);
  10153. if (--n3 === 0) {
  10154. self2.matches[index6] = set;
  10155. cb();
  10156. }
  10157. });
  10158. });
  10159. };
  10160. Glob.prototype._mark = function(p3) {
  10161. return common.mark(this, p3);
  10162. };
  10163. Glob.prototype._makeAbs = function(f5) {
  10164. return common.makeAbs(this, f5);
  10165. };
  10166. Glob.prototype.abort = function() {
  10167. this.aborted = true;
  10168. this.emit("abort");
  10169. };
  10170. Glob.prototype.pause = function() {
  10171. if (!this.paused) {
  10172. this.paused = true;
  10173. this.emit("pause");
  10174. }
  10175. };
  10176. Glob.prototype.resume = function() {
  10177. if (this.paused) {
  10178. this.emit("resume");
  10179. this.paused = false;
  10180. if (this._emitQueue.length) {
  10181. var eq = this._emitQueue.slice(0);
  10182. this._emitQueue.length = 0;
  10183. for (var i4 = 0; i4 < eq.length; i4++) {
  10184. var e4 = eq[i4];
  10185. this._emitMatch(e4[0], e4[1]);
  10186. }
  10187. }
  10188. if (this._processQueue.length) {
  10189. var pq = this._processQueue.slice(0);
  10190. this._processQueue.length = 0;
  10191. for (var i4 = 0; i4 < pq.length; i4++) {
  10192. var p3 = pq[i4];
  10193. this._processing--;
  10194. this._process(p3[0], p3[1], p3[2], p3[3]);
  10195. }
  10196. }
  10197. }
  10198. };
  10199. Glob.prototype._process = function(pattern, index6, inGlobStar, cb) {
  10200. assert(this instanceof Glob);
  10201. assert(typeof cb === "function");
  10202. if (this.aborted)
  10203. return;
  10204. this._processing++;
  10205. if (this.paused) {
  10206. this._processQueue.push([pattern, index6, inGlobStar, cb]);
  10207. return;
  10208. }
  10209. var n3 = 0;
  10210. while (typeof pattern[n3] === "string") {
  10211. n3++;
  10212. }
  10213. var prefix2;
  10214. switch (n3) {
  10215. // if not, then this is rather simple
  10216. case pattern.length:
  10217. this._processSimple(pattern.join("/"), index6, cb);
  10218. return;
  10219. case 0:
  10220. prefix2 = null;
  10221. break;
  10222. default:
  10223. prefix2 = pattern.slice(0, n3).join("/");
  10224. break;
  10225. }
  10226. var remain = pattern.slice(n3);
  10227. var read;
  10228. if (prefix2 === null)
  10229. read = ".";
  10230. else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p3) {
  10231. return typeof p3 === "string" ? p3 : "[*]";
  10232. }).join("/"))) {
  10233. if (!prefix2 || !isAbsolute(prefix2))
  10234. prefix2 = "/" + prefix2;
  10235. read = prefix2;
  10236. } else
  10237. read = prefix2;
  10238. var abs = this._makeAbs(read);
  10239. if (childrenIgnored(this, read))
  10240. return cb();
  10241. var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
  10242. if (isGlobStar)
  10243. this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar, cb);
  10244. else
  10245. this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar, cb);
  10246. };
  10247. Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar, cb) {
  10248. var self2 = this;
  10249. this._readdir(abs, inGlobStar, function(er, entries) {
  10250. return self2._processReaddir2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb);
  10251. });
  10252. };
  10253. Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) {
  10254. if (!entries)
  10255. return cb();
  10256. var pn = remain[0];
  10257. var negate = !!this.minimatch.negate;
  10258. var rawGlob = pn._glob;
  10259. var dotOk = this.dot || rawGlob.charAt(0) === ".";
  10260. var matchedEntries = [];
  10261. for (var i4 = 0; i4 < entries.length; i4++) {
  10262. var e4 = entries[i4];
  10263. if (e4.charAt(0) !== "." || dotOk) {
  10264. var m4;
  10265. if (negate && !prefix2) {
  10266. m4 = !e4.match(pn);
  10267. } else {
  10268. m4 = e4.match(pn);
  10269. }
  10270. if (m4)
  10271. matchedEntries.push(e4);
  10272. }
  10273. }
  10274. var len = matchedEntries.length;
  10275. if (len === 0)
  10276. return cb();
  10277. if (remain.length === 1 && !this.mark && !this.stat) {
  10278. if (!this.matches[index6])
  10279. this.matches[index6] = /* @__PURE__ */ Object.create(null);
  10280. for (var i4 = 0; i4 < len; i4++) {
  10281. var e4 = matchedEntries[i4];
  10282. if (prefix2) {
  10283. if (prefix2 !== "/")
  10284. e4 = prefix2 + "/" + e4;
  10285. else
  10286. e4 = prefix2 + e4;
  10287. }
  10288. if (e4.charAt(0) === "/" && !this.nomount) {
  10289. e4 = path4.join(this.root, e4);
  10290. }
  10291. this._emitMatch(index6, e4);
  10292. }
  10293. return cb();
  10294. }
  10295. remain.shift();
  10296. for (var i4 = 0; i4 < len; i4++) {
  10297. var e4 = matchedEntries[i4];
  10298. var newPattern;
  10299. if (prefix2) {
  10300. if (prefix2 !== "/")
  10301. e4 = prefix2 + "/" + e4;
  10302. else
  10303. e4 = prefix2 + e4;
  10304. }
  10305. this._process([e4].concat(remain), index6, inGlobStar, cb);
  10306. }
  10307. cb();
  10308. };
  10309. Glob.prototype._emitMatch = function(index6, e4) {
  10310. if (this.aborted)
  10311. return;
  10312. if (isIgnored(this, e4))
  10313. return;
  10314. if (this.paused) {
  10315. this._emitQueue.push([index6, e4]);
  10316. return;
  10317. }
  10318. var abs = isAbsolute(e4) ? e4 : this._makeAbs(e4);
  10319. if (this.mark)
  10320. e4 = this._mark(e4);
  10321. if (this.absolute)
  10322. e4 = abs;
  10323. if (this.matches[index6][e4])
  10324. return;
  10325. if (this.nodir) {
  10326. var c3 = this.cache[abs];
  10327. if (c3 === "DIR" || Array.isArray(c3))
  10328. return;
  10329. }
  10330. this.matches[index6][e4] = true;
  10331. var st = this.statCache[abs];
  10332. if (st)
  10333. this.emit("stat", e4, st);
  10334. this.emit("match", e4);
  10335. };
  10336. Glob.prototype._readdirInGlobStar = function(abs, cb) {
  10337. if (this.aborted)
  10338. return;
  10339. if (this.follow)
  10340. return this._readdir(abs, false, cb);
  10341. var lstatkey = "lstat\0" + abs;
  10342. var self2 = this;
  10343. var lstatcb = inflight(lstatkey, lstatcb_);
  10344. if (lstatcb)
  10345. self2.fs.lstat(abs, lstatcb);
  10346. function lstatcb_(er, lstat) {
  10347. if (er && er.code === "ENOENT")
  10348. return cb();
  10349. var isSym = lstat && lstat.isSymbolicLink();
  10350. self2.symlinks[abs] = isSym;
  10351. if (!isSym && lstat && !lstat.isDirectory()) {
  10352. self2.cache[abs] = "FILE";
  10353. cb();
  10354. } else
  10355. self2._readdir(abs, false, cb);
  10356. }
  10357. };
  10358. Glob.prototype._readdir = function(abs, inGlobStar, cb) {
  10359. if (this.aborted)
  10360. return;
  10361. cb = inflight("readdir\0" + abs + "\0" + inGlobStar, cb);
  10362. if (!cb)
  10363. return;
  10364. if (inGlobStar && !ownProp(this.symlinks, abs))
  10365. return this._readdirInGlobStar(abs, cb);
  10366. if (ownProp(this.cache, abs)) {
  10367. var c3 = this.cache[abs];
  10368. if (!c3 || c3 === "FILE")
  10369. return cb();
  10370. if (Array.isArray(c3))
  10371. return cb(null, c3);
  10372. }
  10373. var self2 = this;
  10374. self2.fs.readdir(abs, readdirCb(this, abs, cb));
  10375. };
  10376. function readdirCb(self2, abs, cb) {
  10377. return function(er, entries) {
  10378. if (er)
  10379. self2._readdirError(abs, er, cb);
  10380. else
  10381. self2._readdirEntries(abs, entries, cb);
  10382. };
  10383. }
  10384. Glob.prototype._readdirEntries = function(abs, entries, cb) {
  10385. if (this.aborted)
  10386. return;
  10387. if (!this.mark && !this.stat) {
  10388. for (var i4 = 0; i4 < entries.length; i4++) {
  10389. var e4 = entries[i4];
  10390. if (abs === "/")
  10391. e4 = abs + e4;
  10392. else
  10393. e4 = abs + "/" + e4;
  10394. this.cache[e4] = true;
  10395. }
  10396. }
  10397. this.cache[abs] = entries;
  10398. return cb(null, entries);
  10399. };
  10400. Glob.prototype._readdirError = function(f5, er, cb) {
  10401. if (this.aborted)
  10402. return;
  10403. switch (er.code) {
  10404. case "ENOTSUP":
  10405. // https://github.com/isaacs/node-glob/issues/205
  10406. case "ENOTDIR":
  10407. var abs = this._makeAbs(f5);
  10408. this.cache[abs] = "FILE";
  10409. if (abs === this.cwdAbs) {
  10410. var error2 = new Error(er.code + " invalid cwd " + this.cwd);
  10411. error2.path = this.cwd;
  10412. error2.code = er.code;
  10413. this.emit("error", error2);
  10414. this.abort();
  10415. }
  10416. break;
  10417. case "ENOENT":
  10418. // not terribly unusual
  10419. case "ELOOP":
  10420. case "ENAMETOOLONG":
  10421. case "UNKNOWN":
  10422. this.cache[this._makeAbs(f5)] = false;
  10423. break;
  10424. default:
  10425. this.cache[this._makeAbs(f5)] = false;
  10426. if (this.strict) {
  10427. this.emit("error", er);
  10428. this.abort();
  10429. }
  10430. if (!this.silent)
  10431. console.error("glob error", er);
  10432. break;
  10433. }
  10434. return cb();
  10435. };
  10436. Glob.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar, cb) {
  10437. var self2 = this;
  10438. this._readdir(abs, inGlobStar, function(er, entries) {
  10439. self2._processGlobStar2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb);
  10440. });
  10441. };
  10442. Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) {
  10443. if (!entries)
  10444. return cb();
  10445. var remainWithoutGlobStar = remain.slice(1);
  10446. var gspref = prefix2 ? [prefix2] : [];
  10447. var noGlobStar = gspref.concat(remainWithoutGlobStar);
  10448. this._process(noGlobStar, index6, false, cb);
  10449. var isSym = this.symlinks[abs];
  10450. var len = entries.length;
  10451. if (isSym && inGlobStar)
  10452. return cb();
  10453. for (var i4 = 0; i4 < len; i4++) {
  10454. var e4 = entries[i4];
  10455. if (e4.charAt(0) === "." && !this.dot)
  10456. continue;
  10457. var instead = gspref.concat(entries[i4], remainWithoutGlobStar);
  10458. this._process(instead, index6, true, cb);
  10459. var below = gspref.concat(entries[i4], remain);
  10460. this._process(below, index6, true, cb);
  10461. }
  10462. cb();
  10463. };
  10464. Glob.prototype._processSimple = function(prefix2, index6, cb) {
  10465. var self2 = this;
  10466. this._stat(prefix2, function(er, exists) {
  10467. self2._processSimple2(prefix2, index6, er, exists, cb);
  10468. });
  10469. };
  10470. Glob.prototype._processSimple2 = function(prefix2, index6, er, exists, cb) {
  10471. if (!this.matches[index6])
  10472. this.matches[index6] = /* @__PURE__ */ Object.create(null);
  10473. if (!exists)
  10474. return cb();
  10475. if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
  10476. var trail = /[\/\\]$/.test(prefix2);
  10477. if (prefix2.charAt(0) === "/") {
  10478. prefix2 = path4.join(this.root, prefix2);
  10479. } else {
  10480. prefix2 = path4.resolve(this.root, prefix2);
  10481. if (trail)
  10482. prefix2 += "/";
  10483. }
  10484. }
  10485. if (process.platform === "win32")
  10486. prefix2 = prefix2.replace(/\\/g, "/");
  10487. this._emitMatch(index6, prefix2);
  10488. cb();
  10489. };
  10490. Glob.prototype._stat = function(f5, cb) {
  10491. var abs = this._makeAbs(f5);
  10492. var needDir = f5.slice(-1) === "/";
  10493. if (f5.length > this.maxLength)
  10494. return cb();
  10495. if (!this.stat && ownProp(this.cache, abs)) {
  10496. var c3 = this.cache[abs];
  10497. if (Array.isArray(c3))
  10498. c3 = "DIR";
  10499. if (!needDir || c3 === "DIR")
  10500. return cb(null, c3);
  10501. if (needDir && c3 === "FILE")
  10502. return cb();
  10503. }
  10504. var exists;
  10505. var stat2 = this.statCache[abs];
  10506. if (stat2 !== void 0) {
  10507. if (stat2 === false)
  10508. return cb(null, stat2);
  10509. else {
  10510. var type = stat2.isDirectory() ? "DIR" : "FILE";
  10511. if (needDir && type === "FILE")
  10512. return cb();
  10513. else
  10514. return cb(null, type, stat2);
  10515. }
  10516. }
  10517. var self2 = this;
  10518. var statcb = inflight("stat\0" + abs, lstatcb_);
  10519. if (statcb)
  10520. self2.fs.lstat(abs, statcb);
  10521. function lstatcb_(er, lstat) {
  10522. if (lstat && lstat.isSymbolicLink()) {
  10523. return self2.fs.stat(abs, function(er2, stat3) {
  10524. if (er2)
  10525. self2._stat2(f5, abs, null, lstat, cb);
  10526. else
  10527. self2._stat2(f5, abs, er2, stat3, cb);
  10528. });
  10529. } else {
  10530. self2._stat2(f5, abs, er, lstat, cb);
  10531. }
  10532. }
  10533. };
  10534. Glob.prototype._stat2 = function(f5, abs, er, stat2, cb) {
  10535. if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
  10536. this.statCache[abs] = false;
  10537. return cb();
  10538. }
  10539. var needDir = f5.slice(-1) === "/";
  10540. this.statCache[abs] = stat2;
  10541. if (abs.slice(-1) === "/" && stat2 && !stat2.isDirectory())
  10542. return cb(null, false, stat2);
  10543. var c3 = true;
  10544. if (stat2)
  10545. c3 = stat2.isDirectory() ? "DIR" : "FILE";
  10546. this.cache[abs] = this.cache[abs] || c3;
  10547. if (needDir && c3 === "FILE")
  10548. return cb();
  10549. return cb(null, c3, stat2);
  10550. };
  10551. }
  10552. });
  10553. // src/extensions/getTablesFilterByExtensions.ts
  10554. var getTablesFilterByExtensions;
  10555. var init_getTablesFilterByExtensions = __esm({
  10556. "src/extensions/getTablesFilterByExtensions.ts"() {
  10557. "use strict";
  10558. getTablesFilterByExtensions = ({
  10559. extensionsFilters,
  10560. dialect: dialect6
  10561. }) => {
  10562. if (extensionsFilters) {
  10563. if (extensionsFilters.includes("postgis") && dialect6 === "postgresql") {
  10564. return ["!geography_columns", "!geometry_columns", "!spatial_ref_sys"];
  10565. }
  10566. }
  10567. return [];
  10568. };
  10569. }
  10570. });
  10571. // src/cli/validations/outputs.ts
  10572. var withStyle, outputs;
  10573. var init_outputs = __esm({
  10574. "src/cli/validations/outputs.ts"() {
  10575. "use strict";
  10576. init_source();
  10577. init_common();
  10578. withStyle = {
  10579. error: (str) => `${source_default.red(`${source_default.white.bgRed(" Invalid input ")} ${str}`)}`,
  10580. warning: (str) => `${source_default.white.bgGray(" Warning ")} ${str}`,
  10581. errorWarning: (str) => `${source_default.red(`${source_default.white.bgRed(" Warning ")} ${str}`)}`,
  10582. fullWarning: (str) => `${source_default.black.bgYellow(" Warning ")} ${source_default.bold(str)}`,
  10583. suggestion: (str) => `${source_default.white.bgGray(" Suggestion ")} ${str}`,
  10584. info: (str) => `${source_default.grey(str)}`
  10585. };
  10586. outputs = {
  10587. studio: {
  10588. drivers: (param) => withStyle.error(
  10589. `"${param}" is not a valid driver. Available drivers: "pg", "mysql2", "better-sqlite", "libsql", "turso". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
  10590. ),
  10591. noCredentials: () => withStyle.error(
  10592. `Please specify a 'dbCredentials' param in config. It will help drizzle to know how to query you database. You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
  10593. ),
  10594. noDriver: () => withStyle.error(
  10595. `Please specify a 'driver' param in config. It will help drizzle to know how to query you database. You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
  10596. ),
  10597. noDialect: () => withStyle.error(
  10598. `Please specify 'dialect' param in config, either of 'postgresql', 'mysql', 'sqlite', turso or singlestore`
  10599. )
  10600. },
  10601. common: {
  10602. ambiguousParams: (command) => withStyle.error(
  10603. `You can't use both --config and other cli options for ${command} command`
  10604. ),
  10605. schema: (command) => withStyle.error(`"--schema" is a required field for ${command} command`)
  10606. },
  10607. postgres: {
  10608. connection: {
  10609. required: () => withStyle.error(
  10610. `Either "url" or "host", "database" are required for database connection`
  10611. ),
  10612. awsDataApi: () => withStyle.error(
  10613. "You need to provide 'database', 'secretArn' and 'resourceArn' for Drizzle Kit to connect to AWS Data API"
  10614. )
  10615. }
  10616. },
  10617. mysql: {
  10618. connection: {
  10619. driver: () => withStyle.error(`Only "mysql2" is available options for "--driver"`),
  10620. required: () => withStyle.error(
  10621. `Either "url" or "host", "database" are required for database connection`
  10622. )
  10623. }
  10624. },
  10625. sqlite: {
  10626. connection: {
  10627. driver: () => {
  10628. const listOfDrivers = sqliteDriversLiterals.map((it) => `'${it.value}'`).join(", ");
  10629. return withStyle.error(
  10630. `Either ${listOfDrivers} are available options for 'driver' param`
  10631. );
  10632. },
  10633. url: (driver2) => withStyle.error(
  10634. `"url" is a required option for driver "${driver2}". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
  10635. ),
  10636. authToken: (driver2) => withStyle.error(
  10637. `"authToken" is a required option for driver "${driver2}". You can read more about drizzle.config: https://orm.drizzle.team/kit-docs/config-reference`
  10638. )
  10639. },
  10640. introspect: {},
  10641. push: {}
  10642. },
  10643. singlestore: {
  10644. connection: {
  10645. driver: () => withStyle.error(`Only "mysql2" is available options for "--driver"`),
  10646. required: () => withStyle.error(
  10647. `Either "url" or "host", "database" are required for database connection`
  10648. )
  10649. }
  10650. }
  10651. };
  10652. }
  10653. });
  10654. // src/cli/validations/common.ts
  10655. var assertCollisions, sqliteDriversLiterals, postgresqlDriversLiterals, prefixes, prefix, casingTypes, casingType, sqliteDriver, postgresDriver, driver, configMigrations, configCommonSchema, casing, introspectParams, configIntrospectCliSchema, configGenerateSchema, configPushSchema, drivers, wrapParam;
  10656. var init_common = __esm({
  10657. "src/cli/validations/common.ts"() {
  10658. "use strict";
  10659. init_source();
  10660. init_esm();
  10661. init_schemaValidator();
  10662. init_outputs();
  10663. assertCollisions = (command, options, whitelist, remainingKeys) => {
  10664. const { config, ...rest } = options;
  10665. let atLeastOneParam = false;
  10666. for (const key of Object.keys(rest)) {
  10667. if (whitelist.includes(key)) continue;
  10668. atLeastOneParam = atLeastOneParam || rest[key] !== void 0;
  10669. }
  10670. if (!config && atLeastOneParam) {
  10671. return "cli";
  10672. }
  10673. if (!atLeastOneParam) {
  10674. return "config";
  10675. }
  10676. console.log(outputs.common.ambiguousParams(command));
  10677. process.exit(1);
  10678. };
  10679. sqliteDriversLiterals = [
  10680. literalType("d1-http"),
  10681. literalType("expo"),
  10682. literalType("durable-sqlite")
  10683. ];
  10684. postgresqlDriversLiterals = [
  10685. literalType("aws-data-api"),
  10686. literalType("pglite")
  10687. ];
  10688. prefixes = [
  10689. "index",
  10690. "timestamp",
  10691. "supabase",
  10692. "unix",
  10693. "none"
  10694. ];
  10695. prefix = enumType(prefixes);
  10696. {
  10697. const _3 = "";
  10698. }
  10699. casingTypes = ["snake_case", "camelCase"];
  10700. casingType = enumType(casingTypes);
  10701. sqliteDriver = unionType(sqliteDriversLiterals);
  10702. postgresDriver = unionType(postgresqlDriversLiterals);
  10703. driver = unionType([sqliteDriver, postgresDriver]);
  10704. configMigrations = objectType({
  10705. table: stringType().optional(),
  10706. schema: stringType().optional(),
  10707. prefix: prefix.optional().default("index")
  10708. }).optional();
  10709. configCommonSchema = objectType({
  10710. dialect: dialect4,
  10711. schema: unionType([stringType(), stringType().array()]).optional(),
  10712. out: stringType().optional(),
  10713. breakpoints: booleanType().optional().default(true),
  10714. verbose: booleanType().optional().default(false),
  10715. driver: driver.optional(),
  10716. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  10717. schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
  10718. migrations: configMigrations,
  10719. dbCredentials: anyType().optional(),
  10720. casing: casingType.optional(),
  10721. sql: booleanType().default(true)
  10722. }).passthrough();
  10723. casing = unionType([literalType("camel"), literalType("preserve")]).default(
  10724. "camel"
  10725. );
  10726. introspectParams = objectType({
  10727. schema: unionType([stringType(), stringType().array()]).optional(),
  10728. out: stringType().optional().default("./drizzle"),
  10729. breakpoints: booleanType().default(true),
  10730. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  10731. schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
  10732. introspect: objectType({
  10733. casing
  10734. }).default({ casing: "camel" })
  10735. });
  10736. configIntrospectCliSchema = objectType({
  10737. schema: unionType([stringType(), stringType().array()]).optional(),
  10738. out: stringType().optional().default("./drizzle"),
  10739. breakpoints: booleanType().default(true),
  10740. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  10741. schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
  10742. introspectCasing: unionType([literalType("camel"), literalType("preserve")]).default(
  10743. "camel"
  10744. )
  10745. });
  10746. configGenerateSchema = objectType({
  10747. schema: unionType([stringType(), stringType().array()]),
  10748. out: stringType().optional().default("./drizzle"),
  10749. breakpoints: booleanType().default(true)
  10750. });
  10751. configPushSchema = objectType({
  10752. dialect: dialect4,
  10753. schema: unionType([stringType(), stringType().array()]),
  10754. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  10755. schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
  10756. verbose: booleanType().default(false),
  10757. strict: booleanType().default(false),
  10758. out: stringType().optional()
  10759. });
  10760. drivers = ["d1-http", "expo", "aws-data-api", "pglite", "durable-sqlite"];
  10761. wrapParam = (name, param, optional = false, type) => {
  10762. const check2 = `[${source_default.green("\u2713")}]`;
  10763. const cross = `[${source_default.red("x")}]`;
  10764. if (typeof param === "string") {
  10765. if (param.length === 0) {
  10766. return ` ${cross} ${name}: ''`;
  10767. }
  10768. if (type === "secret") {
  10769. return ` ${check2} ${name}: '*****'`;
  10770. } else if (type === "url") {
  10771. return ` ${check2} ${name}: '${param.replace(/(?<=:\/\/[^:\n]*:)([^@]*)/, "****")}'`;
  10772. }
  10773. return ` ${check2} ${name}: '${param}'`;
  10774. }
  10775. if (optional) {
  10776. return source_default.gray(` ${name}?: `);
  10777. }
  10778. return ` ${cross} ${name}: ${source_default.gray("undefined")}`;
  10779. };
  10780. }
  10781. });
  10782. // src/cli/validations/cli.ts
  10783. var cliConfigGenerate, pushParams, pullParams, configCheck, cliConfigCheck;
  10784. var init_cli = __esm({
  10785. "src/cli/validations/cli.ts"() {
  10786. "use strict";
  10787. init_esm();
  10788. init_schemaValidator();
  10789. init_common();
  10790. cliConfigGenerate = objectType({
  10791. dialect: dialect4.optional(),
  10792. schema: unionType([stringType(), stringType().array()]).optional(),
  10793. out: stringType().optional().default("./drizzle"),
  10794. config: stringType().optional(),
  10795. name: stringType().optional(),
  10796. prefix: prefix.optional(),
  10797. breakpoints: booleanType().optional().default(true),
  10798. custom: booleanType().optional().default(false)
  10799. }).strict();
  10800. pushParams = objectType({
  10801. dialect: dialect4,
  10802. casing: casingType.optional(),
  10803. schema: unionType([stringType(), stringType().array()]),
  10804. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  10805. schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
  10806. extensionsFilters: literalType("postgis").array().optional(),
  10807. verbose: booleanType().optional(),
  10808. strict: booleanType().optional(),
  10809. entities: objectType({
  10810. roles: booleanType().or(objectType({
  10811. provider: stringType().optional(),
  10812. include: stringType().array().optional(),
  10813. exclude: stringType().array().optional()
  10814. })).optional().default(false)
  10815. }).optional()
  10816. }).passthrough();
  10817. pullParams = objectType({
  10818. config: stringType().optional(),
  10819. dialect: dialect4,
  10820. out: stringType().optional().default("drizzle"),
  10821. tablesFilter: unionType([stringType(), stringType().array()]).optional(),
  10822. schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
  10823. extensionsFilters: literalType("postgis").array().optional(),
  10824. casing,
  10825. breakpoints: booleanType().optional().default(true),
  10826. migrations: objectType({
  10827. prefix: prefix.optional().default("index")
  10828. }).optional(),
  10829. entities: objectType({
  10830. roles: booleanType().or(objectType({
  10831. provider: stringType().optional(),
  10832. include: stringType().array().optional(),
  10833. exclude: stringType().array().optional()
  10834. })).optional().default(false)
  10835. }).optional()
  10836. }).passthrough();
  10837. configCheck = objectType({
  10838. dialect: dialect4.optional(),
  10839. out: stringType().optional()
  10840. });
  10841. cliConfigCheck = intersectionType(
  10842. objectType({
  10843. config: stringType().optional()
  10844. }),
  10845. configCheck
  10846. );
  10847. }
  10848. });
  10849. // src/cli/validations/gel.ts
  10850. var gelCredentials, printConfigConnectionIssues;
  10851. var init_gel = __esm({
  10852. "src/cli/validations/gel.ts"() {
  10853. "use strict";
  10854. init_esm();
  10855. init_views();
  10856. init_common();
  10857. gelCredentials = unionType([
  10858. objectType({
  10859. driver: undefinedType(),
  10860. host: stringType().min(1),
  10861. port: coerce.number().min(1).optional(),
  10862. user: stringType().min(1).optional(),
  10863. password: stringType().min(1).optional(),
  10864. database: stringType().min(1),
  10865. tlsSecurity: unionType([
  10866. literalType("insecure"),
  10867. literalType("no_host_verification"),
  10868. literalType("strict"),
  10869. literalType("default")
  10870. ]).optional()
  10871. }).transform((o3) => {
  10872. delete o3.driver;
  10873. return o3;
  10874. }),
  10875. objectType({
  10876. driver: undefinedType(),
  10877. url: stringType().min(1),
  10878. tlsSecurity: unionType([
  10879. literalType("insecure"),
  10880. literalType("no_host_verification"),
  10881. literalType("strict"),
  10882. literalType("default")
  10883. ]).optional()
  10884. }).transform((o3) => {
  10885. delete o3.driver;
  10886. return o3;
  10887. }),
  10888. objectType({
  10889. driver: undefinedType()
  10890. }).transform((o3) => {
  10891. return void 0;
  10892. })
  10893. ]);
  10894. printConfigConnectionIssues = (options) => {
  10895. if ("url" in options) {
  10896. let text = `Please provide required params for Gel driver:
  10897. `;
  10898. console.log(error(text));
  10899. console.log(wrapParam("url", options.url, false, "url"));
  10900. process.exit(1);
  10901. }
  10902. if ("host" in options || "database" in options) {
  10903. let text = `Please provide required params for Gel driver:
  10904. `;
  10905. console.log(error(text));
  10906. console.log(wrapParam("host", options.host));
  10907. console.log(wrapParam("port", options.port, true));
  10908. console.log(wrapParam("user", options.user, true));
  10909. console.log(wrapParam("password", options.password, true, "secret"));
  10910. console.log(wrapParam("database", options.database));
  10911. console.log(wrapParam("tlsSecurity", options.tlsSecurity, true));
  10912. process.exit(1);
  10913. }
  10914. console.log(
  10915. error(
  10916. `Either connection "url" or "host", "database" are required for Gel database connection`
  10917. )
  10918. );
  10919. process.exit(1);
  10920. };
  10921. }
  10922. });
  10923. // src/cli/validations/libsql.ts
  10924. var libSQLCredentials, printConfigConnectionIssues2;
  10925. var init_libsql = __esm({
  10926. "src/cli/validations/libsql.ts"() {
  10927. "use strict";
  10928. init_esm();
  10929. init_views();
  10930. init_common();
  10931. libSQLCredentials = objectType({
  10932. url: stringType().min(1),
  10933. authToken: stringType().min(1).optional()
  10934. });
  10935. printConfigConnectionIssues2 = (options, command) => {
  10936. let text = `Please provide required params for 'turso' dialect:
  10937. `;
  10938. console.log(error(text));
  10939. console.log(wrapParam("url", options.url));
  10940. console.log(wrapParam("authToken", options.authToken, true, "secret"));
  10941. process.exit(1);
  10942. };
  10943. }
  10944. });
  10945. // src/cli/validations/mysql.ts
  10946. var mysqlCredentials, printConfigConnectionIssues3;
  10947. var init_mysql = __esm({
  10948. "src/cli/validations/mysql.ts"() {
  10949. "use strict";
  10950. init_esm();
  10951. init_views();
  10952. init_common();
  10953. init_outputs();
  10954. mysqlCredentials = unionType([
  10955. objectType({
  10956. host: stringType().min(1),
  10957. port: coerce.number().min(1).optional(),
  10958. user: stringType().min(1).optional(),
  10959. password: stringType().min(1).optional(),
  10960. database: stringType().min(1),
  10961. ssl: unionType([
  10962. stringType(),
  10963. objectType({
  10964. pfx: stringType().optional(),
  10965. key: stringType().optional(),
  10966. passphrase: stringType().optional(),
  10967. cert: stringType().optional(),
  10968. ca: unionType([stringType(), stringType().array()]).optional(),
  10969. crl: unionType([stringType(), stringType().array()]).optional(),
  10970. ciphers: stringType().optional(),
  10971. rejectUnauthorized: booleanType().optional()
  10972. })
  10973. ]).optional()
  10974. }),
  10975. objectType({
  10976. url: stringType().min(1)
  10977. })
  10978. ]);
  10979. printConfigConnectionIssues3 = (options) => {
  10980. if ("url" in options) {
  10981. let text2 = `Please provide required params for MySQL driver:
  10982. `;
  10983. console.log(error(text2));
  10984. console.log(wrapParam("url", options.url, false, "url"));
  10985. process.exit(1);
  10986. }
  10987. let text = `Please provide required params for MySQL driver:
  10988. `;
  10989. console.log(error(text));
  10990. console.log(wrapParam("host", options.host));
  10991. console.log(wrapParam("port", options.port, true));
  10992. console.log(wrapParam("user", options.user, true));
  10993. console.log(wrapParam("password", options.password, true, "secret"));
  10994. console.log(wrapParam("database", options.database));
  10995. console.log(wrapParam("ssl", options.ssl, true));
  10996. process.exit(1);
  10997. };
  10998. }
  10999. });
  11000. // src/cli/validations/postgres.ts
  11001. var postgresCredentials, printConfigConnectionIssues4;
  11002. var init_postgres = __esm({
  11003. "src/cli/validations/postgres.ts"() {
  11004. "use strict";
  11005. init_esm();
  11006. init_views();
  11007. init_common();
  11008. postgresCredentials = unionType([
  11009. objectType({
  11010. driver: undefinedType(),
  11011. host: stringType().min(1),
  11012. port: coerce.number().min(1).optional(),
  11013. user: stringType().min(1).optional(),
  11014. password: stringType().min(1).optional(),
  11015. database: stringType().min(1),
  11016. ssl: unionType([
  11017. literalType("require"),
  11018. literalType("allow"),
  11019. literalType("prefer"),
  11020. literalType("verify-full"),
  11021. booleanType(),
  11022. objectType({}).passthrough()
  11023. ]).optional()
  11024. }).transform((o3) => {
  11025. delete o3.driver;
  11026. return o3;
  11027. }),
  11028. objectType({
  11029. driver: undefinedType(),
  11030. url: stringType().min(1)
  11031. }).transform((o3) => {
  11032. delete o3.driver;
  11033. return o3;
  11034. }),
  11035. objectType({
  11036. driver: literalType("aws-data-api"),
  11037. database: stringType().min(1),
  11038. secretArn: stringType().min(1),
  11039. resourceArn: stringType().min(1)
  11040. }),
  11041. objectType({
  11042. driver: literalType("pglite"),
  11043. url: stringType().min(1)
  11044. })
  11045. ]);
  11046. printConfigConnectionIssues4 = (options) => {
  11047. if (options.driver === "aws-data-api") {
  11048. let text = `Please provide required params for AWS Data API driver:
  11049. `;
  11050. console.log(error(text));
  11051. console.log(wrapParam("database", options.database));
  11052. console.log(wrapParam("secretArn", options.secretArn, false, "secret"));
  11053. console.log(wrapParam("resourceArn", options.resourceArn, false, "secret"));
  11054. process.exit(1);
  11055. }
  11056. if ("url" in options) {
  11057. let text = `Please provide required params for Postgres driver:
  11058. `;
  11059. console.log(error(text));
  11060. console.log(wrapParam("url", options.url, false, "url"));
  11061. process.exit(1);
  11062. }
  11063. if ("host" in options || "database" in options) {
  11064. let text = `Please provide required params for Postgres driver:
  11065. `;
  11066. console.log(error(text));
  11067. console.log(wrapParam("host", options.host));
  11068. console.log(wrapParam("port", options.port, true));
  11069. console.log(wrapParam("user", options.user, true));
  11070. console.log(wrapParam("password", options.password, true, "secret"));
  11071. console.log(wrapParam("database", options.database));
  11072. console.log(wrapParam("ssl", options.ssl, true));
  11073. process.exit(1);
  11074. }
  11075. console.log(
  11076. error(
  11077. `Either connection "url" or "host", "database" are required for PostgreSQL database connection`
  11078. )
  11079. );
  11080. process.exit(1);
  11081. };
  11082. }
  11083. });
  11084. // src/cli/validations/singlestore.ts
  11085. var singlestoreCredentials, printConfigConnectionIssues5;
  11086. var init_singlestore = __esm({
  11087. "src/cli/validations/singlestore.ts"() {
  11088. "use strict";
  11089. init_esm();
  11090. init_views();
  11091. init_common();
  11092. init_outputs();
  11093. singlestoreCredentials = unionType([
  11094. objectType({
  11095. host: stringType().min(1),
  11096. port: coerce.number().min(1).optional(),
  11097. user: stringType().min(1).optional(),
  11098. password: stringType().min(1).optional(),
  11099. database: stringType().min(1),
  11100. ssl: unionType([
  11101. stringType(),
  11102. objectType({
  11103. pfx: stringType().optional(),
  11104. key: stringType().optional(),
  11105. passphrase: stringType().optional(),
  11106. cert: stringType().optional(),
  11107. ca: unionType([stringType(), stringType().array()]).optional(),
  11108. crl: unionType([stringType(), stringType().array()]).optional(),
  11109. ciphers: stringType().optional(),
  11110. rejectUnauthorized: booleanType().optional()
  11111. })
  11112. ]).optional()
  11113. }),
  11114. objectType({
  11115. url: stringType().min(1)
  11116. })
  11117. ]);
  11118. printConfigConnectionIssues5 = (options) => {
  11119. if ("url" in options) {
  11120. let text2 = `Please provide required params for SingleStore driver:
  11121. `;
  11122. console.log(error(text2));
  11123. console.log(wrapParam("url", options.url, false, "url"));
  11124. process.exit(1);
  11125. }
  11126. let text = `Please provide required params for SingleStore driver:
  11127. `;
  11128. console.log(error(text));
  11129. console.log(wrapParam("host", options.host));
  11130. console.log(wrapParam("port", options.port, true));
  11131. console.log(wrapParam("user", options.user, true));
  11132. console.log(wrapParam("password", options.password, true, "secret"));
  11133. console.log(wrapParam("database", options.database));
  11134. console.log(wrapParam("ssl", options.ssl, true));
  11135. process.exit(1);
  11136. };
  11137. }
  11138. });
  11139. // src/cli/validations/sqlite.ts
  11140. var sqliteCredentials, printConfigConnectionIssues6;
  11141. var init_sqlite = __esm({
  11142. "src/cli/validations/sqlite.ts"() {
  11143. "use strict";
  11144. init_global();
  11145. init_esm();
  11146. init_views();
  11147. init_common();
  11148. sqliteCredentials = unionType([
  11149. objectType({
  11150. driver: literalType("turso"),
  11151. url: stringType().min(1),
  11152. authToken: stringType().min(1).optional()
  11153. }),
  11154. objectType({
  11155. driver: literalType("d1-http"),
  11156. accountId: stringType().min(1),
  11157. databaseId: stringType().min(1),
  11158. token: stringType().min(1)
  11159. }),
  11160. objectType({
  11161. driver: undefinedType(),
  11162. url: stringType().min(1)
  11163. }).transform((o3) => {
  11164. delete o3.driver;
  11165. return o3;
  11166. })
  11167. ]);
  11168. printConfigConnectionIssues6 = (options, command) => {
  11169. const parsedDriver = sqliteDriver.safeParse(options.driver);
  11170. const driver2 = parsedDriver.success ? parsedDriver.data : "";
  11171. if (driver2 === "expo") {
  11172. if (command === "migrate") {
  11173. console.log(
  11174. error(
  11175. `You can't use 'migrate' command with Expo SQLite, please follow migration instructions in our docs - https://orm.drizzle.team/docs/get-started-sqlite#expo-sqlite`
  11176. )
  11177. );
  11178. } else if (command === "studio") {
  11179. console.log(
  11180. error(
  11181. `You can't use 'studio' command with Expo SQLite, please use Expo Plugin https://www.npmjs.com/package/expo-drizzle-studio-plugin`
  11182. )
  11183. );
  11184. } else if (command === "pull") {
  11185. console.log(error("You can't use 'pull' command with Expo SQLite"));
  11186. } else if (command === "push") {
  11187. console.log(error("You can't use 'push' command with Expo SQLite"));
  11188. } else {
  11189. console.log(error("Unexpected error with expo driver \u{1F914}"));
  11190. }
  11191. process.exit(1);
  11192. } else if (driver2 === "d1-http") {
  11193. let text2 = `Please provide required params for D1 HTTP driver:
  11194. `;
  11195. console.log(error(text2));
  11196. console.log(wrapParam("accountId", options.accountId));
  11197. console.log(wrapParam("databaseId", options.databaseId));
  11198. console.log(wrapParam("token", options.token, false, "secret"));
  11199. process.exit(1);
  11200. } else if (driver2 === "durable-sqlite") {
  11201. if (command === "migrate") {
  11202. console.log(
  11203. error(
  11204. `You can't use 'migrate' command with SQLite Durable Objects`
  11205. )
  11206. );
  11207. } else if (command === "studio") {
  11208. console.log(
  11209. error(
  11210. `You can't use 'studio' command with SQLite Durable Objects`
  11211. )
  11212. );
  11213. } else if (command === "pull") {
  11214. console.log(error("You can't use 'pull' command with SQLite Durable Objects"));
  11215. } else if (command === "push") {
  11216. console.log(error("You can't use 'push' command with SQLite Durable Objects"));
  11217. } else {
  11218. console.log(error("Unexpected error with SQLite Durable Object driver \u{1F914}"));
  11219. }
  11220. process.exit(1);
  11221. } else {
  11222. softAssertUnreachable(driver2);
  11223. }
  11224. let text = `Please provide required params:
  11225. `;
  11226. console.log(error(text));
  11227. console.log(wrapParam("url", options.url));
  11228. process.exit(1);
  11229. };
  11230. }
  11231. });
  11232. // src/cli/validations/studio.ts
  11233. var credentials, studioCliParams, studioConfig;
  11234. var init_studio = __esm({
  11235. "src/cli/validations/studio.ts"() {
  11236. "use strict";
  11237. init_esm();
  11238. init_schemaValidator();
  11239. init_common();
  11240. init_mysql();
  11241. init_postgres();
  11242. init_sqlite();
  11243. credentials = intersectionType(
  11244. postgresCredentials,
  11245. mysqlCredentials,
  11246. sqliteCredentials
  11247. );
  11248. studioCliParams = objectType({
  11249. port: coerce.number().optional().default(4983),
  11250. host: stringType().optional().default("127.0.0.1"),
  11251. config: stringType().optional()
  11252. });
  11253. studioConfig = objectType({
  11254. dialect: dialect4,
  11255. schema: unionType([stringType(), stringType().array()]).optional(),
  11256. casing: casingType.optional()
  11257. });
  11258. }
  11259. });
  11260. // src/cli/commands/_es5.ts
  11261. var es5_exports = {};
  11262. __export(es5_exports, {
  11263. default: () => es5_default
  11264. });
  11265. var _, es5_default;
  11266. var init_es5 = __esm({
  11267. "src/cli/commands/_es5.ts"() {
  11268. "use strict";
  11269. _ = "";
  11270. es5_default = _;
  11271. }
  11272. });
  11273. // ../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/temporary-directory-B83uKxJF.cjs
  11274. var require_temporary_directory_B83uKxJF = __commonJS({
  11275. "../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/temporary-directory-B83uKxJF.cjs"(exports2) {
  11276. "use strict";
  11277. var s4 = require("node:path");
  11278. var r4 = require("node:os");
  11279. var { geteuid: e4 } = process;
  11280. var t4 = e4 ? e4() : r4.userInfo().username;
  11281. var i4 = s4.join(r4.tmpdir(), `tsx-${t4}`);
  11282. exports2.tmpdir = i4;
  11283. }
  11284. });
  11285. // ../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/get-pipe-path-BoR10qr8.cjs
  11286. var require_get_pipe_path_BoR10qr8 = __commonJS({
  11287. "../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/get-pipe-path-BoR10qr8.cjs"(exports2) {
  11288. "use strict";
  11289. var u3 = Object.defineProperty;
  11290. var t4 = (r4, e4) => u3(r4, "name", { value: e4, configurable: true });
  11291. var d3 = require("module");
  11292. var n3 = require("node:path");
  11293. var p3 = require_temporary_directory_B83uKxJF();
  11294. var s4 = typeof document < "u" ? document.currentScript : null;
  11295. var o3 = require;
  11296. var i4 = process.platform === "win32";
  11297. var c3 = t4((r4) => {
  11298. const e4 = n3.join(p3.tmpdir, `${r4}.pipe`);
  11299. return i4 ? `\\\\?\\pipe\\${e4}` : e4;
  11300. }, "getPipePath");
  11301. exports2.getPipePath = c3, exports2.isWindows = i4, exports2.require = o3;
  11302. }
  11303. });
  11304. // ../node_modules/.pnpm/resolve-pkg-maps@1.0.0/node_modules/resolve-pkg-maps/dist/index.cjs
  11305. var require_dist = __commonJS({
  11306. "../node_modules/.pnpm/resolve-pkg-maps@1.0.0/node_modules/resolve-pkg-maps/dist/index.cjs"(exports2) {
  11307. "use strict";
  11308. Object.defineProperty(exports2, "__esModule", { value: true });
  11309. var d3 = (r4) => r4 !== null && typeof r4 == "object";
  11310. var s4 = (r4, t4) => Object.assign(new Error(`[${r4}]: ${t4}`), { code: r4 });
  11311. var g3 = "ERR_INVALID_PACKAGE_CONFIG";
  11312. var E2 = "ERR_INVALID_PACKAGE_TARGET";
  11313. var I2 = "ERR_PACKAGE_PATH_NOT_EXPORTED";
  11314. var P = "ERR_PACKAGE_IMPORT_NOT_DEFINED";
  11315. var R = /^\d+$/;
  11316. var O = /^(\.{1,2}|node_modules)$/i;
  11317. var u3 = /\/|\\/;
  11318. var h4 = ((r4) => (r4.Export = "exports", r4.Import = "imports", r4))(h4 || {});
  11319. var f5 = (r4, t4, n3, o3, c3) => {
  11320. if (t4 == null) return [];
  11321. if (typeof t4 == "string") {
  11322. const [e4, ...i4] = t4.split(u3);
  11323. if (e4 === ".." || i4.some((l3) => O.test(l3))) throw s4(E2, `Invalid "${r4}" target "${t4}" defined in the package config`);
  11324. return [c3 ? t4.replace(/\*/g, c3) : t4];
  11325. }
  11326. if (Array.isArray(t4)) return t4.flatMap((e4) => f5(r4, e4, n3, o3, c3));
  11327. if (d3(t4)) {
  11328. for (const e4 of Object.keys(t4)) {
  11329. if (R.test(e4)) throw s4(g3, "Cannot contain numeric property keys");
  11330. if (e4 === "default" || o3.includes(e4)) return f5(r4, t4[e4], n3, o3, c3);
  11331. }
  11332. return [];
  11333. }
  11334. throw s4(E2, `Invalid "${r4}" target "${t4}"`);
  11335. };
  11336. var a3 = "*";
  11337. var v6 = (r4, t4) => {
  11338. const n3 = r4.indexOf(a3), o3 = t4.indexOf(a3);
  11339. return n3 === o3 ? t4.length > r4.length : o3 > n3;
  11340. };
  11341. function A3(r4, t4) {
  11342. if (!t4.includes(a3) && r4.hasOwnProperty(t4)) return [t4];
  11343. let n3, o3;
  11344. for (const c3 of Object.keys(r4)) if (c3.includes(a3)) {
  11345. const [e4, i4, l3] = c3.split(a3);
  11346. if (l3 === void 0 && t4.startsWith(e4) && t4.endsWith(i4)) {
  11347. const _3 = t4.slice(e4.length, -i4.length || void 0);
  11348. _3 && (!n3 || v6(n3, c3)) && (n3 = c3, o3 = _3);
  11349. }
  11350. }
  11351. return [n3, o3];
  11352. }
  11353. var p3 = (r4) => Object.keys(r4).reduce((t4, n3) => {
  11354. const o3 = n3 === "" || n3[0] !== ".";
  11355. if (t4 === void 0 || t4 === o3) return o3;
  11356. throw s4(g3, '"exports" cannot contain some keys starting with "." and some not');
  11357. }, void 0);
  11358. var w3 = /^\w+:/;
  11359. var m4 = (r4, t4, n3) => {
  11360. if (!r4) throw new Error('"exports" is required');
  11361. t4 = t4 === "" ? "." : `./${t4}`, (typeof r4 == "string" || Array.isArray(r4) || d3(r4) && p3(r4)) && (r4 = { ".": r4 });
  11362. const [o3, c3] = A3(r4, t4), e4 = f5(h4.Export, r4[o3], t4, n3, c3);
  11363. if (e4.length === 0) throw s4(I2, t4 === "." ? 'No "exports" main defined' : `Package subpath '${t4}' is not defined by "exports"`);
  11364. for (const i4 of e4) if (!i4.startsWith("./") && !w3.test(i4)) throw s4(E2, `Invalid "exports" target "${i4}" defined in the package config`);
  11365. return e4;
  11366. };
  11367. var T = (r4, t4, n3) => {
  11368. if (!r4) throw new Error('"imports" is required');
  11369. const [o3, c3] = A3(r4, t4), e4 = f5(h4.Import, r4[o3], t4, n3, c3);
  11370. if (e4.length === 0) throw s4(P, `Package import specifier "${t4}" is not defined in package`);
  11371. return e4;
  11372. };
  11373. exports2.resolveExports = m4, exports2.resolveImports = T;
  11374. }
  11375. });
  11376. // ../node_modules/.pnpm/get-tsconfig@4.13.6/node_modules/get-tsconfig/dist/index.cjs
  11377. var require_dist2 = __commonJS({
  11378. "../node_modules/.pnpm/get-tsconfig@4.13.6/node_modules/get-tsconfig/dist/index.cjs"(exports2) {
  11379. "use strict";
  11380. var Le = Object.defineProperty;
  11381. var o3 = (e4, t4) => Le(e4, "name", { value: t4, configurable: true });
  11382. var w3 = require("node:path");
  11383. var re = require("node:fs");
  11384. var he = require("node:module");
  11385. var Ee = require_dist();
  11386. var Be = require("fs");
  11387. var xe = require("os");
  11388. var Ie = require("path");
  11389. function h4(e4) {
  11390. return e4.startsWith("\\\\?\\") ? e4 : e4.replace(/\\/g, "/");
  11391. }
  11392. o3(h4, "slash");
  11393. var Y = o3((e4) => {
  11394. const t4 = re[e4];
  11395. return (s4, ...n3) => {
  11396. const i4 = `${e4}:${n3.join(":")}`;
  11397. let l3 = s4 == null ? void 0 : s4.get(i4);
  11398. return l3 === void 0 && (l3 = Reflect.apply(t4, re, n3), s4 == null || s4.set(i4, l3)), l3;
  11399. };
  11400. }, "cacheFs");
  11401. var E2 = Y("existsSync");
  11402. var $e = Y("readFileSync");
  11403. var G2 = Y("statSync");
  11404. var fe = o3((e4, t4, s4) => {
  11405. for (; ; ) {
  11406. const n3 = w3.posix.join(e4, t4);
  11407. if (E2(s4, n3)) return n3;
  11408. const i4 = w3.dirname(e4);
  11409. if (i4 === e4) return;
  11410. e4 = i4;
  11411. }
  11412. }, "findUp");
  11413. var Z2 = /^\.{1,2}(\/.*)?$/;
  11414. var K = o3((e4) => {
  11415. const t4 = h4(e4);
  11416. return Z2.test(t4) ? t4 : `./${t4}`;
  11417. }, "normalizeRelativePath");
  11418. function Ue(e4, t4 = false) {
  11419. const s4 = e4.length;
  11420. let n3 = 0, i4 = "", l3 = 0, u3 = 16, a3 = 0, r4 = 0, g3 = 0, v6 = 0, d3 = 0;
  11421. function _3(c3, y2) {
  11422. let A3 = 0, b3 = 0;
  11423. for (; A3 < c3; ) {
  11424. let k3 = e4.charCodeAt(n3);
  11425. if (k3 >= 48 && k3 <= 57) b3 = b3 * 16 + k3 - 48;
  11426. else if (k3 >= 65 && k3 <= 70) b3 = b3 * 16 + k3 - 65 + 10;
  11427. else if (k3 >= 97 && k3 <= 102) b3 = b3 * 16 + k3 - 97 + 10;
  11428. else break;
  11429. n3++, A3++;
  11430. }
  11431. return A3 < c3 && (b3 = -1), b3;
  11432. }
  11433. o3(_3, "scanHexDigits");
  11434. function p3(c3) {
  11435. n3 = c3, i4 = "", l3 = 0, u3 = 16, d3 = 0;
  11436. }
  11437. o3(p3, "setPosition");
  11438. function D2() {
  11439. let c3 = n3;
  11440. if (e4.charCodeAt(n3) === 48) n3++;
  11441. else for (n3++; n3 < e4.length && P(e4.charCodeAt(n3)); ) n3++;
  11442. if (n3 < e4.length && e4.charCodeAt(n3) === 46) if (n3++, n3 < e4.length && P(e4.charCodeAt(n3))) for (n3++; n3 < e4.length && P(e4.charCodeAt(n3)); ) n3++;
  11443. else return d3 = 3, e4.substring(c3, n3);
  11444. let y2 = n3;
  11445. if (n3 < e4.length && (e4.charCodeAt(n3) === 69 || e4.charCodeAt(n3) === 101)) if (n3++, (n3 < e4.length && e4.charCodeAt(n3) === 43 || e4.charCodeAt(n3) === 45) && n3++, n3 < e4.length && P(e4.charCodeAt(n3))) {
  11446. for (n3++; n3 < e4.length && P(e4.charCodeAt(n3)); ) n3++;
  11447. y2 = n3;
  11448. } else d3 = 3;
  11449. return e4.substring(c3, y2);
  11450. }
  11451. o3(D2, "scanNumber");
  11452. function L() {
  11453. let c3 = "", y2 = n3;
  11454. for (; ; ) {
  11455. if (n3 >= s4) {
  11456. c3 += e4.substring(y2, n3), d3 = 2;
  11457. break;
  11458. }
  11459. const A3 = e4.charCodeAt(n3);
  11460. if (A3 === 34) {
  11461. c3 += e4.substring(y2, n3), n3++;
  11462. break;
  11463. }
  11464. if (A3 === 92) {
  11465. if (c3 += e4.substring(y2, n3), n3++, n3 >= s4) {
  11466. d3 = 2;
  11467. break;
  11468. }
  11469. switch (e4.charCodeAt(n3++)) {
  11470. case 34:
  11471. c3 += '"';
  11472. break;
  11473. case 92:
  11474. c3 += "\\";
  11475. break;
  11476. case 47:
  11477. c3 += "/";
  11478. break;
  11479. case 98:
  11480. c3 += "\b";
  11481. break;
  11482. case 102:
  11483. c3 += "\f";
  11484. break;
  11485. case 110:
  11486. c3 += `
  11487. `;
  11488. break;
  11489. case 114:
  11490. c3 += "\r";
  11491. break;
  11492. case 116:
  11493. c3 += " ";
  11494. break;
  11495. case 117:
  11496. const k3 = _3(4);
  11497. k3 >= 0 ? c3 += String.fromCharCode(k3) : d3 = 4;
  11498. break;
  11499. default:
  11500. d3 = 5;
  11501. }
  11502. y2 = n3;
  11503. continue;
  11504. }
  11505. if (A3 >= 0 && A3 <= 31) if (M(A3)) {
  11506. c3 += e4.substring(y2, n3), d3 = 2;
  11507. break;
  11508. } else d3 = 6;
  11509. n3++;
  11510. }
  11511. return c3;
  11512. }
  11513. o3(L, "scanString");
  11514. function T() {
  11515. if (i4 = "", d3 = 0, l3 = n3, r4 = a3, v6 = g3, n3 >= s4) return l3 = s4, u3 = 17;
  11516. let c3 = e4.charCodeAt(n3);
  11517. if (O(c3)) {
  11518. do
  11519. n3++, i4 += String.fromCharCode(c3), c3 = e4.charCodeAt(n3);
  11520. while (O(c3));
  11521. return u3 = 15;
  11522. }
  11523. if (M(c3)) return n3++, i4 += String.fromCharCode(c3), c3 === 13 && e4.charCodeAt(n3) === 10 && (n3++, i4 += `
  11524. `), a3++, g3 = n3, u3 = 14;
  11525. switch (c3) {
  11526. case 123:
  11527. return n3++, u3 = 1;
  11528. case 125:
  11529. return n3++, u3 = 2;
  11530. case 91:
  11531. return n3++, u3 = 3;
  11532. case 93:
  11533. return n3++, u3 = 4;
  11534. case 58:
  11535. return n3++, u3 = 6;
  11536. case 44:
  11537. return n3++, u3 = 5;
  11538. case 34:
  11539. return n3++, i4 = L(), u3 = 10;
  11540. case 47:
  11541. const y2 = n3 - 1;
  11542. if (e4.charCodeAt(n3 + 1) === 47) {
  11543. for (n3 += 2; n3 < s4 && !M(e4.charCodeAt(n3)); ) n3++;
  11544. return i4 = e4.substring(y2, n3), u3 = 12;
  11545. }
  11546. if (e4.charCodeAt(n3 + 1) === 42) {
  11547. n3 += 2;
  11548. const A3 = s4 - 1;
  11549. let b3 = false;
  11550. for (; n3 < A3; ) {
  11551. const k3 = e4.charCodeAt(n3);
  11552. if (k3 === 42 && e4.charCodeAt(n3 + 1) === 47) {
  11553. n3 += 2, b3 = true;
  11554. break;
  11555. }
  11556. n3++, M(k3) && (k3 === 13 && e4.charCodeAt(n3) === 10 && n3++, a3++, g3 = n3);
  11557. }
  11558. return b3 || (n3++, d3 = 1), i4 = e4.substring(y2, n3), u3 = 13;
  11559. }
  11560. return i4 += String.fromCharCode(c3), n3++, u3 = 16;
  11561. case 45:
  11562. if (i4 += String.fromCharCode(c3), n3++, n3 === s4 || !P(e4.charCodeAt(n3))) return u3 = 16;
  11563. case 48:
  11564. case 49:
  11565. case 50:
  11566. case 51:
  11567. case 52:
  11568. case 53:
  11569. case 54:
  11570. case 55:
  11571. case 56:
  11572. case 57:
  11573. return i4 += D2(), u3 = 11;
  11574. default:
  11575. for (; n3 < s4 && F3(c3); ) n3++, c3 = e4.charCodeAt(n3);
  11576. if (l3 !== n3) {
  11577. switch (i4 = e4.substring(l3, n3), i4) {
  11578. case "true":
  11579. return u3 = 8;
  11580. case "false":
  11581. return u3 = 9;
  11582. case "null":
  11583. return u3 = 7;
  11584. }
  11585. return u3 = 16;
  11586. }
  11587. return i4 += String.fromCharCode(c3), n3++, u3 = 16;
  11588. }
  11589. }
  11590. o3(T, "scanNext");
  11591. function F3(c3) {
  11592. if (O(c3) || M(c3)) return false;
  11593. switch (c3) {
  11594. case 125:
  11595. case 93:
  11596. case 123:
  11597. case 91:
  11598. case 34:
  11599. case 58:
  11600. case 44:
  11601. case 47:
  11602. return false;
  11603. }
  11604. return true;
  11605. }
  11606. o3(F3, "isUnknownContentCharacter");
  11607. function B2() {
  11608. let c3;
  11609. do
  11610. c3 = T();
  11611. while (c3 >= 12 && c3 <= 15);
  11612. return c3;
  11613. }
  11614. return o3(B2, "scanNextNonTrivia"), { setPosition: p3, getPosition: o3(() => n3, "getPosition"), scan: t4 ? B2 : T, getToken: o3(() => u3, "getToken"), getTokenValue: o3(() => i4, "getTokenValue"), getTokenOffset: o3(() => l3, "getTokenOffset"), getTokenLength: o3(() => n3 - l3, "getTokenLength"), getTokenStartLine: o3(() => r4, "getTokenStartLine"), getTokenStartCharacter: o3(() => l3 - v6, "getTokenStartCharacter"), getTokenError: o3(() => d3, "getTokenError") };
  11615. }
  11616. o3(Ue, "createScanner");
  11617. function O(e4) {
  11618. return e4 === 32 || e4 === 9;
  11619. }
  11620. o3(O, "isWhiteSpace");
  11621. function M(e4) {
  11622. return e4 === 10 || e4 === 13;
  11623. }
  11624. o3(M, "isLineBreak");
  11625. function P(e4) {
  11626. return e4 >= 48 && e4 <= 57;
  11627. }
  11628. o3(P, "isDigit");
  11629. var ae;
  11630. (function(e4) {
  11631. e4[e4.lineFeed = 10] = "lineFeed", e4[e4.carriageReturn = 13] = "carriageReturn", e4[e4.space = 32] = "space", e4[e4._0 = 48] = "_0", e4[e4._1 = 49] = "_1", e4[e4._2 = 50] = "_2", e4[e4._3 = 51] = "_3", e4[e4._4 = 52] = "_4", e4[e4._5 = 53] = "_5", e4[e4._6 = 54] = "_6", e4[e4._7 = 55] = "_7", e4[e4._8 = 56] = "_8", e4[e4._9 = 57] = "_9", e4[e4.a = 97] = "a", e4[e4.b = 98] = "b", e4[e4.c = 99] = "c", e4[e4.d = 100] = "d", e4[e4.e = 101] = "e", e4[e4.f = 102] = "f", e4[e4.g = 103] = "g", e4[e4.h = 104] = "h", e4[e4.i = 105] = "i", e4[e4.j = 106] = "j", e4[e4.k = 107] = "k", e4[e4.l = 108] = "l", e4[e4.m = 109] = "m", e4[e4.n = 110] = "n", e4[e4.o = 111] = "o", e4[e4.p = 112] = "p", e4[e4.q = 113] = "q", e4[e4.r = 114] = "r", e4[e4.s = 115] = "s", e4[e4.t = 116] = "t", e4[e4.u = 117] = "u", e4[e4.v = 118] = "v", e4[e4.w = 119] = "w", e4[e4.x = 120] = "x", e4[e4.y = 121] = "y", e4[e4.z = 122] = "z", e4[e4.A = 65] = "A", e4[e4.B = 66] = "B", e4[e4.C = 67] = "C", e4[e4.D = 68] = "D", e4[e4.E = 69] = "E", e4[e4.F = 70] = "F", e4[e4.G = 71] = "G", e4[e4.H = 72] = "H", e4[e4.I = 73] = "I", e4[e4.J = 74] = "J", e4[e4.K = 75] = "K", e4[e4.L = 76] = "L", e4[e4.M = 77] = "M", e4[e4.N = 78] = "N", e4[e4.O = 79] = "O", e4[e4.P = 80] = "P", e4[e4.Q = 81] = "Q", e4[e4.R = 82] = "R", e4[e4.S = 83] = "S", e4[e4.T = 84] = "T", e4[e4.U = 85] = "U", e4[e4.V = 86] = "V", e4[e4.W = 87] = "W", e4[e4.X = 88] = "X", e4[e4.Y = 89] = "Y", e4[e4.Z = 90] = "Z", e4[e4.asterisk = 42] = "asterisk", e4[e4.backslash = 92] = "backslash", e4[e4.closeBrace = 125] = "closeBrace", e4[e4.closeBracket = 93] = "closeBracket", e4[e4.colon = 58] = "colon", e4[e4.comma = 44] = "comma", e4[e4.dot = 46] = "dot", e4[e4.doubleQuote = 34] = "doubleQuote", e4[e4.minus = 45] = "minus", e4[e4.openBrace = 123] = "openBrace", e4[e4.openBracket = 91] = "openBracket", e4[e4.plus = 43] = "plus", e4[e4.slash = 47] = "slash", e4[e4.formFeed = 12] = "formFeed", e4[e4.tab = 9] = "tab";
  11632. })(ae || (ae = {})), new Array(20).fill(0).map((e4, t4) => " ".repeat(t4));
  11633. var N = 200;
  11634. new Array(N).fill(0).map((e4, t4) => `
  11635. ` + " ".repeat(t4)), new Array(N).fill(0).map((e4, t4) => "\r" + " ".repeat(t4)), new Array(N).fill(0).map((e4, t4) => `\r
  11636. ` + " ".repeat(t4)), new Array(N).fill(0).map((e4, t4) => `
  11637. ` + " ".repeat(t4)), new Array(N).fill(0).map((e4, t4) => "\r" + " ".repeat(t4)), new Array(N).fill(0).map((e4, t4) => `\r
  11638. ` + " ".repeat(t4));
  11639. var q3;
  11640. (function(e4) {
  11641. e4.DEFAULT = { allowTrailingComma: false };
  11642. })(q3 || (q3 = {}));
  11643. function Pe(e4, t4 = [], s4 = q3.DEFAULT) {
  11644. let n3 = null, i4 = [];
  11645. const l3 = [];
  11646. function u3(r4) {
  11647. Array.isArray(i4) ? i4.push(r4) : n3 !== null && (i4[n3] = r4);
  11648. }
  11649. return o3(u3, "onValue"), Ne(e4, { onObjectBegin: o3(() => {
  11650. const r4 = {};
  11651. u3(r4), l3.push(i4), i4 = r4, n3 = null;
  11652. }, "onObjectBegin"), onObjectProperty: o3((r4) => {
  11653. n3 = r4;
  11654. }, "onObjectProperty"), onObjectEnd: o3(() => {
  11655. i4 = l3.pop();
  11656. }, "onObjectEnd"), onArrayBegin: o3(() => {
  11657. const r4 = [];
  11658. u3(r4), l3.push(i4), i4 = r4, n3 = null;
  11659. }, "onArrayBegin"), onArrayEnd: o3(() => {
  11660. i4 = l3.pop();
  11661. }, "onArrayEnd"), onLiteralValue: u3, onError: o3((r4, g3, v6) => {
  11662. t4.push({ error: r4, offset: g3, length: v6 });
  11663. }, "onError") }, s4), i4[0];
  11664. }
  11665. o3(Pe, "parse$1");
  11666. function Ne(e4, t4, s4 = q3.DEFAULT) {
  11667. const n3 = Ue(e4, false), i4 = [];
  11668. let l3 = 0;
  11669. function u3(m4) {
  11670. return m4 ? () => l3 === 0 && m4(n3.getTokenOffset(), n3.getTokenLength(), n3.getTokenStartLine(), n3.getTokenStartCharacter()) : () => true;
  11671. }
  11672. o3(u3, "toNoArgVisit");
  11673. function a3(m4) {
  11674. return m4 ? (j3) => l3 === 0 && m4(j3, n3.getTokenOffset(), n3.getTokenLength(), n3.getTokenStartLine(), n3.getTokenStartCharacter()) : () => true;
  11675. }
  11676. o3(a3, "toOneArgVisit");
  11677. function r4(m4) {
  11678. return m4 ? (j3) => l3 === 0 && m4(j3, n3.getTokenOffset(), n3.getTokenLength(), n3.getTokenStartLine(), n3.getTokenStartCharacter(), () => i4.slice()) : () => true;
  11679. }
  11680. o3(r4, "toOneArgVisitWithPath");
  11681. function g3(m4) {
  11682. return m4 ? () => {
  11683. l3 > 0 ? l3++ : m4(n3.getTokenOffset(), n3.getTokenLength(), n3.getTokenStartLine(), n3.getTokenStartCharacter(), () => i4.slice()) === false && (l3 = 1);
  11684. } : () => true;
  11685. }
  11686. o3(g3, "toBeginVisit");
  11687. function v6(m4) {
  11688. return m4 ? () => {
  11689. l3 > 0 && l3--, l3 === 0 && m4(n3.getTokenOffset(), n3.getTokenLength(), n3.getTokenStartLine(), n3.getTokenStartCharacter());
  11690. } : () => true;
  11691. }
  11692. o3(v6, "toEndVisit");
  11693. const d3 = g3(t4.onObjectBegin), _3 = r4(t4.onObjectProperty), p3 = v6(t4.onObjectEnd), D2 = g3(t4.onArrayBegin), L = v6(t4.onArrayEnd), T = r4(t4.onLiteralValue), F3 = a3(t4.onSeparator), B2 = u3(t4.onComment), c3 = a3(t4.onError), y2 = s4 && s4.disallowComments, A3 = s4 && s4.allowTrailingComma;
  11694. function b3() {
  11695. for (; ; ) {
  11696. const m4 = n3.scan();
  11697. switch (n3.getTokenError()) {
  11698. case 4:
  11699. k3(14);
  11700. break;
  11701. case 5:
  11702. k3(15);
  11703. break;
  11704. case 3:
  11705. k3(13);
  11706. break;
  11707. case 1:
  11708. y2 || k3(11);
  11709. break;
  11710. case 2:
  11711. k3(12);
  11712. break;
  11713. case 6:
  11714. k3(16);
  11715. break;
  11716. }
  11717. switch (m4) {
  11718. case 12:
  11719. case 13:
  11720. y2 ? k3(10) : B2();
  11721. break;
  11722. case 16:
  11723. k3(1);
  11724. break;
  11725. case 15:
  11726. case 14:
  11727. break;
  11728. default:
  11729. return m4;
  11730. }
  11731. }
  11732. }
  11733. o3(b3, "scanNext");
  11734. function k3(m4, j3 = [], S2 = []) {
  11735. if (c3(m4), j3.length + S2.length > 0) {
  11736. let $ = n3.getToken();
  11737. for (; $ !== 17; ) {
  11738. if (j3.indexOf($) !== -1) {
  11739. b3();
  11740. break;
  11741. } else if (S2.indexOf($) !== -1) break;
  11742. $ = b3();
  11743. }
  11744. }
  11745. }
  11746. o3(k3, "handleError");
  11747. function R(m4) {
  11748. const j3 = n3.getTokenValue();
  11749. return m4 ? T(j3) : (_3(j3), i4.push(j3)), b3(), true;
  11750. }
  11751. o3(R, "parseString");
  11752. function J2() {
  11753. switch (n3.getToken()) {
  11754. case 11:
  11755. const m4 = n3.getTokenValue();
  11756. let j3 = Number(m4);
  11757. isNaN(j3) && (k3(2), j3 = 0), T(j3);
  11758. break;
  11759. case 7:
  11760. T(null);
  11761. break;
  11762. case 8:
  11763. T(true);
  11764. break;
  11765. case 9:
  11766. T(false);
  11767. break;
  11768. default:
  11769. return false;
  11770. }
  11771. return b3(), true;
  11772. }
  11773. o3(J2, "parseLiteral");
  11774. function W() {
  11775. return n3.getToken() !== 10 ? (k3(3, [], [2, 5]), false) : (R(false), n3.getToken() === 6 ? (F3(":"), b3(), U() || k3(4, [], [2, 5])) : k3(5, [], [2, 5]), i4.pop(), true);
  11776. }
  11777. o3(W, "parseProperty");
  11778. function V() {
  11779. d3(), b3();
  11780. let m4 = false;
  11781. for (; n3.getToken() !== 2 && n3.getToken() !== 17; ) {
  11782. if (n3.getToken() === 5) {
  11783. if (m4 || k3(4, [], []), F3(","), b3(), n3.getToken() === 2 && A3) break;
  11784. } else m4 && k3(6, [], []);
  11785. W() || k3(4, [], [2, 5]), m4 = true;
  11786. }
  11787. return p3(), n3.getToken() !== 2 ? k3(7, [2], []) : b3(), true;
  11788. }
  11789. o3(V, "parseObject");
  11790. function z2() {
  11791. D2(), b3();
  11792. let m4 = true, j3 = false;
  11793. for (; n3.getToken() !== 4 && n3.getToken() !== 17; ) {
  11794. if (n3.getToken() === 5) {
  11795. if (j3 || k3(4, [], []), F3(","), b3(), n3.getToken() === 4 && A3) break;
  11796. } else j3 && k3(6, [], []);
  11797. m4 ? (i4.push(0), m4 = false) : i4[i4.length - 1]++, U() || k3(4, [], [4, 5]), j3 = true;
  11798. }
  11799. return L(), m4 || i4.pop(), n3.getToken() !== 4 ? k3(8, [4], []) : b3(), true;
  11800. }
  11801. o3(z2, "parseArray");
  11802. function U() {
  11803. switch (n3.getToken()) {
  11804. case 3:
  11805. return z2();
  11806. case 1:
  11807. return V();
  11808. case 10:
  11809. return R(true);
  11810. default:
  11811. return J2();
  11812. }
  11813. }
  11814. return o3(U, "parseValue"), b3(), n3.getToken() === 17 ? s4.allowEmptyContent ? true : (k3(4, [], []), false) : U() ? (n3.getToken() !== 17 && k3(9, [], []), true) : (k3(4, [], []), false);
  11815. }
  11816. o3(Ne, "visit");
  11817. var ce;
  11818. (function(e4) {
  11819. e4[e4.None = 0] = "None", e4[e4.UnexpectedEndOfComment = 1] = "UnexpectedEndOfComment", e4[e4.UnexpectedEndOfString = 2] = "UnexpectedEndOfString", e4[e4.UnexpectedEndOfNumber = 3] = "UnexpectedEndOfNumber", e4[e4.InvalidUnicode = 4] = "InvalidUnicode", e4[e4.InvalidEscapeCharacter = 5] = "InvalidEscapeCharacter", e4[e4.InvalidCharacter = 6] = "InvalidCharacter";
  11820. })(ce || (ce = {}));
  11821. var ge;
  11822. (function(e4) {
  11823. e4[e4.OpenBraceToken = 1] = "OpenBraceToken", e4[e4.CloseBraceToken = 2] = "CloseBraceToken", e4[e4.OpenBracketToken = 3] = "OpenBracketToken", e4[e4.CloseBracketToken = 4] = "CloseBracketToken", e4[e4.CommaToken = 5] = "CommaToken", e4[e4.ColonToken = 6] = "ColonToken", e4[e4.NullKeyword = 7] = "NullKeyword", e4[e4.TrueKeyword = 8] = "TrueKeyword", e4[e4.FalseKeyword = 9] = "FalseKeyword", e4[e4.StringLiteral = 10] = "StringLiteral", e4[e4.NumericLiteral = 11] = "NumericLiteral", e4[e4.LineCommentTrivia = 12] = "LineCommentTrivia", e4[e4.BlockCommentTrivia = 13] = "BlockCommentTrivia", e4[e4.LineBreakTrivia = 14] = "LineBreakTrivia", e4[e4.Trivia = 15] = "Trivia", e4[e4.Unknown = 16] = "Unknown", e4[e4.EOF = 17] = "EOF";
  11824. })(ge || (ge = {}));
  11825. var Re = Pe;
  11826. var ke;
  11827. (function(e4) {
  11828. e4[e4.InvalidSymbol = 1] = "InvalidSymbol", e4[e4.InvalidNumberFormat = 2] = "InvalidNumberFormat", e4[e4.PropertyNameExpected = 3] = "PropertyNameExpected", e4[e4.ValueExpected = 4] = "ValueExpected", e4[e4.ColonExpected = 5] = "ColonExpected", e4[e4.CommaExpected = 6] = "CommaExpected", e4[e4.CloseBraceExpected = 7] = "CloseBraceExpected", e4[e4.CloseBracketExpected = 8] = "CloseBracketExpected", e4[e4.EndOfFileExpected = 9] = "EndOfFileExpected", e4[e4.InvalidCommentToken = 10] = "InvalidCommentToken", e4[e4.UnexpectedEndOfComment = 11] = "UnexpectedEndOfComment", e4[e4.UnexpectedEndOfString = 12] = "UnexpectedEndOfString", e4[e4.UnexpectedEndOfNumber = 13] = "UnexpectedEndOfNumber", e4[e4.InvalidUnicode = 14] = "InvalidUnicode", e4[e4.InvalidEscapeCharacter = 15] = "InvalidEscapeCharacter", e4[e4.InvalidCharacter = 16] = "InvalidCharacter";
  11829. })(ke || (ke = {}));
  11830. var we = o3((e4, t4) => Re($e(t4, e4, "utf8")), "readJsonc");
  11831. var C2 = Symbol("implicitBaseUrl");
  11832. var I2 = "${configDir}";
  11833. var Se = o3(() => {
  11834. const { findPnpApi: e4 } = he;
  11835. return e4 && e4(process.cwd());
  11836. }, "getPnpApi");
  11837. var ee = o3((e4, t4, s4, n3) => {
  11838. const i4 = `resolveFromPackageJsonPath:${e4}:${t4}:${s4}`;
  11839. if (n3 != null && n3.has(i4)) return n3.get(i4);
  11840. const l3 = we(e4, n3);
  11841. if (!l3) return;
  11842. let u3 = t4 || "tsconfig.json";
  11843. if (!s4 && l3.exports) try {
  11844. const [a3] = Ee.resolveExports(l3.exports, t4, ["require", "types"]);
  11845. u3 = a3;
  11846. } catch {
  11847. return false;
  11848. }
  11849. else !t4 && l3.tsconfig && (u3 = l3.tsconfig);
  11850. return u3 = w3.join(e4, "..", u3), n3 == null || n3.set(i4, u3), u3;
  11851. }, "resolveFromPackageJsonPath");
  11852. var ne = "package.json";
  11853. var te = "tsconfig.json";
  11854. var Me = o3((e4, t4, s4) => {
  11855. let n3 = e4;
  11856. if (e4 === ".." && (n3 = w3.join(n3, te)), e4[0] === "." && (n3 = w3.resolve(t4, n3)), w3.isAbsolute(n3)) {
  11857. if (E2(s4, n3)) {
  11858. if (G2(s4, n3).isFile()) return n3;
  11859. } else if (!n3.endsWith(".json")) {
  11860. const p3 = `${n3}.json`;
  11861. if (E2(s4, p3)) return p3;
  11862. }
  11863. return;
  11864. }
  11865. const [i4, ...l3] = e4.split("/"), u3 = i4[0] === "@" ? `${i4}/${l3.shift()}` : i4, a3 = l3.join("/"), r4 = Se();
  11866. if (r4) {
  11867. const { resolveRequest: p3 } = r4;
  11868. try {
  11869. if (u3 === e4) {
  11870. const D2 = p3(w3.join(u3, ne), t4);
  11871. if (D2) {
  11872. const L = ee(D2, a3, false, s4);
  11873. if (L && E2(s4, L)) return L;
  11874. }
  11875. } else {
  11876. let D2;
  11877. try {
  11878. D2 = p3(e4, t4, { extensions: [".json"] });
  11879. } catch {
  11880. D2 = p3(w3.join(e4, te), t4);
  11881. }
  11882. if (D2) return D2;
  11883. }
  11884. } catch {
  11885. }
  11886. }
  11887. const g3 = fe(w3.resolve(t4), w3.join("node_modules", u3), s4);
  11888. if (!g3 || !G2(s4, g3).isDirectory()) return;
  11889. const v6 = w3.join(g3, ne);
  11890. if (E2(s4, v6)) {
  11891. const p3 = ee(v6, a3, false, s4);
  11892. if (p3 === false) return;
  11893. if (p3 && E2(s4, p3) && G2(s4, p3).isFile()) return p3;
  11894. }
  11895. const d3 = w3.join(g3, a3), _3 = d3.endsWith(".json");
  11896. if (!_3) {
  11897. const p3 = `${d3}.json`;
  11898. if (E2(s4, p3)) return p3;
  11899. }
  11900. if (E2(s4, d3)) {
  11901. if (G2(s4, d3).isDirectory()) {
  11902. const p3 = w3.join(d3, ne);
  11903. if (E2(s4, p3)) {
  11904. const L = ee(p3, "", true, s4);
  11905. if (L && E2(s4, L)) return L;
  11906. }
  11907. const D2 = w3.join(d3, te);
  11908. if (E2(s4, D2)) return D2;
  11909. } else if (_3) return d3;
  11910. }
  11911. }, "resolveExtendsPath");
  11912. var se = o3((e4, t4) => K(w3.relative(e4, t4)), "pathRelative");
  11913. var me = ["files", "include", "exclude"];
  11914. var de = o3((e4, t4, s4) => {
  11915. const n3 = w3.join(t4, s4), i4 = w3.relative(e4, n3);
  11916. return h4(i4) || "./";
  11917. }, "resolveAndRelativize");
  11918. var Je = o3((e4, t4, s4) => {
  11919. const n3 = w3.relative(e4, t4);
  11920. if (!n3) return s4;
  11921. const i4 = s4.startsWith("./") ? s4.slice(2) : s4;
  11922. return h4(`${n3}/${i4}`);
  11923. }, "prefixPattern");
  11924. var We = o3((e4, t4, s4, n3) => {
  11925. const i4 = Me(e4, t4, n3);
  11926. if (!i4) throw new Error(`File '${e4}' not found.`);
  11927. if (s4.has(i4)) throw new Error(`Circularity detected while resolving configuration: ${i4}`);
  11928. s4.add(i4);
  11929. const l3 = w3.dirname(i4), u3 = ve(i4, n3, s4);
  11930. delete u3.references;
  11931. const { compilerOptions: a3 } = u3;
  11932. if (a3) {
  11933. const { baseUrl: r4 } = a3;
  11934. r4 && !r4.startsWith(I2) && (a3.baseUrl = de(t4, l3, r4));
  11935. const { outDir: g3 } = a3;
  11936. g3 && !g3.startsWith(I2) && (a3.outDir = de(t4, l3, g3));
  11937. }
  11938. for (const r4 of me) {
  11939. const g3 = u3[r4];
  11940. g3 && (u3[r4] = g3.map((v6) => v6.startsWith(I2) ? v6 : Je(t4, l3, v6)));
  11941. }
  11942. return u3;
  11943. }, "resolveExtends");
  11944. var be = ["outDir", "declarationDir"];
  11945. var ve = o3((e4, t4, s4 = /* @__PURE__ */ new Set()) => {
  11946. let n3;
  11947. try {
  11948. n3 = we(e4, t4) || {};
  11949. } catch {
  11950. throw new Error(`Cannot resolve tsconfig at path: ${e4}`);
  11951. }
  11952. if (typeof n3 != "object") throw new SyntaxError(`Failed to parse tsconfig at: ${e4}`);
  11953. const i4 = w3.dirname(e4);
  11954. if (n3.compilerOptions) {
  11955. const { compilerOptions: l3 } = n3;
  11956. l3.paths && !l3.baseUrl && (l3[C2] = i4);
  11957. }
  11958. if (n3.extends) {
  11959. const l3 = Array.isArray(n3.extends) ? n3.extends : [n3.extends];
  11960. delete n3.extends;
  11961. for (const u3 of l3.reverse()) {
  11962. const a3 = We(u3, i4, new Set(s4), t4), r4 = { ...a3, ...n3, compilerOptions: { ...a3.compilerOptions, ...n3.compilerOptions } };
  11963. a3.watchOptions && (r4.watchOptions = { ...a3.watchOptions, ...n3.watchOptions }), n3 = r4;
  11964. }
  11965. }
  11966. if (n3.compilerOptions) {
  11967. const { compilerOptions: l3 } = n3, u3 = ["baseUrl", "rootDir"];
  11968. for (const a3 of u3) {
  11969. const r4 = l3[a3];
  11970. if (r4 && !r4.startsWith(I2)) {
  11971. const g3 = w3.resolve(i4, r4), v6 = se(i4, g3);
  11972. l3[a3] = v6;
  11973. }
  11974. }
  11975. for (const a3 of be) {
  11976. let r4 = l3[a3];
  11977. r4 && (Array.isArray(n3.exclude) || (n3.exclude = be.map((g3) => l3[g3]).filter(Boolean)), r4.startsWith(I2) || (r4 = K(r4)), l3[a3] = r4);
  11978. }
  11979. } else n3.compilerOptions = {};
  11980. if (n3.include ? (n3.include = n3.include.map(h4), n3.files && delete n3.files) : n3.files && (n3.files = n3.files.map((l3) => l3.startsWith(I2) ? l3 : K(l3))), n3.watchOptions) {
  11981. const { watchOptions: l3 } = n3;
  11982. l3.excludeDirectories && (l3.excludeDirectories = l3.excludeDirectories.map((u3) => h4(w3.resolve(i4, u3)))), l3.excludeFiles && (l3.excludeFiles = l3.excludeFiles.map((u3) => h4(w3.resolve(i4, u3)))), l3.watchFile && (l3.watchFile = l3.watchFile.toLowerCase()), l3.watchDirectory && (l3.watchDirectory = l3.watchDirectory.toLowerCase()), l3.fallbackPolling && (l3.fallbackPolling = l3.fallbackPolling.toLowerCase());
  11983. }
  11984. return n3;
  11985. }, "_parseTsconfig");
  11986. var Q = o3((e4, t4) => {
  11987. if (e4.startsWith(I2)) return h4(w3.join(t4, e4.slice(I2.length)));
  11988. }, "interpolateConfigDir");
  11989. var Ve = ["outDir", "declarationDir", "outFile", "rootDir", "baseUrl", "tsBuildInfoFile"];
  11990. var ze = o3((e4) => {
  11991. var t4, s4, n3, i4, l3, u3, a3, r4, g3, v6, d3, _3, p3, D2, L, T, F3, B2, c3, y2, A3, b3, k3, R, J2, W, V, z2, U, m4, j3, S2, $;
  11992. if (e4.strict) {
  11993. const f5 = ["noImplicitAny", "noImplicitThis", "strictNullChecks", "strictFunctionTypes", "strictBindCallApply", "strictPropertyInitialization", "strictBuiltinIteratorReturn", "alwaysStrict", "useUnknownInCatchVariables"];
  11994. for (const x4 of f5) e4[x4] === void 0 && (e4[x4] = true);
  11995. }
  11996. if (e4.composite && ((t4 = e4.declaration) != null || (e4.declaration = true), (s4 = e4.incremental) != null || (e4.incremental = true)), e4.target) {
  11997. let f5 = e4.target.toLowerCase();
  11998. f5 === "es2015" && (f5 = "es6"), e4.target = f5, f5 === "esnext" && ((n3 = e4.module) != null || (e4.module = "es6"), (i4 = e4.useDefineForClassFields) != null || (e4.useDefineForClassFields = true)), (f5 === "es6" || f5 === "es2016" || f5 === "es2017" || f5 === "es2018" || f5 === "es2019" || f5 === "es2020" || f5 === "es2021" || f5 === "es2022" || f5 === "es2023" || f5 === "es2024") && ((l3 = e4.module) != null || (e4.module = "es6")), (f5 === "es2022" || f5 === "es2023" || f5 === "es2024") && ((u3 = e4.useDefineForClassFields) != null || (e4.useDefineForClassFields = true));
  11999. }
  12000. if (e4.module) {
  12001. let f5 = e4.module.toLowerCase();
  12002. if (f5 === "es2015" && (f5 = "es6"), e4.module = f5, (f5 === "es6" || f5 === "es2020" || f5 === "es2022" || f5 === "esnext" || f5 === "none" || f5 === "system" || f5 === "umd" || f5 === "amd") && ((a3 = e4.moduleResolution) != null || (e4.moduleResolution = "classic")), f5 === "system" && ((r4 = e4.allowSyntheticDefaultImports) != null || (e4.allowSyntheticDefaultImports = true)), (f5 === "node16" || f5 === "node18" || f5 === "node20" || f5 === "nodenext" || f5 === "preserve") && ((g3 = e4.esModuleInterop) != null || (e4.esModuleInterop = true), (v6 = e4.allowSyntheticDefaultImports) != null || (e4.allowSyntheticDefaultImports = true)), (f5 === "node16" || f5 === "node18" || f5 === "node20" || f5 === "nodenext") && ((d3 = e4.moduleDetection) != null || (e4.moduleDetection = "force")), f5 === "node16" && ((_3 = e4.target) != null || (e4.target = "es2022"), (p3 = e4.moduleResolution) != null || (e4.moduleResolution = "node16")), f5 === "node18" && ((D2 = e4.target) != null || (e4.target = "es2022"), (L = e4.moduleResolution) != null || (e4.moduleResolution = "node16")), f5 === "node20" && ((T = e4.target) != null || (e4.target = "es2023"), (F3 = e4.moduleResolution) != null || (e4.moduleResolution = "node16"), (B2 = e4.resolveJsonModule) != null || (e4.resolveJsonModule = true)), f5 === "nodenext" && ((c3 = e4.target) != null || (e4.target = "esnext"), (y2 = e4.moduleResolution) != null || (e4.moduleResolution = "nodenext"), (A3 = e4.resolveJsonModule) != null || (e4.resolveJsonModule = true)), f5 === "node16" || f5 === "node18" || f5 === "node20" || f5 === "nodenext") {
  12003. const x4 = e4.target;
  12004. (x4 === "es3" || x4 === "es2022" || x4 === "es2023" || x4 === "es2024" || x4 === "esnext") && ((b3 = e4.useDefineForClassFields) != null || (e4.useDefineForClassFields = true));
  12005. }
  12006. f5 === "preserve" && ((k3 = e4.moduleResolution) != null || (e4.moduleResolution = "bundler"));
  12007. }
  12008. if (e4.moduleResolution) {
  12009. let f5 = e4.moduleResolution.toLowerCase();
  12010. f5 === "node" && (f5 = "node10"), e4.moduleResolution = f5, (f5 === "node16" || f5 === "nodenext" || f5 === "bundler") && ((R = e4.resolvePackageJsonExports) != null || (e4.resolvePackageJsonExports = true), (J2 = e4.resolvePackageJsonImports) != null || (e4.resolvePackageJsonImports = true)), f5 === "bundler" && ((W = e4.allowSyntheticDefaultImports) != null || (e4.allowSyntheticDefaultImports = true), (V = e4.resolveJsonModule) != null || (e4.resolveJsonModule = true));
  12011. }
  12012. e4.jsx && (e4.jsx = e4.jsx.toLowerCase()), e4.moduleDetection && (e4.moduleDetection = e4.moduleDetection.toLowerCase()), e4.importsNotUsedAsValues && (e4.importsNotUsedAsValues = e4.importsNotUsedAsValues.toLowerCase()), e4.newLine && (e4.newLine = e4.newLine.toLowerCase()), e4.esModuleInterop && ((z2 = e4.allowSyntheticDefaultImports) != null || (e4.allowSyntheticDefaultImports = true)), e4.verbatimModuleSyntax && ((U = e4.isolatedModules) != null || (e4.isolatedModules = true), (m4 = e4.preserveConstEnums) != null || (e4.preserveConstEnums = true)), e4.isolatedModules && ((j3 = e4.preserveConstEnums) != null || (e4.preserveConstEnums = true)), e4.rewriteRelativeImportExtensions && ((S2 = e4.allowImportingTsExtensions) != null || (e4.allowImportingTsExtensions = true)), e4.lib && (e4.lib = e4.lib.map((f5) => f5.toLowerCase())), e4.checkJs && (($ = e4.allowJs) != null || (e4.allowJs = true));
  12013. }, "normalizeCompilerOptions");
  12014. var pe = o3((e4, t4 = /* @__PURE__ */ new Map()) => {
  12015. const s4 = w3.resolve(e4), n3 = ve(s4, t4), i4 = w3.dirname(s4), { compilerOptions: l3 } = n3;
  12016. if (l3) {
  12017. for (const a3 of Ve) {
  12018. const r4 = l3[a3];
  12019. if (r4) {
  12020. const g3 = Q(r4, i4);
  12021. l3[a3] = g3 ? se(i4, g3) : r4;
  12022. }
  12023. }
  12024. for (const a3 of ["rootDirs", "typeRoots"]) {
  12025. const r4 = l3[a3];
  12026. r4 && (l3[a3] = r4.map((g3) => {
  12027. const v6 = Q(g3, i4);
  12028. return v6 ? se(i4, v6) : g3;
  12029. }));
  12030. }
  12031. const { paths: u3 } = l3;
  12032. if (u3) for (const a3 of Object.keys(u3)) u3[a3] = u3[a3].map((r4) => {
  12033. var g3;
  12034. return (g3 = Q(r4, i4)) != null ? g3 : r4;
  12035. });
  12036. ze(l3);
  12037. }
  12038. for (const u3 of me) {
  12039. const a3 = n3[u3];
  12040. a3 && (n3[u3] = a3.map((r4) => {
  12041. var g3;
  12042. return (g3 = Q(r4, i4)) != null ? g3 : r4;
  12043. }));
  12044. }
  12045. return n3;
  12046. }, "parseTsconfig");
  12047. var Ge = o3((e4 = process.cwd(), t4 = "tsconfig.json", s4 = /* @__PURE__ */ new Map()) => {
  12048. const n3 = fe(h4(e4), t4, s4);
  12049. if (!n3) return null;
  12050. const i4 = pe(n3, s4);
  12051. return { path: n3, config: i4 };
  12052. }, "getTsconfig");
  12053. var qe = /\*/g;
  12054. var Te = o3((e4, t4) => {
  12055. const s4 = e4.match(qe);
  12056. if (s4 && s4.length > 1) throw new Error(t4);
  12057. }, "assertStarCount");
  12058. var Qe = o3((e4) => {
  12059. if (e4.includes("*")) {
  12060. const [t4, s4] = e4.split("*");
  12061. return { prefix: t4, suffix: s4 };
  12062. }
  12063. return e4;
  12064. }, "parsePattern");
  12065. var He = o3(({ prefix: e4, suffix: t4 }, s4) => s4.startsWith(e4) && s4.endsWith(t4), "isPatternMatch");
  12066. var Xe = o3((e4, t4, s4) => Object.entries(e4).map(([n3, i4]) => (Te(n3, `Pattern '${n3}' can have at most one '*' character.`), { pattern: Qe(n3), substitutions: i4.map((l3) => {
  12067. if (Te(l3, `Substitution '${l3}' in pattern '${n3}' can have at most one '*' character.`), !t4 && !Z2.test(l3) && !w3.isAbsolute(l3)) throw new Error("Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?");
  12068. return w3.resolve(s4, l3);
  12069. }) })), "parsePaths");
  12070. var Ye = o3((e4) => {
  12071. const { compilerOptions: t4 } = e4.config;
  12072. if (!t4) return null;
  12073. const { baseUrl: s4, paths: n3 } = t4;
  12074. if (!s4 && !n3) return null;
  12075. const i4 = C2 in t4 && t4[C2], l3 = w3.resolve(w3.dirname(e4.path), s4 || i4 || "."), u3 = n3 ? Xe(n3, s4, l3) : [];
  12076. return (a3) => {
  12077. if (Z2.test(a3)) return [];
  12078. const r4 = [];
  12079. for (const _3 of u3) {
  12080. if (_3.pattern === a3) return _3.substitutions.map(h4);
  12081. typeof _3.pattern != "string" && r4.push(_3);
  12082. }
  12083. let g3, v6 = -1;
  12084. for (const _3 of r4) He(_3.pattern, a3) && _3.pattern.prefix.length > v6 && (v6 = _3.pattern.prefix.length, g3 = _3);
  12085. if (!g3) return s4 ? [h4(w3.join(l3, a3))] : [];
  12086. const d3 = a3.slice(g3.pattern.prefix.length, a3.length - g3.pattern.suffix.length);
  12087. return g3.substitutions.map((_3) => h4(_3.replace("*", d3)));
  12088. };
  12089. }, "createPathsMatcher");
  12090. var Ze = Object.defineProperty;
  12091. var H2 = o3((e4, t4) => Ze(e4, "name", { value: t4, configurable: true }), "s");
  12092. var Ae = H2((e4) => {
  12093. let t4 = "";
  12094. for (let s4 = 0; s4 < e4.length; s4 += 1) {
  12095. const n3 = e4[s4], i4 = n3.toUpperCase();
  12096. t4 += n3 === i4 ? n3.toLowerCase() : i4;
  12097. }
  12098. return t4;
  12099. }, "invertCase");
  12100. var le = /* @__PURE__ */ new Map();
  12101. var _e = H2((e4, t4) => {
  12102. const s4 = Ie.join(e4, `.is-fs-case-sensitive-test-${process.pid}`);
  12103. try {
  12104. return t4.writeFileSync(s4, ""), !t4.existsSync(Ae(s4));
  12105. } finally {
  12106. try {
  12107. t4.unlinkSync(s4);
  12108. } catch {
  12109. }
  12110. }
  12111. }, "checkDirectoryCaseWithWrite");
  12112. var Ke = H2((e4, t4, s4) => {
  12113. try {
  12114. return _e(e4, s4);
  12115. } catch (n3) {
  12116. if (t4 === void 0) return _e(xe.tmpdir(), s4);
  12117. throw n3;
  12118. }
  12119. }, "checkDirectoryCaseWithFallback");
  12120. var Oe = H2((e4, t4 = Be, s4 = true) => {
  12121. const n3 = e4 != null ? e4 : process.cwd();
  12122. if (s4 && le.has(n3)) return le.get(n3);
  12123. let i4;
  12124. const l3 = Ae(n3);
  12125. return l3 !== n3 && t4.existsSync(n3) ? i4 = !t4.existsSync(l3) : i4 = Ke(n3, e4, t4), s4 && le.set(n3, i4), i4;
  12126. }, "isFsCaseSensitive");
  12127. var { join: ye } = w3.posix;
  12128. var ie = { ts: [".ts", ".tsx", ".d.ts"], cts: [".cts", ".d.cts"], mts: [".mts", ".d.mts"] };
  12129. var Ce = o3((e4) => {
  12130. const t4 = [...ie.ts], s4 = [...ie.cts], n3 = [...ie.mts];
  12131. return e4 != null && e4.allowJs && (t4.push(".js", ".jsx"), s4.push(".cjs"), n3.push(".mjs")), [...t4, ...s4, ...n3];
  12132. }, "getSupportedExtensions");
  12133. var en = o3((e4) => {
  12134. const t4 = [];
  12135. if (!e4) return t4;
  12136. const { outDir: s4, declarationDir: n3 } = e4;
  12137. return s4 && t4.push(s4), n3 && t4.push(n3), t4;
  12138. }, "getDefaultExcludeSpec");
  12139. var je = o3((e4) => e4.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`), "escapeForRegexp");
  12140. var nn = ["node_modules", "bower_components", "jspm_packages"];
  12141. var oe = `(?!(${nn.join("|")})(/|$))`;
  12142. var tn = /(?:^|\/)[^.*?]+$/;
  12143. var Fe = "**/*";
  12144. var X = "[^/]";
  12145. var ue = "[^./]";
  12146. var De = process.platform === "win32";
  12147. var sn = o3(({ config: e4, path: t4 }, s4 = Oe()) => {
  12148. if ("extends" in e4) throw new Error("tsconfig#extends must be resolved. Use getTsconfig or parseTsconfig to resolve it.");
  12149. if (!w3.isAbsolute(t4)) throw new Error("The tsconfig path must be absolute");
  12150. De && (t4 = h4(t4));
  12151. const n3 = w3.dirname(t4), { files: i4, include: l3, exclude: u3, compilerOptions: a3 } = e4, r4 = o3((T) => w3.isAbsolute(T) ? T : ye(n3, T), "resolvePattern"), g3 = i4 == null ? void 0 : i4.map(r4), v6 = Ce(a3), d3 = s4 ? "" : "i", p3 = (u3 || en(a3)).map((T) => {
  12152. const F3 = r4(T), B2 = je(F3).replaceAll(String.raw`\*\*/`, "(.+/)?").replaceAll(String.raw`\*`, `${X}*`).replaceAll(String.raw`\?`, X);
  12153. return new RegExp(`^${B2}($|/)`, d3);
  12154. }), D2 = i4 || l3 ? l3 : [Fe], L = D2 ? D2.map((T) => {
  12155. let F3 = r4(T);
  12156. tn.test(F3) && (F3 = ye(F3, Fe));
  12157. const B2 = je(F3).replaceAll(String.raw`/\*\*`, `(/${oe}${ue}${X}*)*?`).replaceAll(/(\/)?\\\*/g, (c3, y2) => {
  12158. const A3 = `(${ue}|(\\.(?!min\\.js$))?)*`;
  12159. return y2 ? `/${oe}${ue}${A3}` : A3;
  12160. }).replaceAll(/(\/)?\\\?/g, (c3, y2) => {
  12161. const A3 = X;
  12162. return y2 ? `/${oe}${A3}` : A3;
  12163. });
  12164. return new RegExp(`^${B2}$`, d3);
  12165. }) : void 0;
  12166. return (T) => {
  12167. if (!w3.isAbsolute(T)) throw new Error("filePath must be absolute");
  12168. if (De && (T = h4(T)), g3 != null && g3.includes(T)) return e4;
  12169. if (!(!v6.some((F3) => T.endsWith(F3)) || p3.some((F3) => F3.test(T))) && L && L.some((F3) => F3.test(T))) return e4;
  12170. };
  12171. }, "createFilesMatcher");
  12172. exports2.createFilesMatcher = sn, exports2.createPathsMatcher = Ye, exports2.getTsconfig = Ge, exports2.parseTsconfig = pe;
  12173. }
  12174. });
  12175. // ../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/lexer-DgIbo0BU.cjs
  12176. var require_lexer_DgIbo0BU = __commonJS({
  12177. "../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/lexer-DgIbo0BU.cjs"(exports2) {
  12178. "use strict";
  12179. var G2 = Object.defineProperty;
  12180. var k3 = (A3, E2) => G2(A3, "name", { value: E2, configurable: true });
  12181. exports2.ImportType = void 0, function(A3) {
  12182. A3[A3.Static = 1] = "Static", A3[A3.Dynamic = 2] = "Dynamic", A3[A3.ImportMeta = 3] = "ImportMeta", A3[A3.StaticSourcePhase = 4] = "StaticSourcePhase", A3[A3.DynamicSourcePhase = 5] = "DynamicSourcePhase";
  12183. }(exports2.ImportType || (exports2.ImportType = {}));
  12184. var r4 = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
  12185. function U(A3, E2 = "@") {
  12186. if (!Q) return F3.then(() => U(A3));
  12187. const g3 = A3.length + 1, B2 = (Q.__heap_base.value || Q.__heap_base) + 4 * g3 - Q.memory.buffer.byteLength;
  12188. B2 > 0 && Q.memory.grow(Math.ceil(B2 / 65536));
  12189. const i4 = Q.sa(g3 - 1);
  12190. if ((r4 ? R : Y)(A3, new Uint16Array(Q.memory.buffer, i4, g3)), !Q.parse()) throw Object.assign(new Error(`Parse error ${E2}:${A3.slice(0, Q.e()).split(`
  12191. `).length}:${Q.e() - A3.lastIndexOf(`
  12192. `, Q.e() - 1)}`), { idx: Q.e() });
  12193. const a3 = [], t4 = [];
  12194. for (; Q.ri(); ) {
  12195. const C2 = Q.is(), I2 = Q.ie(), D2 = Q.it(), s4 = Q.ai(), w3 = Q.id(), J2 = Q.ss(), K = Q.se();
  12196. let o3;
  12197. Q.ip() && (o3 = N(A3.slice(w3 === -1 ? C2 - 1 : C2, w3 === -1 ? I2 + 1 : I2))), a3.push({ n: o3, t: D2, s: C2, e: I2, ss: J2, se: K, d: w3, a: s4 });
  12198. }
  12199. for (; Q.re(); ) {
  12200. const C2 = Q.es(), I2 = Q.ee(), D2 = Q.els(), s4 = Q.ele(), w3 = A3.slice(C2, I2), J2 = w3[0], K = D2 < 0 ? void 0 : A3.slice(D2, s4), o3 = K ? K[0] : "";
  12201. t4.push({ s: C2, e: I2, ls: D2, le: s4, n: J2 === '"' || J2 === "'" ? N(w3) : w3, ln: o3 === '"' || o3 === "'" ? N(K) : K });
  12202. }
  12203. function N(C2) {
  12204. try {
  12205. return (0, eval)(C2);
  12206. } catch {
  12207. }
  12208. }
  12209. return k3(N, "k"), [a3, t4, !!Q.f(), !!Q.ms()];
  12210. }
  12211. k3(U, "parse");
  12212. function Y(A3, E2) {
  12213. const g3 = A3.length;
  12214. let B2 = 0;
  12215. for (; B2 < g3; ) {
  12216. const i4 = A3.charCodeAt(B2);
  12217. E2[B2++] = (255 & i4) << 8 | i4 >>> 8;
  12218. }
  12219. }
  12220. k3(Y, "Q");
  12221. function R(A3, E2) {
  12222. const g3 = A3.length;
  12223. let B2 = 0;
  12224. for (; B2 < g3; ) E2[B2] = A3.charCodeAt(B2++);
  12225. }
  12226. k3(R, "B");
  12227. var Q;
  12228. var F3 = WebAssembly.compile((L = "AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKm0EwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1AkhBEEAKALQCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUEANgIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALQCSADRiICOgAYAkACQCACDQBBACgC1AkgA0cNAQtBAEEBOgCMCgsLXgEBf0EAKAL4CSIEQRBqQeQJIAQbQQAoAogKIgQ2AgBBACAENgL4CUEAIARBFGo2AogKQQBBAToAjAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKQCgsVAEEAKALoCSgCAEEAKALcCWtBAXULHgEBf0EAKALoCSgCBCIAQQAoAtwJa0EBdUF/IAAbCxUAQQAoAugJKAIIQQAoAtwJa0EBdQseAQF/QQAoAugJKAIMIgBBACgC3AlrQQF1QX8gABsLCwBBACgC6AkoAhwLHgEBf0EAKALoCSgCECIAQQAoAtwJa0EBdUF/IAAbCzsBAX8CQEEAKALoCSgCFCIAQQAoAtAJRw0AQX8PCwJAIABBACgC1AlHDQBBfg8LIABBACgC3AlrQQF1CwsAQQAoAugJLQAYCxUAQQAoAuwJKAIAQQAoAtwJa0EBdQsVAEEAKALsCSgCBEEAKALcCWtBAXULHgEBf0EAKALsCSgCCCIAQQAoAtwJa0EBdUF/IAAbCx4BAX9BACgC7AkoAgwiAEEAKALcCWtBAXVBfyAAGwslAQF/QQBBACgC6AkiAEEgakHgCSAAGygCACIANgLoCSAAQQBHCyUBAX9BAEEAKALsCSIAQRBqQeQJIAAbKAIAIgA2AuwJIABBAEcLCABBAC0AlAoLCABBAC0AjAoL3Q0BBX8jAEGA0ABrIgAkAEEAQQE6AJQKQQBBACgC2Ak2ApwKQQBBACgC3AlBfmoiATYCsApBACABQQAoAoAKQQF0aiICNgK0CkEAQQA6AIwKQQBBADsBlgpBAEEAOwGYCkEAQQA6AKAKQQBBADYCkApBAEEAOgD8CUEAIABBgBBqNgKkCkEAIAA2AqgKQQBBADoArAoCQAJAAkACQANAQQAgAUECaiIDNgKwCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BmAoNASADEBVFDQEgAUEEakGCCEEKEC8NARAWQQAtAJQKDQFBAEEAKAKwCiIBNgKcCgwHCyADEBVFDQAgAUEEakGMCEEKEC8NABAXC0EAQQAoArAKNgKcCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAYDAELQQEQGQtBACgCtAohAkEAKAKwCiEBDAALC0EAIQIgAyEBQQAtAPwJDQIMAQtBACABNgKwCkEAQQA6AJQKCwNAQQAgAUECaiIDNgKwCgJAAkACQAJAAkACQAJAIAFBACgCtApPDQAgAy8BACICQXdqQQVJDQYCQAJAAkACQAJAAkACQAJAAkACQCACQWBqDgoQDwYPDw8PBQECAAsCQAJAAkACQCACQaB/ag4KCxISAxIBEhISAgALIAJBhX9qDgMFEQYJC0EALwGYCg0QIAMQFUUNECABQQRqQYIIQQoQLw0QEBYMEAsgAxAVRQ0PIAFBBGpBjAhBChAvDQ8QFwwPCyADEBVFDQ4gASkABELsgISDsI7AOVINDiABLwEMIgNBd2oiAUEXSw0MQQEgAXRBn4CABHFFDQwMDQtBAEEALwGYCiIBQQFqOwGYCkEAKAKkCiABQQN0aiIBQQE2AgAgAUEAKAKcCjYCBAwNC0EALwGYCiIDRQ0JQQAgA0F/aiIDOwGYCkEALwGWCiICRQ0MQQAoAqQKIANB//8DcUEDdGooAgBBBUcNDAJAIAJBAnRBACgCqApqQXxqKAIAIgMoAgQNACADQQAoApwKQQJqNgIEC0EAIAJBf2o7AZYKIAMgAUEEajYCDAwMCwJAQQAoApwKIgEvAQBBKUcNAEEAKALwCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAvQJIgM2AvAJAkAgA0UNACADQQA2AiAMAQtBAEEANgLgCQtBAEEALwGYCiIDQQFqOwGYCkEAKAKkCiADQQN0aiIDQQZBAkEALQCsChs2AgAgAyABNgIEQQBBADoArAoMCwtBAC8BmAoiAUUNB0EAIAFBf2oiATsBmApBACgCpAogAUH//wNxQQN0aigCAEEERg0EDAoLQScQGgwJC0EiEBoMCAsgAkEvRw0HAkACQCABLwEEIgFBKkYNACABQS9HDQEQGAwKC0EBEBkMCQsCQAJAAkACQEEAKAKcCiIBLwEAIgMQG0UNAAJAAkAgA0FVag4EAAkBAwkLIAFBfmovAQBBK0YNAwwICyABQX5qLwEAQS1GDQIMBwsgA0EpRw0BQQAoAqQKQQAvAZgKIgJBA3RqKAIEEBxFDQIMBgsgAUF+ai8BAEFQakH//wNxQQpPDQULQQAvAZgKIQILAkACQCACQf//A3EiAkUNACADQeYARw0AQQAoAqQKIAJBf2pBA3RqIgQoAgBBAUcNACABQX5qLwEAQe8ARw0BIAQoAgRBlghBAxAdRQ0BDAULIANB/QBHDQBBACgCpAogAkEDdGoiAigCBBAeDQQgAigCAEEGRg0ECyABEB8NAyADRQ0DIANBL0ZBAC0AoApBAEdxDQMCQEEAKAL4CSICRQ0AIAEgAigCAEkNACABIAIoAgRNDQQLIAFBfmohAUEAKALcCSECAkADQCABQQJqIgQgAk0NAUEAIAE2ApwKIAEvAQAhAyABQX5qIgQhASADECBFDQALIARBAmohBAsCQCADQf//A3EQIUUNACAEQX5qIQECQANAIAFBAmoiAyACTQ0BQQAgATYCnAogAS8BACEDIAFBfmoiBCEBIAMQIQ0ACyAEQQJqIQMLIAMQIg0EC0EAQQE6AKAKDAcLQQAoAqQKQQAvAZgKIgFBA3QiA2pBACgCnAo2AgRBACABQQFqOwGYCkEAKAKkCiADakEDNgIACxAjDAULQQAtAPwJQQAvAZYKQQAvAZgKcnJFIQIMBwsQJEEAQQA6AKAKDAMLECVBACECDAULIANBoAFHDQELQQBBAToArAoLQQBBACgCsAo2ApwKC0EAKAKwCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC3AkgAEcNAEEBDwsgAEF+ahAmC/4KAQZ/QQBBACgCsAoiAEEMaiIBNgKwCkEAKAL4CSECQQEQKSEDAkACQAJAAkACQAJAAkACQAJAQQAoArAKIgQgAUcNACADEChFDQELAkACQAJAAkACQAJAAkAgA0EqRg0AIANB+wBHDQFBACAEQQJqNgKwCkEBECkhA0EAKAKwCiEEA0ACQAJAIANB//8DcSIDQSJGDQAgA0EnRg0AIAMQLBpBACgCsAohAwwBCyADEBpBAEEAKAKwCkECaiIDNgKwCgtBARApGgJAIAQgAxAtIgNBLEcNAEEAQQAoArAKQQJqNgKwCkEBECkhAwsgA0H9AEYNA0EAKAKwCiIFIARGDQ8gBSEEIAVBACgCtApNDQAMDwsLQQAgBEECajYCsApBARApGkEAKAKwCiIDIAMQLRoMAgtBAEEAOgCUCgJAAkACQAJAAkACQCADQZ9/ag4MAgsEAQsDCwsLCwsFAAsgA0H2AEYNBAwKC0EAIARBDmoiAzYCsAoCQAJAAkBBARApQZ9/ag4GABICEhIBEgtBACgCsAoiBSkAAkLzgOSD4I3AMVINESAFLwEKECFFDRFBACAFQQpqNgKwCkEAECkaC0EAKAKwCiIFQQJqQbIIQQ4QLw0QIAUvARAiAkF3aiIBQRdLDQ1BASABdEGfgIAEcUUNDQwOC0EAKAKwCiIFKQACQuyAhIOwjsA5Ug0PIAUvAQoiAkF3aiIBQRdNDQYMCgtBACAEQQpqNgKwCkEAECkaQQAoArAKIQQLQQAgBEEQajYCsAoCQEEBECkiBEEqRw0AQQBBACgCsApBAmo2ArAKQQEQKSEEC0EAKAKwCiEDIAQQLBogA0EAKAKwCiIEIAMgBBACQQBBACgCsApBfmo2ArAKDwsCQCAEKQACQuyAhIOwjsA5Ug0AIAQvAQoQIEUNAEEAIARBCmo2ArAKQQEQKSEEQQAoArAKIQMgBBAsGiADQQAoArAKIgQgAyAEEAJBAEEAKAKwCkF+ajYCsAoPC0EAIARBBGoiBDYCsAoLQQAgBEEGajYCsApBAEEAOgCUCkEBECkhBEEAKAKwCiEDIAQQLCEEQQAoArAKIQIgBEHf/wNxIgFB2wBHDQNBACACQQJqNgKwCkEBECkhBUEAKAKwCiEDQQAhBAwEC0EAQQE6AIwKQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0AQQAgA0EIajYCsAogAEEBEClBABArIAJBEGpB5AkgAhshAwNAIAMoAgAiA0UNBSADQgA3AgggA0EQaiEDDAALC0EAIANBfmo2ArAKDAMLQQEgAXRBn4CABHFFDQMMBAtBASEECwNAAkACQCAEDgIAAQELIAVB//8DcRAsGkEBIQQMAQsCQAJAQQAoArAKIgQgA0YNACADIAQgAyAEEAJBARApIQQCQCABQdsARw0AIARBIHJB/QBGDQQLQQAoArAKIQMCQCAEQSxHDQBBACADQQJqNgKwCkEBECkhBUEAKAKwCiEDIAVBIHJB+wBHDQILQQAgA0F+ajYCsAoLIAFB2wBHDQJBACACQX5qNgKwCg8LQQAhBAwACwsPCyACQaABRg0AIAJB+wBHDQQLQQAgBUEKajYCsApBARApIgVB+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2ArAKAkBBARApIgVBKkcNAEEAQQAoArAKQQJqNgKwCkEBECkhBQsgBUEoRg0BC0EAKAKwCiEBIAUQLBpBACgCsAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoArAKQX5qNgKwCg8LIAQgA0EAQQAQAkEAIARBDGo2ArAKDwsQJQvcCAEGf0EAIQBBAEEAKAKwCiIBQQxqIgI2ArAKQQEQKSEDQQAoArAKIQQCQAJAAkACQAJAAkACQAJAIANBLkcNAEEAIARBAmo2ArAKAkBBARApIgNB8wBGDQAgA0HtAEcNB0EAKAKwCiIDQQJqQZwIQQYQLw0HAkBBACgCnAoiBBAqDQAgBC8BAEEuRg0ICyABIAEgA0EIakEAKALUCRABDwtBACgCsAoiA0ECakGiCEEKEC8NBgJAQQAoApwKIgQQKg0AIAQvAQBBLkYNBwsgA0EMaiEDDAELIANB8wBHDQEgBCACTQ0BQQYhAEEAIQIgBEECakGiCEEKEC8NAiAEQQxqIQMCQCAELwEMIgVBd2oiBEEXSw0AQQEgBHRBn4CABHENAQsgBUGgAUcNAgtBACADNgKwCkEBIQBBARApIQMLAkACQAJAAkAgA0H7AEYNACADQShHDQFBACgCpApBAC8BmAoiA0EDdGoiBEEAKAKwCjYCBEEAIANBAWo7AZgKIARBBTYCAEEAKAKcCi8BAEEuRg0HQQBBACgCsAoiBEECajYCsApBARApIQMgAUEAKAKwCkEAIAQQAQJAAkAgAA0AQQAoAvAJIQQMAQtBACgC8AkiBEEFNgIcC0EAQQAvAZYKIgBBAWo7AZYKQQAoAqgKIABBAnRqIAQ2AgACQCADQSJGDQAgA0EnRg0AQQBBACgCsApBfmo2ArAKDwsgAxAaQQBBACgCsApBAmoiAzYCsAoCQAJAAkBBARApQVdqDgQBAgIAAgtBAEEAKAKwCkECajYCsApBARApGkEAKALwCSIEIAM2AgQgBEEBOgAYIARBACgCsAoiAzYCEEEAIANBfmo2ArAKDwtBACgC8AkiBCADNgIEIARBAToAGEEAQQAvAZgKQX9qOwGYCiAEQQAoArAKQQJqNgIMQQBBAC8BlgpBf2o7AZYKDwtBAEEAKAKwCkF+ajYCsAoPCyAADQJBACgCsAohA0EALwGYCg0BA0ACQAJAAkAgA0EAKAK0Ck8NAEEBECkiA0EiRg0BIANBJ0YNASADQf0ARw0CQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0JC0EAIANBCGo2ArAKAkBBARApIgNBIkYNACADQSdHDQkLIAEgA0EAECsPCyADEBoLQQBBACgCsApBAmoiAzYCsAoMAAsLIAANAUEGIQBBACECAkAgA0FZag4EBAMDBAALIANBIkYNAwwCC0EAIANBfmo2ArAKDwtBDCEAQQEhAgtBACgCsAoiAyABIABBAXRqRw0AQQAgA0F+ajYCsAoPC0EALwGYCg0CQQAoArAKIQNBACgCtAohAANAIAMgAE8NAQJAAkAgAy8BACIEQSdGDQAgBEEiRw0BCyABIAQgAhArDwtBACADQQJqIgM2ArAKDAALCxAlCw8LQQBBACgCsApBfmo2ArAKC0cBA39BACgCsApBAmohAEEAKAK0CiEBAkADQCAAIgJBfmogAU8NASACQQJqIQAgAi8BAEF2ag4EAQAAAQALC0EAIAI2ArAKC5gBAQN/QQBBACgCsAoiAUECajYCsAogAUEGaiEBQQAoArQKIQIDQAJAAkACQCABQXxqIAJPDQAgAUF+ai8BACEDAkACQCAADQAgA0EqRg0BIANBdmoOBAIEBAIECyADQSpHDQMLIAEvAQBBL0cNAkEAIAFBfmo2ArAKDAELIAFBfmohAQtBACABNgKwCg8LIAFBAmohAQwACwuIAQEEf0EAKAKwCiEBQQAoArQKIQICQAJAA0AgASIDQQJqIQEgAyACTw0BIAEvAQAiBCAARg0CAkAgBEHcAEYNACAEQXZqDgQCAQECAQsgA0EEaiEBIAMvAQRBDUcNACADQQZqIAEgAy8BBkEKRhshAQwACwtBACABNgKwChAlDwtBACABNgKwCgtsAQF/AkACQCAAQV9qIgFBBUsNAEEBIAF0QTFxDQELIABBRmpB//8DcUEGSQ0AIABBKUcgAEFYakH//wNxQQdJcQ0AAkAgAEGlf2oOBAEAAAEACyAAQf0ARyAAQYV/akH//wNxQQRJcQ8LQQELLgEBf0EBIQECQCAAQaYJQQUQHQ0AIABBlghBAxAdDQAgAEGwCUECEB0hAQsgAQtGAQN/QQAhAwJAIAAgAkEBdCICayIEQQJqIgBBACgC3AkiBUkNACAAIAEgAhAvDQACQCAAIAVHDQBBAQ8LIAQQJiEDCyADC4MBAQJ/QQEhAQJAAkACQAJAAkACQCAALwEAIgJBRWoOBAUEBAEACwJAIAJBm39qDgQDBAQCAAsgAkEpRg0EIAJB+QBHDQMgAEF+akG8CUEGEB0PCyAAQX5qLwEAQT1GDwsgAEF+akG0CUEEEB0PCyAAQX5qQcgJQQMQHQ8LQQAhAQsgAQu0AwECf0EAIQECQAJAAkACQAJAAkACQAJAAkACQCAALwEAQZx/ag4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEF+ai8BAEGXf2oOBAAKCgEKCyAAQXxqQcoIQQIQHQ8LIABBfGpBzghBAxAdDwsCQAJAAkAgAEF+ai8BAEGNf2oOAwABAgoLAkAgAEF8ai8BACICQeEARg0AIAJB7ABHDQogAEF6akHlABAnDwsgAEF6akHjABAnDwsgAEF8akHUCEEEEB0PCyAAQXxqQdwIQQYQHQ8LIABBfmovAQBB7wBHDQYgAEF8ai8BAEHlAEcNBgJAIABBemovAQAiAkHwAEYNACACQeMARw0HIABBeGpB6AhBBhAdDwsgAEF4akH0CEECEB0PCyAAQX5qQfgIQQQQHQ8LQQEhASAAQX5qIgBB6QAQJw0EIABBgAlBBRAdDwsgAEF+akHkABAnDwsgAEF+akGKCUEHEB0PCyAAQX5qQZgJQQQQHQ8LAkAgAEF+ai8BACICQe8ARg0AIAJB5QBHDQEgAEF8akHuABAnDwsgAEF8akGgCUEDEB0hAQsgAQs0AQF/QQEhAQJAIABBd2pB//8DcUEFSQ0AIABBgAFyQaABRg0AIABBLkcgABAocSEBCyABCzABAX8CQAJAIABBd2oiAUEXSw0AQQEgAXRBjYCABHENAQsgAEGgAUYNAEEADwtBAQtOAQJ/QQAhAQJAAkAgAC8BACICQeUARg0AIAJB6wBHDQEgAEF+akH4CEEEEB0PCyAAQX5qLwEAQfUARw0AIABBfGpB3AhBBhAdIQELIAEL3gEBBH9BACgCsAohAEEAKAK0CiEBAkACQAJAA0AgACICQQJqIQAgAiABTw0BAkACQAJAIAAvAQAiA0Gkf2oOBQIDAwMBAAsgA0EkRw0CIAIvAQRB+wBHDQJBACACQQRqIgA2ArAKQQBBAC8BmAoiAkEBajsBmApBACgCpAogAkEDdGoiAkEENgIAIAIgADYCBA8LQQAgADYCsApBAEEALwGYCkF/aiIAOwGYCkEAKAKkCiAAQf//A3FBA3RqKAIAQQNHDQMMBAsgAkEEaiEADAALC0EAIAA2ArAKCxAlCwtwAQJ/AkACQANAQQBBACgCsAoiAEECaiIBNgKwCiAAQQAoArQKTw0BAkACQAJAIAEvAQAiAUGlf2oOAgECAAsCQCABQXZqDgQEAwMEAAsgAUEvRw0CDAQLEC4aDAELQQAgAEEEajYCsAoMAAsLECULCzUBAX9BAEEBOgD8CUEAKAKwCiEAQQBBACgCtApBAmo2ArAKQQAgAEEAKALcCWtBAXU2ApAKC0MBAn9BASEBAkAgAC8BACICQXdqQf//A3FBBUkNACACQYABckGgAUYNAEEAIQEgAhAoRQ0AIAJBLkcgABAqcg8LIAELPQECf0EAIQICQEEAKALcCSIDIABLDQAgAC8BACABRw0AAkAgAyAARw0AQQEPCyAAQX5qLwEAECAhAgsgAgtoAQJ/QQEhAQJAAkAgAEFfaiICQQVLDQBBASACdEExcQ0BCyAAQfj/A3FBKEYNACAAQUZqQf//A3FBBkkNAAJAIABBpX9qIgJBA0sNACACQQFHDQELIABBhX9qQf//A3FBBEkhAQsgAQucAQEDf0EAKAKwCiEBAkADQAJAAkAgAS8BACICQS9HDQACQCABLwECIgFBKkYNACABQS9HDQQQGAwCCyAAEBkMAQsCQAJAIABFDQAgAkF3aiIBQRdLDQFBASABdEGfgIAEcUUNAQwCCyACECFFDQMMAQsgAkGgAUcNAgtBAEEAKAKwCiIDQQJqIgE2ArAKIANBACgCtApJDQALCyACCzEBAX9BACEBAkAgAC8BAEEuRw0AIABBfmovAQBBLkcNACAAQXxqLwEAQS5GIQELIAELnAQBAX8CQCABQSJGDQAgAUEnRg0AECUPC0EAKAKwCiEDIAEQGiAAIANBAmpBACgCsApBACgC0AkQAQJAIAJFDQBBACgC8AlBBDYCHAtBAEEAKAKwCkECajYCsAoCQAJAAkACQEEAECkiAUHhAEYNACABQfcARg0BQQAoArAKIQEMAgtBACgCsAoiAUECakHACEEKEC8NAUEGIQAMAgtBACgCsAoiAS8BAkHpAEcNACABLwEEQfQARw0AQQQhACABLwEGQegARg0BC0EAIAFBfmo2ArAKDwtBACABIABBAXRqNgKwCgJAQQEQKUH7AEYNAEEAIAE2ArAKDwtBACgCsAoiAiEAA0BBACAAQQJqNgKwCgJAAkACQEEBECkiAEEiRg0AIABBJ0cNAUEnEBpBAEEAKAKwCkECajYCsApBARApIQAMAgtBIhAaQQBBACgCsApBAmo2ArAKQQEQKSEADAELIAAQLCEACwJAIABBOkYNAEEAIAE2ArAKDwtBAEEAKAKwCkECajYCsAoCQEEBECkiAEEiRg0AIABBJ0YNAEEAIAE2ArAKDwsgABAaQQBBACgCsApBAmo2ArAKAkACQEEBECkiAEEsRg0AIABB/QBGDQFBACABNgKwCg8LQQBBACgCsApBAmo2ArAKQQEQKUH9AEYNAEEAKAKwCiEADAELC0EAKALwCSIBIAI2AhAgAUEAKAKwCkECajYCDAttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAoDQJBACECQQBBACgCsAoiAEECajYCsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=", typeof Buffer < "u" ? Buffer.from(L, "base64") : Uint8Array.from(atob(L), (A3) => A3.charCodeAt(0)))).then(WebAssembly.instantiate).then(({ exports: A3 }) => {
  12229. Q = A3;
  12230. });
  12231. var L;
  12232. exports2.init = F3, exports2.parse = U;
  12233. }
  12234. });
  12235. // ../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/index-gckBtVBf.cjs
  12236. var require_index_gckBtVBf = __commonJS({
  12237. "../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/index-gckBtVBf.cjs"(exports2) {
  12238. "use strict";
  12239. var Bt = Object.defineProperty;
  12240. var f5 = (s4, e4) => Bt(s4, "name", { value: e4, configurable: true });
  12241. var Ne = require("node:url");
  12242. var ne = require("esbuild");
  12243. var Jt = require("node:crypto");
  12244. var j3 = require("node:fs");
  12245. var X = require("node:path");
  12246. var Gt = require("node:os");
  12247. var zt = require_temporary_directory_B83uKxJF();
  12248. var Ie = f5((s4) => Jt.createHash("sha1").update(s4).digest("hex"), "sha1");
  12249. var Me = 44;
  12250. var Ht = 59;
  12251. var Ue = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  12252. var je = new Uint8Array(64);
  12253. var $e = new Uint8Array(128);
  12254. for (let s4 = 0; s4 < Ue.length; s4++) {
  12255. const e4 = Ue.charCodeAt(s4);
  12256. je[s4] = e4, $e[e4] = s4;
  12257. }
  12258. var ke = typeof TextDecoder < "u" ? new TextDecoder() : typeof Buffer < "u" ? { decode(s4) {
  12259. return Buffer.from(s4.buffer, s4.byteOffset, s4.byteLength).toString();
  12260. } } : { decode(s4) {
  12261. let e4 = "";
  12262. for (let r4 = 0; r4 < s4.length; r4++) e4 += String.fromCharCode(s4[r4]);
  12263. return e4;
  12264. } };
  12265. function Xt(s4) {
  12266. const e4 = new Int32Array(5), r4 = [];
  12267. let i4 = 0;
  12268. do {
  12269. const o3 = Kt(s4, i4), c3 = [];
  12270. let u3 = true, p3 = 0;
  12271. e4[0] = 0;
  12272. for (let g3 = i4; g3 < o3; g3++) {
  12273. let b3;
  12274. g3 = K(s4, g3, e4, 0);
  12275. const d3 = e4[0];
  12276. d3 < p3 && (u3 = false), p3 = d3, De(s4, g3, o3) ? (g3 = K(s4, g3, e4, 1), g3 = K(s4, g3, e4, 2), g3 = K(s4, g3, e4, 3), De(s4, g3, o3) ? (g3 = K(s4, g3, e4, 4), b3 = [d3, e4[1], e4[2], e4[3], e4[4]]) : b3 = [d3, e4[1], e4[2], e4[3]]) : b3 = [d3], c3.push(b3);
  12277. }
  12278. u3 || Yt(c3), r4.push(c3), i4 = o3 + 1;
  12279. } while (i4 <= s4.length);
  12280. return r4;
  12281. }
  12282. f5(Xt, "decode");
  12283. function Kt(s4, e4) {
  12284. const r4 = s4.indexOf(";", e4);
  12285. return r4 === -1 ? s4.length : r4;
  12286. }
  12287. f5(Kt, "indexOf");
  12288. function K(s4, e4, r4, i4) {
  12289. let o3 = 0, c3 = 0, u3 = 0;
  12290. do {
  12291. const g3 = s4.charCodeAt(e4++);
  12292. u3 = $e[g3], o3 |= (u3 & 31) << c3, c3 += 5;
  12293. } while (u3 & 32);
  12294. const p3 = o3 & 1;
  12295. return o3 >>>= 1, p3 && (o3 = -2147483648 | -o3), r4[i4] += o3, e4;
  12296. }
  12297. f5(K, "decodeInteger");
  12298. function De(s4, e4, r4) {
  12299. return e4 >= r4 ? false : s4.charCodeAt(e4) !== Me;
  12300. }
  12301. f5(De, "hasMoreVlq");
  12302. function Yt(s4) {
  12303. s4.sort(Qt);
  12304. }
  12305. f5(Yt, "sort");
  12306. function Qt(s4, e4) {
  12307. return s4[0] - e4[0];
  12308. }
  12309. f5(Qt, "sortComparator$1");
  12310. function Te(s4) {
  12311. const e4 = new Int32Array(5), r4 = 1024 * 16, i4 = r4 - 36, o3 = new Uint8Array(r4), c3 = o3.subarray(0, i4);
  12312. let u3 = 0, p3 = "";
  12313. for (let g3 = 0; g3 < s4.length; g3++) {
  12314. const b3 = s4[g3];
  12315. if (g3 > 0 && (u3 === r4 && (p3 += ke.decode(o3), u3 = 0), o3[u3++] = Ht), b3.length !== 0) {
  12316. e4[0] = 0;
  12317. for (let d3 = 0; d3 < b3.length; d3++) {
  12318. const n3 = b3[d3];
  12319. u3 > i4 && (p3 += ke.decode(c3), o3.copyWithin(0, i4, u3), u3 -= i4), d3 > 0 && (o3[u3++] = Me), u3 = Y(o3, u3, e4, n3, 0), n3.length !== 1 && (u3 = Y(o3, u3, e4, n3, 1), u3 = Y(o3, u3, e4, n3, 2), u3 = Y(o3, u3, e4, n3, 3), n3.length !== 4 && (u3 = Y(o3, u3, e4, n3, 4)));
  12320. }
  12321. }
  12322. }
  12323. return p3 + ke.decode(o3.subarray(0, u3));
  12324. }
  12325. f5(Te, "encode");
  12326. function Y(s4, e4, r4, i4, o3) {
  12327. const c3 = i4[o3];
  12328. let u3 = c3 - r4[o3];
  12329. r4[o3] = c3, u3 = u3 < 0 ? -u3 << 1 | 1 : u3 << 1;
  12330. do {
  12331. let p3 = u3 & 31;
  12332. u3 >>>= 5, u3 > 0 && (p3 |= 32), s4[e4++] = je[p3];
  12333. } while (u3 > 0);
  12334. return e4;
  12335. }
  12336. f5(Y, "encodeInteger");
  12337. var _ce = class _ce {
  12338. constructor(e4) {
  12339. this.bits = e4 instanceof _ce ? e4.bits.slice() : [];
  12340. }
  12341. add(e4) {
  12342. this.bits[e4 >> 5] |= 1 << (e4 & 31);
  12343. }
  12344. has(e4) {
  12345. return !!(this.bits[e4 >> 5] & 1 << (e4 & 31));
  12346. }
  12347. };
  12348. f5(_ce, "BitSet");
  12349. var ce = _ce;
  12350. var _ee = class _ee {
  12351. constructor(e4, r4, i4) {
  12352. this.start = e4, this.end = r4, this.original = i4, this.intro = "", this.outro = "", this.content = i4, this.storeName = false, this.edited = false, this.previous = null, this.next = null;
  12353. }
  12354. appendLeft(e4) {
  12355. this.outro += e4;
  12356. }
  12357. appendRight(e4) {
  12358. this.intro = this.intro + e4;
  12359. }
  12360. clone() {
  12361. const e4 = new _ee(this.start, this.end, this.original);
  12362. return e4.intro = this.intro, e4.outro = this.outro, e4.content = this.content, e4.storeName = this.storeName, e4.edited = this.edited, e4;
  12363. }
  12364. contains(e4) {
  12365. return this.start < e4 && e4 < this.end;
  12366. }
  12367. eachNext(e4) {
  12368. let r4 = this;
  12369. for (; r4; ) e4(r4), r4 = r4.next;
  12370. }
  12371. eachPrevious(e4) {
  12372. let r4 = this;
  12373. for (; r4; ) e4(r4), r4 = r4.previous;
  12374. }
  12375. edit(e4, r4, i4) {
  12376. return this.content = e4, i4 || (this.intro = "", this.outro = ""), this.storeName = r4, this.edited = true, this;
  12377. }
  12378. prependLeft(e4) {
  12379. this.outro = e4 + this.outro;
  12380. }
  12381. prependRight(e4) {
  12382. this.intro = e4 + this.intro;
  12383. }
  12384. reset() {
  12385. this.intro = "", this.outro = "", this.edited && (this.content = this.original, this.storeName = false, this.edited = false);
  12386. }
  12387. split(e4) {
  12388. const r4 = e4 - this.start, i4 = this.original.slice(0, r4), o3 = this.original.slice(r4);
  12389. this.original = i4;
  12390. const c3 = new _ee(e4, this.end, o3);
  12391. return c3.outro = this.outro, this.outro = "", this.end = e4, this.edited ? (c3.edit("", false), this.content = "") : this.content = i4, c3.next = this.next, c3.next && (c3.next.previous = c3), c3.previous = this, this.next = c3, c3;
  12392. }
  12393. toString() {
  12394. return this.intro + this.content + this.outro;
  12395. }
  12396. trimEnd(e4) {
  12397. if (this.outro = this.outro.replace(e4, ""), this.outro.length) return true;
  12398. const r4 = this.content.replace(e4, "");
  12399. if (r4.length) return r4 !== this.content && (this.split(this.start + r4.length).edit("", void 0, true), this.edited && this.edit(r4, this.storeName, true)), true;
  12400. if (this.edit("", void 0, true), this.intro = this.intro.replace(e4, ""), this.intro.length) return true;
  12401. }
  12402. trimStart(e4) {
  12403. if (this.intro = this.intro.replace(e4, ""), this.intro.length) return true;
  12404. const r4 = this.content.replace(e4, "");
  12405. if (r4.length) {
  12406. if (r4 !== this.content) {
  12407. const i4 = this.split(this.end - r4.length);
  12408. this.edited && i4.edit(r4, this.storeName, true), this.edit("", void 0, true);
  12409. }
  12410. return true;
  12411. } else if (this.edit("", void 0, true), this.outro = this.outro.replace(e4, ""), this.outro.length) return true;
  12412. }
  12413. };
  12414. f5(_ee, "Chunk");
  12415. var ee = _ee;
  12416. function Zt() {
  12417. return typeof globalThis < "u" && typeof globalThis.btoa == "function" ? (s4) => globalThis.btoa(unescape(encodeURIComponent(s4))) : typeof Buffer == "function" ? (s4) => Buffer.from(s4, "utf-8").toString("base64") : () => {
  12418. throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
  12419. };
  12420. }
  12421. f5(Zt, "getBtoa");
  12422. var Vt = Zt();
  12423. var _a2;
  12424. var er = (_a2 = class {
  12425. constructor(e4) {
  12426. this.version = 3, this.file = e4.file, this.sources = e4.sources, this.sourcesContent = e4.sourcesContent, this.names = e4.names, this.mappings = Te(e4.mappings), typeof e4.x_google_ignoreList < "u" && (this.x_google_ignoreList = e4.x_google_ignoreList);
  12427. }
  12428. toString() {
  12429. return JSON.stringify(this);
  12430. }
  12431. toUrl() {
  12432. return "data:application/json;charset=utf-8;base64," + Vt(this.toString());
  12433. }
  12434. }, f5(_a2, "SourceMap"), _a2);
  12435. function tr(s4) {
  12436. const e4 = s4.split(`
  12437. `), r4 = e4.filter((c3) => /^\t+/.test(c3)), i4 = e4.filter((c3) => /^ {2,}/.test(c3));
  12438. if (r4.length === 0 && i4.length === 0) return null;
  12439. if (r4.length >= i4.length) return " ";
  12440. const o3 = i4.reduce((c3, u3) => {
  12441. const p3 = /^ +/.exec(u3)[0].length;
  12442. return Math.min(p3, c3);
  12443. }, 1 / 0);
  12444. return new Array(o3 + 1).join(" ");
  12445. }
  12446. f5(tr, "guessIndent");
  12447. function rr(s4, e4) {
  12448. const r4 = s4.split(/[/\\]/), i4 = e4.split(/[/\\]/);
  12449. for (r4.pop(); r4[0] === i4[0]; ) r4.shift(), i4.shift();
  12450. if (r4.length) {
  12451. let o3 = r4.length;
  12452. for (; o3--; ) r4[o3] = "..";
  12453. }
  12454. return r4.concat(i4).join("/");
  12455. }
  12456. f5(rr, "getRelativePath");
  12457. var nr = Object.prototype.toString;
  12458. function ir(s4) {
  12459. return nr.call(s4) === "[object Object]";
  12460. }
  12461. f5(ir, "isObject");
  12462. function Fe(s4) {
  12463. const e4 = s4.split(`
  12464. `), r4 = [];
  12465. for (let i4 = 0, o3 = 0; i4 < e4.length; i4++) r4.push(o3), o3 += e4[i4].length + 1;
  12466. return f5(function(o3) {
  12467. let c3 = 0, u3 = r4.length;
  12468. for (; c3 < u3; ) {
  12469. const b3 = c3 + u3 >> 1;
  12470. o3 < r4[b3] ? u3 = b3 : c3 = b3 + 1;
  12471. }
  12472. const p3 = c3 - 1, g3 = o3 - r4[p3];
  12473. return { line: p3, column: g3 };
  12474. }, "locate");
  12475. }
  12476. f5(Fe, "getLocator");
  12477. var sr = /\w/;
  12478. var _or = class _or {
  12479. constructor(e4) {
  12480. this.hires = e4, this.generatedCodeLine = 0, this.generatedCodeColumn = 0, this.raw = [], this.rawSegments = this.raw[this.generatedCodeLine] = [], this.pending = null;
  12481. }
  12482. addEdit(e4, r4, i4, o3) {
  12483. if (r4.length) {
  12484. const c3 = r4.length - 1;
  12485. let u3 = r4.indexOf(`
  12486. `, 0), p3 = -1;
  12487. for (; u3 >= 0 && c3 > u3; ) {
  12488. const b3 = [this.generatedCodeColumn, e4, i4.line, i4.column];
  12489. o3 >= 0 && b3.push(o3), this.rawSegments.push(b3), this.generatedCodeLine += 1, this.raw[this.generatedCodeLine] = this.rawSegments = [], this.generatedCodeColumn = 0, p3 = u3, u3 = r4.indexOf(`
  12490. `, u3 + 1);
  12491. }
  12492. const g3 = [this.generatedCodeColumn, e4, i4.line, i4.column];
  12493. o3 >= 0 && g3.push(o3), this.rawSegments.push(g3), this.advance(r4.slice(p3 + 1));
  12494. } else this.pending && (this.rawSegments.push(this.pending), this.advance(r4));
  12495. this.pending = null;
  12496. }
  12497. addUneditedChunk(e4, r4, i4, o3, c3) {
  12498. let u3 = r4.start, p3 = true, g3 = false;
  12499. for (; u3 < r4.end; ) {
  12500. if (this.hires || p3 || c3.has(u3)) {
  12501. const b3 = [this.generatedCodeColumn, e4, o3.line, o3.column];
  12502. this.hires === "boundary" ? sr.test(i4[u3]) ? g3 || (this.rawSegments.push(b3), g3 = true) : (this.rawSegments.push(b3), g3 = false) : this.rawSegments.push(b3);
  12503. }
  12504. i4[u3] === `
  12505. ` ? (o3.line += 1, o3.column = 0, this.generatedCodeLine += 1, this.raw[this.generatedCodeLine] = this.rawSegments = [], this.generatedCodeColumn = 0, p3 = true) : (o3.column += 1, this.generatedCodeColumn += 1, p3 = false), u3 += 1;
  12506. }
  12507. this.pending = null;
  12508. }
  12509. advance(e4) {
  12510. if (!e4) return;
  12511. const r4 = e4.split(`
  12512. `);
  12513. if (r4.length > 1) {
  12514. for (let i4 = 0; i4 < r4.length - 1; i4++) this.generatedCodeLine++, this.raw[this.generatedCodeLine] = this.rawSegments = [];
  12515. this.generatedCodeColumn = 0;
  12516. }
  12517. this.generatedCodeColumn += r4[r4.length - 1].length;
  12518. }
  12519. };
  12520. f5(_or, "Mappings");
  12521. var or = _or;
  12522. var Q = `
  12523. `;
  12524. var B2 = { insertLeft: false, insertRight: false, storeName: false };
  12525. var _Ee = class _Ee {
  12526. constructor(e4, r4 = {}) {
  12527. const i4 = new ee(0, e4.length, e4);
  12528. Object.defineProperties(this, { original: { writable: true, value: e4 }, outro: { writable: true, value: "" }, intro: { writable: true, value: "" }, firstChunk: { writable: true, value: i4 }, lastChunk: { writable: true, value: i4 }, lastSearchedChunk: { writable: true, value: i4 }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: r4.filename }, indentExclusionRanges: { writable: true, value: r4.indentExclusionRanges }, sourcemapLocations: { writable: true, value: new ce() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: void 0 }, ignoreList: { writable: true, value: r4.ignoreList } }), this.byStart[0] = i4, this.byEnd[e4.length] = i4;
  12529. }
  12530. addSourcemapLocation(e4) {
  12531. this.sourcemapLocations.add(e4);
  12532. }
  12533. append(e4) {
  12534. if (typeof e4 != "string") throw new TypeError("outro content must be a string");
  12535. return this.outro += e4, this;
  12536. }
  12537. appendLeft(e4, r4) {
  12538. if (typeof r4 != "string") throw new TypeError("inserted content must be a string");
  12539. this._split(e4);
  12540. const i4 = this.byEnd[e4];
  12541. return i4 ? i4.appendLeft(r4) : this.intro += r4, this;
  12542. }
  12543. appendRight(e4, r4) {
  12544. if (typeof r4 != "string") throw new TypeError("inserted content must be a string");
  12545. this._split(e4);
  12546. const i4 = this.byStart[e4];
  12547. return i4 ? i4.appendRight(r4) : this.outro += r4, this;
  12548. }
  12549. clone() {
  12550. const e4 = new _Ee(this.original, { filename: this.filename });
  12551. let r4 = this.firstChunk, i4 = e4.firstChunk = e4.lastSearchedChunk = r4.clone();
  12552. for (; r4; ) {
  12553. e4.byStart[i4.start] = i4, e4.byEnd[i4.end] = i4;
  12554. const o3 = r4.next, c3 = o3 && o3.clone();
  12555. c3 && (i4.next = c3, c3.previous = i4, i4 = c3), r4 = o3;
  12556. }
  12557. return e4.lastChunk = i4, this.indentExclusionRanges && (e4.indentExclusionRanges = this.indentExclusionRanges.slice()), e4.sourcemapLocations = new ce(this.sourcemapLocations), e4.intro = this.intro, e4.outro = this.outro, e4;
  12558. }
  12559. generateDecodedMap(e4) {
  12560. e4 = e4 || {};
  12561. const r4 = 0, i4 = Object.keys(this.storedNames), o3 = new or(e4.hires), c3 = Fe(this.original);
  12562. return this.intro && o3.advance(this.intro), this.firstChunk.eachNext((u3) => {
  12563. const p3 = c3(u3.start);
  12564. u3.intro.length && o3.advance(u3.intro), u3.edited ? o3.addEdit(r4, u3.content, p3, u3.storeName ? i4.indexOf(u3.original) : -1) : o3.addUneditedChunk(r4, u3, this.original, p3, this.sourcemapLocations), u3.outro.length && o3.advance(u3.outro);
  12565. }), { file: e4.file ? e4.file.split(/[/\\]/).pop() : void 0, sources: [e4.source ? rr(e4.file || "", e4.source) : e4.file || ""], sourcesContent: e4.includeContent ? [this.original] : void 0, names: i4, mappings: o3.raw, x_google_ignoreList: this.ignoreList ? [r4] : void 0 };
  12566. }
  12567. generateMap(e4) {
  12568. return new er(this.generateDecodedMap(e4));
  12569. }
  12570. _ensureindentStr() {
  12571. this.indentStr === void 0 && (this.indentStr = tr(this.original));
  12572. }
  12573. _getRawIndentString() {
  12574. return this._ensureindentStr(), this.indentStr;
  12575. }
  12576. getIndentString() {
  12577. return this._ensureindentStr(), this.indentStr === null ? " " : this.indentStr;
  12578. }
  12579. indent(e4, r4) {
  12580. const i4 = /^[^\r\n]/gm;
  12581. if (ir(e4) && (r4 = e4, e4 = void 0), e4 === void 0 && (this._ensureindentStr(), e4 = this.indentStr || " "), e4 === "") return this;
  12582. r4 = r4 || {};
  12583. const o3 = {};
  12584. r4.exclude && (typeof r4.exclude[0] == "number" ? [r4.exclude] : r4.exclude).forEach((d3) => {
  12585. for (let n3 = d3[0]; n3 < d3[1]; n3 += 1) o3[n3] = true;
  12586. });
  12587. let c3 = r4.indentStart !== false;
  12588. const u3 = f5((b3) => c3 ? `${e4}${b3}` : (c3 = true, b3), "replacer");
  12589. this.intro = this.intro.replace(i4, u3);
  12590. let p3 = 0, g3 = this.firstChunk;
  12591. for (; g3; ) {
  12592. const b3 = g3.end;
  12593. if (g3.edited) o3[p3] || (g3.content = g3.content.replace(i4, u3), g3.content.length && (c3 = g3.content[g3.content.length - 1] === `
  12594. `));
  12595. else for (p3 = g3.start; p3 < b3; ) {
  12596. if (!o3[p3]) {
  12597. const d3 = this.original[p3];
  12598. d3 === `
  12599. ` ? c3 = true : d3 !== "\r" && c3 && (c3 = false, p3 === g3.start || (this._splitChunk(g3, p3), g3 = g3.next), g3.prependRight(e4));
  12600. }
  12601. p3 += 1;
  12602. }
  12603. p3 = g3.end, g3 = g3.next;
  12604. }
  12605. return this.outro = this.outro.replace(i4, u3), this;
  12606. }
  12607. insert() {
  12608. throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
  12609. }
  12610. insertLeft(e4, r4) {
  12611. return B2.insertLeft || (console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"), B2.insertLeft = true), this.appendLeft(e4, r4);
  12612. }
  12613. insertRight(e4, r4) {
  12614. return B2.insertRight || (console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"), B2.insertRight = true), this.prependRight(e4, r4);
  12615. }
  12616. move(e4, r4, i4) {
  12617. if (i4 >= e4 && i4 <= r4) throw new Error("Cannot move a selection inside itself");
  12618. this._split(e4), this._split(r4), this._split(i4);
  12619. const o3 = this.byStart[e4], c3 = this.byEnd[r4], u3 = o3.previous, p3 = c3.next, g3 = this.byStart[i4];
  12620. if (!g3 && c3 === this.lastChunk) return this;
  12621. const b3 = g3 ? g3.previous : this.lastChunk;
  12622. return u3 && (u3.next = p3), p3 && (p3.previous = u3), b3 && (b3.next = o3), g3 && (g3.previous = c3), o3.previous || (this.firstChunk = c3.next), c3.next || (this.lastChunk = o3.previous, this.lastChunk.next = null), o3.previous = b3, c3.next = g3 || null, b3 || (this.firstChunk = o3), g3 || (this.lastChunk = c3), this;
  12623. }
  12624. overwrite(e4, r4, i4, o3) {
  12625. return o3 = o3 || {}, this.update(e4, r4, i4, { ...o3, overwrite: !o3.contentOnly });
  12626. }
  12627. update(e4, r4, i4, o3) {
  12628. if (typeof i4 != "string") throw new TypeError("replacement content must be a string");
  12629. for (; e4 < 0; ) e4 += this.original.length;
  12630. for (; r4 < 0; ) r4 += this.original.length;
  12631. if (r4 > this.original.length) throw new Error("end is out of bounds");
  12632. if (e4 === r4) throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");
  12633. this._split(e4), this._split(r4), o3 === true && (B2.storeName || (console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"), B2.storeName = true), o3 = { storeName: true });
  12634. const c3 = o3 !== void 0 ? o3.storeName : false, u3 = o3 !== void 0 ? o3.overwrite : false;
  12635. if (c3) {
  12636. const b3 = this.original.slice(e4, r4);
  12637. Object.defineProperty(this.storedNames, b3, { writable: true, value: true, enumerable: true });
  12638. }
  12639. const p3 = this.byStart[e4], g3 = this.byEnd[r4];
  12640. if (p3) {
  12641. let b3 = p3;
  12642. for (; b3 !== g3; ) {
  12643. if (b3.next !== this.byStart[b3.end]) throw new Error("Cannot overwrite across a split point");
  12644. b3 = b3.next, b3.edit("", false);
  12645. }
  12646. p3.edit(i4, c3, !u3);
  12647. } else {
  12648. const b3 = new ee(e4, r4, "").edit(i4, c3);
  12649. g3.next = b3, b3.previous = g3;
  12650. }
  12651. return this;
  12652. }
  12653. prepend(e4) {
  12654. if (typeof e4 != "string") throw new TypeError("outro content must be a string");
  12655. return this.intro = e4 + this.intro, this;
  12656. }
  12657. prependLeft(e4, r4) {
  12658. if (typeof r4 != "string") throw new TypeError("inserted content must be a string");
  12659. this._split(e4);
  12660. const i4 = this.byEnd[e4];
  12661. return i4 ? i4.prependLeft(r4) : this.intro = r4 + this.intro, this;
  12662. }
  12663. prependRight(e4, r4) {
  12664. if (typeof r4 != "string") throw new TypeError("inserted content must be a string");
  12665. this._split(e4);
  12666. const i4 = this.byStart[e4];
  12667. return i4 ? i4.prependRight(r4) : this.outro = r4 + this.outro, this;
  12668. }
  12669. remove(e4, r4) {
  12670. for (; e4 < 0; ) e4 += this.original.length;
  12671. for (; r4 < 0; ) r4 += this.original.length;
  12672. if (e4 === r4) return this;
  12673. if (e4 < 0 || r4 > this.original.length) throw new Error("Character is out of bounds");
  12674. if (e4 > r4) throw new Error("end must be greater than start");
  12675. this._split(e4), this._split(r4);
  12676. let i4 = this.byStart[e4];
  12677. for (; i4; ) i4.intro = "", i4.outro = "", i4.edit(""), i4 = r4 > i4.end ? this.byStart[i4.end] : null;
  12678. return this;
  12679. }
  12680. reset(e4, r4) {
  12681. for (; e4 < 0; ) e4 += this.original.length;
  12682. for (; r4 < 0; ) r4 += this.original.length;
  12683. if (e4 === r4) return this;
  12684. if (e4 < 0 || r4 > this.original.length) throw new Error("Character is out of bounds");
  12685. if (e4 > r4) throw new Error("end must be greater than start");
  12686. this._split(e4), this._split(r4);
  12687. let i4 = this.byStart[e4];
  12688. for (; i4; ) i4.reset(), i4 = r4 > i4.end ? this.byStart[i4.end] : null;
  12689. return this;
  12690. }
  12691. lastChar() {
  12692. if (this.outro.length) return this.outro[this.outro.length - 1];
  12693. let e4 = this.lastChunk;
  12694. do {
  12695. if (e4.outro.length) return e4.outro[e4.outro.length - 1];
  12696. if (e4.content.length) return e4.content[e4.content.length - 1];
  12697. if (e4.intro.length) return e4.intro[e4.intro.length - 1];
  12698. } while (e4 = e4.previous);
  12699. return this.intro.length ? this.intro[this.intro.length - 1] : "";
  12700. }
  12701. lastLine() {
  12702. let e4 = this.outro.lastIndexOf(Q);
  12703. if (e4 !== -1) return this.outro.substr(e4 + 1);
  12704. let r4 = this.outro, i4 = this.lastChunk;
  12705. do {
  12706. if (i4.outro.length > 0) {
  12707. if (e4 = i4.outro.lastIndexOf(Q), e4 !== -1) return i4.outro.substr(e4 + 1) + r4;
  12708. r4 = i4.outro + r4;
  12709. }
  12710. if (i4.content.length > 0) {
  12711. if (e4 = i4.content.lastIndexOf(Q), e4 !== -1) return i4.content.substr(e4 + 1) + r4;
  12712. r4 = i4.content + r4;
  12713. }
  12714. if (i4.intro.length > 0) {
  12715. if (e4 = i4.intro.lastIndexOf(Q), e4 !== -1) return i4.intro.substr(e4 + 1) + r4;
  12716. r4 = i4.intro + r4;
  12717. }
  12718. } while (i4 = i4.previous);
  12719. return e4 = this.intro.lastIndexOf(Q), e4 !== -1 ? this.intro.substr(e4 + 1) + r4 : this.intro + r4;
  12720. }
  12721. slice(e4 = 0, r4 = this.original.length) {
  12722. for (; e4 < 0; ) e4 += this.original.length;
  12723. for (; r4 < 0; ) r4 += this.original.length;
  12724. let i4 = "", o3 = this.firstChunk;
  12725. for (; o3 && (o3.start > e4 || o3.end <= e4); ) {
  12726. if (o3.start < r4 && o3.end >= r4) return i4;
  12727. o3 = o3.next;
  12728. }
  12729. if (o3 && o3.edited && o3.start !== e4) throw new Error(`Cannot use replaced character ${e4} as slice start anchor.`);
  12730. const c3 = o3;
  12731. for (; o3; ) {
  12732. o3.intro && (c3 !== o3 || o3.start === e4) && (i4 += o3.intro);
  12733. const u3 = o3.start < r4 && o3.end >= r4;
  12734. if (u3 && o3.edited && o3.end !== r4) throw new Error(`Cannot use replaced character ${r4} as slice end anchor.`);
  12735. const p3 = c3 === o3 ? e4 - o3.start : 0, g3 = u3 ? o3.content.length + r4 - o3.end : o3.content.length;
  12736. if (i4 += o3.content.slice(p3, g3), o3.outro && (!u3 || o3.end === r4) && (i4 += o3.outro), u3) break;
  12737. o3 = o3.next;
  12738. }
  12739. return i4;
  12740. }
  12741. snip(e4, r4) {
  12742. const i4 = this.clone();
  12743. return i4.remove(0, e4), i4.remove(r4, i4.original.length), i4;
  12744. }
  12745. _split(e4) {
  12746. if (this.byStart[e4] || this.byEnd[e4]) return;
  12747. let r4 = this.lastSearchedChunk;
  12748. const i4 = e4 > r4.end;
  12749. for (; r4; ) {
  12750. if (r4.contains(e4)) return this._splitChunk(r4, e4);
  12751. r4 = i4 ? this.byStart[r4.end] : this.byEnd[r4.start];
  12752. }
  12753. }
  12754. _splitChunk(e4, r4) {
  12755. if (e4.edited && e4.content.length) {
  12756. const o3 = Fe(this.original)(r4);
  12757. throw new Error(`Cannot split a chunk that has already been edited (${o3.line}:${o3.column} \u2013 "${e4.original}")`);
  12758. }
  12759. const i4 = e4.split(r4);
  12760. return this.byEnd[r4] = e4, this.byStart[r4] = i4, this.byEnd[i4.end] = i4, e4 === this.lastChunk && (this.lastChunk = i4), this.lastSearchedChunk = e4, true;
  12761. }
  12762. toString() {
  12763. let e4 = this.intro, r4 = this.firstChunk;
  12764. for (; r4; ) e4 += r4.toString(), r4 = r4.next;
  12765. return e4 + this.outro;
  12766. }
  12767. isEmpty() {
  12768. let e4 = this.firstChunk;
  12769. do
  12770. if (e4.intro.length && e4.intro.trim() || e4.content.length && e4.content.trim() || e4.outro.length && e4.outro.trim()) return false;
  12771. while (e4 = e4.next);
  12772. return true;
  12773. }
  12774. length() {
  12775. let e4 = this.firstChunk, r4 = 0;
  12776. do
  12777. r4 += e4.intro.length + e4.content.length + e4.outro.length;
  12778. while (e4 = e4.next);
  12779. return r4;
  12780. }
  12781. trimLines() {
  12782. return this.trim("[\\r\\n]");
  12783. }
  12784. trim(e4) {
  12785. return this.trimStart(e4).trimEnd(e4);
  12786. }
  12787. trimEndAborted(e4) {
  12788. const r4 = new RegExp((e4 || "\\s") + "+$");
  12789. if (this.outro = this.outro.replace(r4, ""), this.outro.length) return true;
  12790. let i4 = this.lastChunk;
  12791. do {
  12792. const o3 = i4.end, c3 = i4.trimEnd(r4);
  12793. if (i4.end !== o3 && (this.lastChunk === i4 && (this.lastChunk = i4.next), this.byEnd[i4.end] = i4, this.byStart[i4.next.start] = i4.next, this.byEnd[i4.next.end] = i4.next), c3) return true;
  12794. i4 = i4.previous;
  12795. } while (i4);
  12796. return false;
  12797. }
  12798. trimEnd(e4) {
  12799. return this.trimEndAborted(e4), this;
  12800. }
  12801. trimStartAborted(e4) {
  12802. const r4 = new RegExp("^" + (e4 || "\\s") + "+");
  12803. if (this.intro = this.intro.replace(r4, ""), this.intro.length) return true;
  12804. let i4 = this.firstChunk;
  12805. do {
  12806. const o3 = i4.end, c3 = i4.trimStart(r4);
  12807. if (i4.end !== o3 && (i4 === this.lastChunk && (this.lastChunk = i4.next), this.byEnd[i4.end] = i4, this.byStart[i4.next.start] = i4.next, this.byEnd[i4.next.end] = i4.next), c3) return true;
  12808. i4 = i4.next;
  12809. } while (i4);
  12810. return false;
  12811. }
  12812. trimStart(e4) {
  12813. return this.trimStartAborted(e4), this;
  12814. }
  12815. hasChanged() {
  12816. return this.original !== this.toString();
  12817. }
  12818. _replaceRegexp(e4, r4) {
  12819. function i4(c3, u3) {
  12820. return typeof r4 == "string" ? r4.replace(/\$(\$|&|\d+)/g, (p3, g3) => g3 === "$" ? "$" : g3 === "&" ? c3[0] : +g3 < c3.length ? c3[+g3] : `$${g3}`) : r4(...c3, c3.index, u3, c3.groups);
  12821. }
  12822. f5(i4, "getReplacement");
  12823. function o3(c3, u3) {
  12824. let p3;
  12825. const g3 = [];
  12826. for (; p3 = c3.exec(u3); ) g3.push(p3);
  12827. return g3;
  12828. }
  12829. if (f5(o3, "matchAll"), e4.global) o3(e4, this.original).forEach((u3) => {
  12830. if (u3.index != null) {
  12831. const p3 = i4(u3, this.original);
  12832. p3 !== u3[0] && this.overwrite(u3.index, u3.index + u3[0].length, p3);
  12833. }
  12834. });
  12835. else {
  12836. const c3 = this.original.match(e4);
  12837. if (c3 && c3.index != null) {
  12838. const u3 = i4(c3, this.original);
  12839. u3 !== c3[0] && this.overwrite(c3.index, c3.index + c3[0].length, u3);
  12840. }
  12841. }
  12842. return this;
  12843. }
  12844. _replaceString(e4, r4) {
  12845. const { original: i4 } = this, o3 = i4.indexOf(e4);
  12846. return o3 !== -1 && this.overwrite(o3, o3 + e4.length, r4), this;
  12847. }
  12848. replace(e4, r4) {
  12849. return typeof e4 == "string" ? this._replaceString(e4, r4) : this._replaceRegexp(e4, r4);
  12850. }
  12851. _replaceAllString(e4, r4) {
  12852. const { original: i4 } = this, o3 = e4.length;
  12853. for (let c3 = i4.indexOf(e4); c3 !== -1; c3 = i4.indexOf(e4, c3 + o3)) i4.slice(c3, c3 + o3) !== r4 && this.overwrite(c3, c3 + o3, r4);
  12854. return this;
  12855. }
  12856. replaceAll(e4, r4) {
  12857. if (typeof e4 == "string") return this._replaceAllString(e4, r4);
  12858. if (!e4.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
  12859. return this._replaceRegexp(e4, r4);
  12860. }
  12861. };
  12862. f5(_Ee, "MagicString");
  12863. var Ee = _Ee;
  12864. var x4;
  12865. var ie;
  12866. var ye;
  12867. var Z2 = 2 << 19;
  12868. var Pe = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1 ? function(s4, e4) {
  12869. const r4 = s4.length;
  12870. let i4 = 0;
  12871. for (; i4 < r4; ) e4[i4] = s4.charCodeAt(i4++);
  12872. } : function(s4, e4) {
  12873. const r4 = s4.length;
  12874. let i4 = 0;
  12875. for (; i4 < r4; ) {
  12876. const o3 = s4.charCodeAt(i4);
  12877. e4[i4++] = (255 & o3) << 8 | o3 >>> 8;
  12878. }
  12879. };
  12880. var ar = "xportmportlassforetaourceromsyncunctionssertvoyiedelecontininstantybreareturdebuggeawaithrwhileifcatcfinallels";
  12881. var _3;
  12882. var We;
  12883. var y2;
  12884. function cr(s4, e4 = "@") {
  12885. _3 = s4, We = e4;
  12886. const r4 = 2 * _3.length + (2 << 18);
  12887. if (r4 > Z2 || !x4) {
  12888. for (; r4 > Z2; ) Z2 *= 2;
  12889. ie = new ArrayBuffer(Z2), Pe(ar, new Uint16Array(ie, 16, 110)), x4 = function(u3, p3, g3) {
  12890. var b3 = new u3.Int8Array(g3), d3 = new u3.Int16Array(g3), n3 = new u3.Int32Array(g3), R = new u3.Uint8Array(g3), L = new u3.Uint16Array(g3), E2 = 1040;
  12891. function N() {
  12892. var t4 = 0, a3 = 0, h4 = 0, l3 = 0, w3 = 0, m4 = 0, C2 = 0;
  12893. C2 = E2, E2 = E2 + 10240 | 0, b3[804] = 1, b3[803] = 0, d3[399] = 0, d3[400] = 0, n3[69] = n3[2], b3[805] = 0, n3[68] = 0, b3[802] = 0, n3[70] = C2 + 2048, n3[71] = C2, b3[806] = 0, t4 = (n3[3] | 0) + -2 | 0, n3[72] = t4, a3 = t4 + (n3[66] << 1) | 0, n3[73] = a3;
  12894. e: for (; ; ) {
  12895. if (h4 = t4 + 2 | 0, n3[72] = h4, t4 >>> 0 >= a3 >>> 0) {
  12896. l3 = 18;
  12897. break;
  12898. }
  12899. t: do
  12900. switch (d3[h4 >> 1] | 0) {
  12901. case 9:
  12902. case 10:
  12903. case 11:
  12904. case 12:
  12905. case 13:
  12906. case 32:
  12907. break;
  12908. case 101: {
  12909. if (!(d3[400] | 0) && z2(h4) | 0 && !(A3(t4 + 4 | 0, 16, 10) | 0) && (U(), (b3[804] | 0) == 0)) {
  12910. l3 = 9;
  12911. break e;
  12912. } else l3 = 17;
  12913. break;
  12914. }
  12915. case 105: {
  12916. z2(h4) | 0 && !(A3(t4 + 4 | 0, 26, 10) | 0) && P(), l3 = 17;
  12917. break;
  12918. }
  12919. case 59: {
  12920. l3 = 17;
  12921. break;
  12922. }
  12923. case 47:
  12924. switch (d3[t4 + 4 >> 1] | 0) {
  12925. case 47: {
  12926. de();
  12927. break t;
  12928. }
  12929. case 42: {
  12930. he(1);
  12931. break t;
  12932. }
  12933. default: {
  12934. l3 = 16;
  12935. break e;
  12936. }
  12937. }
  12938. default: {
  12939. l3 = 16;
  12940. break e;
  12941. }
  12942. }
  12943. while (false);
  12944. (l3 | 0) == 17 && (l3 = 0, n3[69] = n3[72]), t4 = n3[72] | 0, a3 = n3[73] | 0;
  12945. }
  12946. (l3 | 0) == 9 ? (t4 = n3[72] | 0, n3[69] = t4, l3 = 19) : (l3 | 0) == 16 ? (b3[804] = 0, n3[72] = t4, l3 = 19) : (l3 | 0) == 18 && (b3[802] | 0 ? t4 = 0 : (t4 = h4, l3 = 19));
  12947. do
  12948. if ((l3 | 0) == 19) {
  12949. e: for (; ; ) {
  12950. if (a3 = t4 + 2 | 0, n3[72] = a3, t4 >>> 0 >= (n3[73] | 0) >>> 0) {
  12951. l3 = 92;
  12952. break;
  12953. }
  12954. t: do
  12955. switch (d3[a3 >> 1] | 0) {
  12956. case 9:
  12957. case 10:
  12958. case 11:
  12959. case 12:
  12960. case 13:
  12961. case 32:
  12962. break;
  12963. case 101: {
  12964. !(d3[400] | 0) && z2(a3) | 0 && !(A3(t4 + 4 | 0, 16, 10) | 0) && U(), l3 = 91;
  12965. break;
  12966. }
  12967. case 105: {
  12968. z2(a3) | 0 && !(A3(t4 + 4 | 0, 26, 10) | 0) && P(), l3 = 91;
  12969. break;
  12970. }
  12971. case 99: {
  12972. z2(a3) | 0 && !(A3(t4 + 4 | 0, 36, 8) | 0) && q3(d3[t4 + 12 >> 1] | 0) | 0 && (b3[806] = 1), l3 = 91;
  12973. break;
  12974. }
  12975. case 40: {
  12976. h4 = n3[70] | 0, t4 = d3[400] | 0, l3 = t4 & 65535, n3[h4 + (l3 << 3) >> 2] = 1, a3 = n3[69] | 0, d3[400] = t4 + 1 << 16 >> 16, n3[h4 + (l3 << 3) + 4 >> 2] = a3, l3 = 91;
  12977. break;
  12978. }
  12979. case 41: {
  12980. if (a3 = d3[400] | 0, !(a3 << 16 >> 16)) {
  12981. l3 = 36;
  12982. break e;
  12983. }
  12984. h4 = a3 + -1 << 16 >> 16, d3[400] = h4, l3 = d3[399] | 0, a3 = l3 & 65535, l3 << 16 >> 16 && (n3[(n3[70] | 0) + ((h4 & 65535) << 3) >> 2] | 0) == 5 && (a3 = n3[(n3[71] | 0) + (a3 + -1 << 2) >> 2] | 0, h4 = a3 + 4 | 0, n3[h4 >> 2] | 0 || (n3[h4 >> 2] = (n3[69] | 0) + 2), n3[a3 + 12 >> 2] = t4 + 4, d3[399] = l3 + -1 << 16 >> 16), l3 = 91;
  12985. break;
  12986. }
  12987. case 123: {
  12988. l3 = n3[69] | 0, h4 = n3[63] | 0, t4 = l3;
  12989. do
  12990. if ((d3[l3 >> 1] | 0) == 41 & (h4 | 0) != 0 && (n3[h4 + 4 >> 2] | 0) == (l3 | 0)) if (a3 = n3[64] | 0, n3[63] = a3, a3) {
  12991. n3[a3 + 32 >> 2] = 0;
  12992. break;
  12993. } else {
  12994. n3[59] = 0;
  12995. break;
  12996. }
  12997. while (false);
  12998. h4 = n3[70] | 0, a3 = d3[400] | 0, l3 = a3 & 65535, n3[h4 + (l3 << 3) >> 2] = b3[806] | 0 ? 6 : 2, d3[400] = a3 + 1 << 16 >> 16, n3[h4 + (l3 << 3) + 4 >> 2] = t4, b3[806] = 0, l3 = 91;
  12999. break;
  13000. }
  13001. case 125: {
  13002. if (t4 = d3[400] | 0, !(t4 << 16 >> 16)) {
  13003. l3 = 49;
  13004. break e;
  13005. }
  13006. h4 = n3[70] | 0, l3 = t4 + -1 << 16 >> 16, d3[400] = l3, (n3[h4 + ((l3 & 65535) << 3) >> 2] | 0) == 4 && Le(), l3 = 91;
  13007. break;
  13008. }
  13009. case 39: {
  13010. I2(39), l3 = 91;
  13011. break;
  13012. }
  13013. case 34: {
  13014. I2(34), l3 = 91;
  13015. break;
  13016. }
  13017. case 47:
  13018. switch (d3[t4 + 4 >> 1] | 0) {
  13019. case 47: {
  13020. de();
  13021. break t;
  13022. }
  13023. case 42: {
  13024. he(1);
  13025. break t;
  13026. }
  13027. default: {
  13028. t4 = n3[69] | 0, a3 = d3[t4 >> 1] | 0;
  13029. r: do
  13030. if (!(yt(a3) | 0)) a3 << 16 >> 16 == 41 ? (h4 = d3[400] | 0, xt(n3[(n3[70] | 0) + ((h4 & 65535) << 3) + 4 >> 2] | 0) | 0 || (l3 = 65)) : l3 = 64;
  13031. else switch (a3 << 16 >> 16) {
  13032. case 46:
  13033. if (((d3[t4 + -2 >> 1] | 0) + -48 & 65535) < 10) {
  13034. l3 = 64;
  13035. break r;
  13036. } else break r;
  13037. case 43:
  13038. if ((d3[t4 + -2 >> 1] | 0) == 43) {
  13039. l3 = 64;
  13040. break r;
  13041. } else break r;
  13042. case 45:
  13043. if ((d3[t4 + -2 >> 1] | 0) == 45) {
  13044. l3 = 64;
  13045. break r;
  13046. } else break r;
  13047. default:
  13048. break r;
  13049. }
  13050. while (false);
  13051. (l3 | 0) == 64 && (h4 = d3[400] | 0, l3 = 65);
  13052. r: do
  13053. if ((l3 | 0) == 65) {
  13054. if (l3 = 0, h4 << 16 >> 16 && (w3 = n3[70] | 0, m4 = (h4 & 65535) + -1 | 0, a3 << 16 >> 16 == 102 ? (n3[w3 + (m4 << 3) >> 2] | 0) == 1 : 0)) {
  13055. if ((d3[t4 + -2 >> 1] | 0) == 111 && O(n3[w3 + (m4 << 3) + 4 >> 2] | 0, 44, 3) | 0) break;
  13056. } else l3 = 69;
  13057. if ((l3 | 0) == 69 && a3 << 16 >> 16 == 125 && (l3 = n3[70] | 0, h4 = h4 & 65535, kt(n3[l3 + (h4 << 3) + 4 >> 2] | 0) | 0 || (n3[l3 + (h4 << 3) >> 2] | 0) == 6)) break;
  13058. if (!(wt(t4) | 0)) {
  13059. switch (a3 << 16 >> 16) {
  13060. case 0:
  13061. break r;
  13062. case 47: {
  13063. if (b3[805] | 0) break r;
  13064. break;
  13065. }
  13066. default:
  13067. }
  13068. if (l3 = n3[65] | 0, l3 | 0 && t4 >>> 0 >= (n3[l3 >> 2] | 0) >>> 0 && t4 >>> 0 <= (n3[l3 + 4 >> 2] | 0) >>> 0) {
  13069. le(), b3[805] = 0, l3 = 91;
  13070. break t;
  13071. }
  13072. h4 = n3[3] | 0;
  13073. do {
  13074. if (t4 >>> 0 <= h4 >>> 0) break;
  13075. t4 = t4 + -2 | 0, n3[69] = t4, a3 = d3[t4 >> 1] | 0;
  13076. } while (!(fe(a3) | 0));
  13077. if (re(a3) | 0) {
  13078. do {
  13079. if (t4 >>> 0 <= h4 >>> 0) break;
  13080. t4 = t4 + -2 | 0, n3[69] = t4;
  13081. } while (re(d3[t4 >> 1] | 0) | 0);
  13082. if (St(t4) | 0) {
  13083. le(), b3[805] = 0, l3 = 91;
  13084. break t;
  13085. }
  13086. }
  13087. b3[805] = 1, l3 = 91;
  13088. break t;
  13089. }
  13090. }
  13091. while (false);
  13092. le(), b3[805] = 0, l3 = 91;
  13093. break t;
  13094. }
  13095. }
  13096. case 96: {
  13097. h4 = n3[70] | 0, a3 = d3[400] | 0, l3 = a3 & 65535, n3[h4 + (l3 << 3) + 4 >> 2] = n3[69], d3[400] = a3 + 1 << 16 >> 16, n3[h4 + (l3 << 3) >> 2] = 3, Le(), l3 = 91;
  13098. break;
  13099. }
  13100. default:
  13101. l3 = 91;
  13102. }
  13103. while (false);
  13104. (l3 | 0) == 91 && (l3 = 0, n3[69] = n3[72]), t4 = n3[72] | 0;
  13105. }
  13106. if ((l3 | 0) == 36) {
  13107. M(), t4 = 0;
  13108. break;
  13109. } else if ((l3 | 0) == 49) {
  13110. M(), t4 = 0;
  13111. break;
  13112. } else if ((l3 | 0) == 92) {
  13113. t4 = b3[802] | 0 ? 0 : (d3[399] | d3[400]) << 16 >> 16 == 0;
  13114. break;
  13115. }
  13116. }
  13117. while (false);
  13118. return E2 = C2, t4 | 0;
  13119. }
  13120. f5(N, "b");
  13121. function U() {
  13122. var t4 = 0, a3 = 0, h4 = 0, l3 = 0, w3 = 0, m4 = 0, C2 = 0, T = 0, be = 0, pe = 0, we = 0, me = 0, S2 = 0, v6 = 0;
  13123. T = n3[72] | 0, be = n3[65] | 0, v6 = T + 12 | 0, n3[72] = v6, h4 = k3(1) | 0, t4 = n3[72] | 0, (t4 | 0) == (v6 | 0) && !(te(h4) | 0) || (S2 = 3);
  13124. e: do
  13125. if ((S2 | 0) == 3) {
  13126. t: do
  13127. switch (h4 << 16 >> 16) {
  13128. case 123: {
  13129. for (n3[72] = t4 + 2, t4 = k3(1) | 0, a3 = n3[72] | 0; ; ) {
  13130. if (H2(t4) | 0 ? (I2(t4), t4 = (n3[72] | 0) + 2 | 0, n3[72] = t4) : ($(t4) | 0, t4 = n3[72] | 0), k3(1) | 0, t4 = Oe(a3, t4) | 0, t4 << 16 >> 16 == 44 && (n3[72] = (n3[72] | 0) + 2, t4 = k3(1) | 0), t4 << 16 >> 16 == 125) {
  13131. S2 = 15;
  13132. break;
  13133. }
  13134. if (v6 = a3, a3 = n3[72] | 0, (a3 | 0) == (v6 | 0)) {
  13135. S2 = 12;
  13136. break;
  13137. }
  13138. if (a3 >>> 0 > (n3[73] | 0) >>> 0) {
  13139. S2 = 14;
  13140. break;
  13141. }
  13142. }
  13143. if ((S2 | 0) == 12) {
  13144. M();
  13145. break e;
  13146. } else if ((S2 | 0) == 14) {
  13147. M();
  13148. break e;
  13149. } else if ((S2 | 0) == 15) {
  13150. b3[803] = 1, n3[72] = (n3[72] | 0) + 2;
  13151. break t;
  13152. }
  13153. break;
  13154. }
  13155. case 42: {
  13156. n3[72] = t4 + 2, k3(1) | 0, v6 = n3[72] | 0, Oe(v6, v6) | 0;
  13157. break;
  13158. }
  13159. default: {
  13160. switch (b3[804] = 0, h4 << 16 >> 16) {
  13161. case 100: {
  13162. switch (T = t4 + 14 | 0, n3[72] = T, (k3(1) | 0) << 16 >> 16) {
  13163. case 97: {
  13164. a3 = n3[72] | 0, !(A3(a3 + 2 | 0, 72, 8) | 0) && (w3 = a3 + 10 | 0, re(d3[w3 >> 1] | 0) | 0) && (n3[72] = w3, k3(0) | 0, S2 = 22);
  13165. break;
  13166. }
  13167. case 102: {
  13168. S2 = 22;
  13169. break;
  13170. }
  13171. case 99: {
  13172. a3 = n3[72] | 0, !(A3(a3 + 2 | 0, 36, 8) | 0) && (l3 = a3 + 10 | 0, v6 = d3[l3 >> 1] | 0, q3(v6) | 0 | v6 << 16 >> 16 == 123) && (n3[72] = l3, m4 = k3(1) | 0, m4 << 16 >> 16 != 123) && (me = m4, S2 = 31);
  13173. break;
  13174. }
  13175. default:
  13176. }
  13177. r: do
  13178. if ((S2 | 0) == 22 && (C2 = n3[72] | 0, (A3(C2 + 2 | 0, 80, 14) | 0) == 0)) {
  13179. if (h4 = C2 + 16 | 0, a3 = d3[h4 >> 1] | 0, !(q3(a3) | 0)) switch (a3 << 16 >> 16) {
  13180. case 40:
  13181. case 42:
  13182. break;
  13183. default:
  13184. break r;
  13185. }
  13186. n3[72] = h4, a3 = k3(1) | 0, a3 << 16 >> 16 == 42 && (n3[72] = (n3[72] | 0) + 2, a3 = k3(1) | 0), a3 << 16 >> 16 != 40 && (me = a3, S2 = 31);
  13187. }
  13188. while (false);
  13189. if ((S2 | 0) == 31 && (pe = n3[72] | 0, $(me) | 0, we = n3[72] | 0, we >>> 0 > pe >>> 0)) {
  13190. W(t4, T, pe, we), n3[72] = (n3[72] | 0) + -2;
  13191. break e;
  13192. }
  13193. W(t4, T, 0, 0), n3[72] = t4 + 12;
  13194. break e;
  13195. }
  13196. case 97: {
  13197. n3[72] = t4 + 10, k3(0) | 0, t4 = n3[72] | 0, S2 = 35;
  13198. break;
  13199. }
  13200. case 102: {
  13201. S2 = 35;
  13202. break;
  13203. }
  13204. case 99: {
  13205. if (!(A3(t4 + 2 | 0, 36, 8) | 0) && (a3 = t4 + 10 | 0, fe(d3[a3 >> 1] | 0) | 0)) {
  13206. n3[72] = a3, v6 = k3(1) | 0, S2 = n3[72] | 0, $(v6) | 0, v6 = n3[72] | 0, W(S2, v6, S2, v6), n3[72] = (n3[72] | 0) + -2;
  13207. break e;
  13208. }
  13209. t4 = t4 + 4 | 0, n3[72] = t4;
  13210. break;
  13211. }
  13212. case 108:
  13213. case 118:
  13214. break;
  13215. default:
  13216. break e;
  13217. }
  13218. if ((S2 | 0) == 35) {
  13219. n3[72] = t4 + 16, t4 = k3(1) | 0, t4 << 16 >> 16 == 42 && (n3[72] = (n3[72] | 0) + 2, t4 = k3(1) | 0), S2 = n3[72] | 0, $(t4) | 0, v6 = n3[72] | 0, W(S2, v6, S2, v6), n3[72] = (n3[72] | 0) + -2;
  13220. break e;
  13221. }
  13222. n3[72] = t4 + 6, b3[804] = 0, h4 = k3(1) | 0, t4 = n3[72] | 0, h4 = ($(h4) | 0 | 32) << 16 >> 16 == 123, l3 = n3[72] | 0, h4 && (n3[72] = l3 + 2, v6 = k3(1) | 0, t4 = n3[72] | 0, $(v6) | 0);
  13223. r: for (; a3 = n3[72] | 0, (a3 | 0) != (t4 | 0); ) {
  13224. if (W(t4, a3, t4, a3), a3 = k3(1) | 0, h4) switch (a3 << 16 >> 16) {
  13225. case 93:
  13226. case 125:
  13227. break e;
  13228. default:
  13229. }
  13230. if (t4 = n3[72] | 0, a3 << 16 >> 16 != 44) {
  13231. S2 = 51;
  13232. break;
  13233. }
  13234. switch (n3[72] = t4 + 2, a3 = k3(1) | 0, t4 = n3[72] | 0, a3 << 16 >> 16) {
  13235. case 91:
  13236. case 123: {
  13237. S2 = 51;
  13238. break r;
  13239. }
  13240. default:
  13241. }
  13242. $(a3) | 0;
  13243. }
  13244. if ((S2 | 0) == 51 && (n3[72] = t4 + -2), !h4) break e;
  13245. n3[72] = l3 + -2;
  13246. break e;
  13247. }
  13248. }
  13249. while (false);
  13250. if (v6 = (k3(1) | 0) << 16 >> 16 == 102, t4 = n3[72] | 0, v6 && !(A3(t4 + 2 | 0, 66, 6) | 0)) for (n3[72] = t4 + 8, J2(T, k3(1) | 0, 0), t4 = be | 0 ? be + 16 | 0 : 240; ; ) {
  13251. if (t4 = n3[t4 >> 2] | 0, !t4) break e;
  13252. n3[t4 + 12 >> 2] = 0, n3[t4 + 8 >> 2] = 0, t4 = t4 + 16 | 0;
  13253. }
  13254. n3[72] = t4 + -2;
  13255. }
  13256. while (false);
  13257. }
  13258. f5(U, "k");
  13259. function P() {
  13260. var t4 = 0, a3 = 0, h4 = 0, l3 = 0, w3 = 0, m4 = 0, C2 = 0;
  13261. w3 = n3[72] | 0, h4 = w3 + 12 | 0, n3[72] = h4, l3 = k3(1) | 0, a3 = n3[72] | 0;
  13262. e: do
  13263. if (l3 << 16 >> 16 != 46) l3 << 16 >> 16 == 115 & a3 >>> 0 > h4 >>> 0 ? !(A3(a3 + 2 | 0, 56, 10) | 0) && (t4 = a3 + 12 | 0, q3(d3[t4 >> 1] | 0) | 0) ? m4 = 14 : (a3 = 6, h4 = 0, m4 = 46) : (t4 = l3, h4 = 0, m4 = 15);
  13264. else switch (n3[72] = a3 + 2, (k3(1) | 0) << 16 >> 16) {
  13265. case 109: {
  13266. if (t4 = n3[72] | 0, A3(t4 + 2 | 0, 50, 6) | 0 || (a3 = n3[69] | 0, !(ge(a3) | 0) && (d3[a3 >> 1] | 0) == 46)) break e;
  13267. ue(w3, w3, t4 + 8 | 0, 2);
  13268. break e;
  13269. }
  13270. case 115: {
  13271. if (t4 = n3[72] | 0, A3(t4 + 2 | 0, 56, 10) | 0 || (a3 = n3[69] | 0, !(ge(a3) | 0) && (d3[a3 >> 1] | 0) == 46)) break e;
  13272. t4 = t4 + 12 | 0, m4 = 14;
  13273. break e;
  13274. }
  13275. default:
  13276. break e;
  13277. }
  13278. while (false);
  13279. (m4 | 0) == 14 && (n3[72] = t4, t4 = k3(1) | 0, h4 = 1, m4 = 15);
  13280. e: do
  13281. if ((m4 | 0) == 15) switch (t4 << 16 >> 16) {
  13282. case 40: {
  13283. if (a3 = n3[70] | 0, C2 = d3[400] | 0, l3 = C2 & 65535, n3[a3 + (l3 << 3) >> 2] = 5, t4 = n3[72] | 0, d3[400] = C2 + 1 << 16 >> 16, n3[a3 + (l3 << 3) + 4 >> 2] = t4, (d3[n3[69] >> 1] | 0) == 46) break e;
  13284. switch (n3[72] = t4 + 2, a3 = k3(1) | 0, ue(w3, n3[72] | 0, 0, t4), h4 ? (t4 = n3[63] | 0, n3[t4 + 28 >> 2] = 5) : t4 = n3[63] | 0, w3 = n3[71] | 0, C2 = d3[399] | 0, d3[399] = C2 + 1 << 16 >> 16, n3[w3 + ((C2 & 65535) << 2) >> 2] = t4, a3 << 16 >> 16) {
  13285. case 39: {
  13286. I2(39);
  13287. break;
  13288. }
  13289. case 34: {
  13290. I2(34);
  13291. break;
  13292. }
  13293. default: {
  13294. n3[72] = (n3[72] | 0) + -2;
  13295. break e;
  13296. }
  13297. }
  13298. switch (t4 = (n3[72] | 0) + 2 | 0, n3[72] = t4, (k3(1) | 0) << 16 >> 16) {
  13299. case 44: {
  13300. n3[72] = (n3[72] | 0) + 2, k3(1) | 0, w3 = n3[63] | 0, n3[w3 + 4 >> 2] = t4, C2 = n3[72] | 0, n3[w3 + 16 >> 2] = C2, b3[w3 + 24 >> 0] = 1, n3[72] = C2 + -2;
  13301. break e;
  13302. }
  13303. case 41: {
  13304. d3[400] = (d3[400] | 0) + -1 << 16 >> 16, C2 = n3[63] | 0, n3[C2 + 4 >> 2] = t4, n3[C2 + 12 >> 2] = (n3[72] | 0) + 2, b3[C2 + 24 >> 0] = 1, d3[399] = (d3[399] | 0) + -1 << 16 >> 16;
  13305. break e;
  13306. }
  13307. default: {
  13308. n3[72] = (n3[72] | 0) + -2;
  13309. break e;
  13310. }
  13311. }
  13312. }
  13313. case 123: {
  13314. if (h4) {
  13315. a3 = 12, h4 = 1, m4 = 46;
  13316. break e;
  13317. }
  13318. if (t4 = n3[72] | 0, d3[400] | 0) {
  13319. n3[72] = t4 + -2;
  13320. break e;
  13321. }
  13322. for (; !(t4 >>> 0 >= (n3[73] | 0) >>> 0); ) {
  13323. if (t4 = k3(1) | 0, H2(t4) | 0) I2(t4);
  13324. else if (t4 << 16 >> 16 == 125) {
  13325. m4 = 36;
  13326. break;
  13327. }
  13328. t4 = (n3[72] | 0) + 2 | 0, n3[72] = t4;
  13329. }
  13330. if ((m4 | 0) == 36 && (n3[72] = (n3[72] | 0) + 2), C2 = (k3(1) | 0) << 16 >> 16 == 102, t4 = n3[72] | 0, C2 && A3(t4 + 2 | 0, 66, 6) | 0) {
  13331. M();
  13332. break e;
  13333. }
  13334. if (n3[72] = t4 + 8, t4 = k3(1) | 0, H2(t4) | 0) {
  13335. J2(w3, t4, 0);
  13336. break e;
  13337. } else {
  13338. M();
  13339. break e;
  13340. }
  13341. }
  13342. default: {
  13343. if (h4) {
  13344. a3 = 12, h4 = 1, m4 = 46;
  13345. break e;
  13346. }
  13347. switch (t4 << 16 >> 16) {
  13348. case 42:
  13349. case 39:
  13350. case 34: {
  13351. h4 = 0, m4 = 48;
  13352. break e;
  13353. }
  13354. default: {
  13355. a3 = 6, h4 = 0, m4 = 46;
  13356. break e;
  13357. }
  13358. }
  13359. }
  13360. }
  13361. while (false);
  13362. (m4 | 0) == 46 && (t4 = n3[72] | 0, (t4 | 0) == (w3 + (a3 << 1) | 0) ? n3[72] = t4 + -2 : m4 = 48);
  13363. do
  13364. if ((m4 | 0) == 48) {
  13365. if (d3[400] | 0) {
  13366. n3[72] = (n3[72] | 0) + -2;
  13367. break;
  13368. }
  13369. for (t4 = n3[73] | 0, a3 = n3[72] | 0; ; ) {
  13370. if (a3 >>> 0 >= t4 >>> 0) {
  13371. m4 = 55;
  13372. break;
  13373. }
  13374. if (l3 = d3[a3 >> 1] | 0, H2(l3) | 0) {
  13375. m4 = 53;
  13376. break;
  13377. }
  13378. C2 = a3 + 2 | 0, n3[72] = C2, a3 = C2;
  13379. }
  13380. if ((m4 | 0) == 53) {
  13381. J2(w3, l3, h4);
  13382. break;
  13383. } else if ((m4 | 0) == 55) {
  13384. M();
  13385. break;
  13386. }
  13387. }
  13388. while (false);
  13389. }
  13390. f5(P, "l");
  13391. function J2(t4, a3, h4) {
  13392. t4 = t4 | 0, a3 = a3 | 0, h4 = h4 | 0;
  13393. var l3 = 0, w3 = 0;
  13394. switch (l3 = (n3[72] | 0) + 2 | 0, a3 << 16 >> 16) {
  13395. case 39: {
  13396. I2(39), w3 = 5;
  13397. break;
  13398. }
  13399. case 34: {
  13400. I2(34), w3 = 5;
  13401. break;
  13402. }
  13403. default:
  13404. M();
  13405. }
  13406. do
  13407. if ((w3 | 0) == 5) {
  13408. if (ue(t4, l3, n3[72] | 0, 1), h4 && (n3[(n3[63] | 0) + 28 >> 2] = 4), n3[72] = (n3[72] | 0) + 2, a3 = k3(0) | 0, h4 = a3 << 16 >> 16 == 97, h4 ? (l3 = n3[72] | 0, A3(l3 + 2 | 0, 94, 10) | 0 && (w3 = 13)) : (l3 = n3[72] | 0, a3 << 16 >> 16 == 119 && (d3[l3 + 2 >> 1] | 0) == 105 && (d3[l3 + 4 >> 1] | 0) == 116 && (d3[l3 + 6 >> 1] | 0) == 104 || (w3 = 13)), (w3 | 0) == 13) {
  13409. n3[72] = l3 + -2;
  13410. break;
  13411. }
  13412. if (n3[72] = l3 + ((h4 ? 6 : 4) << 1), (k3(1) | 0) << 16 >> 16 != 123) {
  13413. n3[72] = l3;
  13414. break;
  13415. }
  13416. h4 = n3[72] | 0, a3 = h4;
  13417. e: for (; ; ) {
  13418. switch (n3[72] = a3 + 2, a3 = k3(1) | 0, a3 << 16 >> 16) {
  13419. case 39: {
  13420. I2(39), n3[72] = (n3[72] | 0) + 2, a3 = k3(1) | 0;
  13421. break;
  13422. }
  13423. case 34: {
  13424. I2(34), n3[72] = (n3[72] | 0) + 2, a3 = k3(1) | 0;
  13425. break;
  13426. }
  13427. default:
  13428. a3 = $(a3) | 0;
  13429. }
  13430. if (a3 << 16 >> 16 != 58) {
  13431. w3 = 22;
  13432. break;
  13433. }
  13434. switch (n3[72] = (n3[72] | 0) + 2, (k3(1) | 0) << 16 >> 16) {
  13435. case 39: {
  13436. I2(39);
  13437. break;
  13438. }
  13439. case 34: {
  13440. I2(34);
  13441. break;
  13442. }
  13443. default: {
  13444. w3 = 26;
  13445. break e;
  13446. }
  13447. }
  13448. switch (n3[72] = (n3[72] | 0) + 2, (k3(1) | 0) << 16 >> 16) {
  13449. case 125: {
  13450. w3 = 31;
  13451. break e;
  13452. }
  13453. case 44:
  13454. break;
  13455. default: {
  13456. w3 = 30;
  13457. break e;
  13458. }
  13459. }
  13460. if (n3[72] = (n3[72] | 0) + 2, (k3(1) | 0) << 16 >> 16 == 125) {
  13461. w3 = 31;
  13462. break;
  13463. }
  13464. a3 = n3[72] | 0;
  13465. }
  13466. if ((w3 | 0) == 22) {
  13467. n3[72] = l3;
  13468. break;
  13469. } else if ((w3 | 0) == 26) {
  13470. n3[72] = l3;
  13471. break;
  13472. } else if ((w3 | 0) == 30) {
  13473. n3[72] = l3;
  13474. break;
  13475. } else if ((w3 | 0) == 31) {
  13476. w3 = n3[63] | 0, n3[w3 + 16 >> 2] = h4, n3[w3 + 12 >> 2] = (n3[72] | 0) + 2;
  13477. break;
  13478. }
  13479. }
  13480. while (false);
  13481. }
  13482. f5(J2, "u");
  13483. function wt(t4) {
  13484. t4 = t4 | 0;
  13485. e: do
  13486. switch (d3[t4 >> 1] | 0) {
  13487. case 100:
  13488. switch (d3[t4 + -2 >> 1] | 0) {
  13489. case 105: {
  13490. t4 = O(t4 + -4 | 0, 104, 2) | 0;
  13491. break e;
  13492. }
  13493. case 108: {
  13494. t4 = O(t4 + -4 | 0, 108, 3) | 0;
  13495. break e;
  13496. }
  13497. default: {
  13498. t4 = 0;
  13499. break e;
  13500. }
  13501. }
  13502. case 101:
  13503. switch (d3[t4 + -2 >> 1] | 0) {
  13504. case 115:
  13505. switch (d3[t4 + -4 >> 1] | 0) {
  13506. case 108: {
  13507. t4 = G2(t4 + -6 | 0, 101) | 0;
  13508. break e;
  13509. }
  13510. case 97: {
  13511. t4 = G2(t4 + -6 | 0, 99) | 0;
  13512. break e;
  13513. }
  13514. default: {
  13515. t4 = 0;
  13516. break e;
  13517. }
  13518. }
  13519. case 116: {
  13520. t4 = O(t4 + -4 | 0, 114, 4) | 0;
  13521. break e;
  13522. }
  13523. case 117: {
  13524. t4 = O(t4 + -4 | 0, 122, 6) | 0;
  13525. break e;
  13526. }
  13527. default: {
  13528. t4 = 0;
  13529. break e;
  13530. }
  13531. }
  13532. case 102: {
  13533. if ((d3[t4 + -2 >> 1] | 0) == 111 && (d3[t4 + -4 >> 1] | 0) == 101) switch (d3[t4 + -6 >> 1] | 0) {
  13534. case 99: {
  13535. t4 = O(t4 + -8 | 0, 134, 6) | 0;
  13536. break e;
  13537. }
  13538. case 112: {
  13539. t4 = O(t4 + -8 | 0, 146, 2) | 0;
  13540. break e;
  13541. }
  13542. default: {
  13543. t4 = 0;
  13544. break e;
  13545. }
  13546. }
  13547. else t4 = 0;
  13548. break;
  13549. }
  13550. case 107: {
  13551. t4 = O(t4 + -2 | 0, 150, 4) | 0;
  13552. break;
  13553. }
  13554. case 110: {
  13555. t4 = t4 + -2 | 0, G2(t4, 105) | 0 ? t4 = 1 : t4 = O(t4, 158, 5) | 0;
  13556. break;
  13557. }
  13558. case 111: {
  13559. t4 = G2(t4 + -2 | 0, 100) | 0;
  13560. break;
  13561. }
  13562. case 114: {
  13563. t4 = O(t4 + -2 | 0, 168, 7) | 0;
  13564. break;
  13565. }
  13566. case 116: {
  13567. t4 = O(t4 + -2 | 0, 182, 4) | 0;
  13568. break;
  13569. }
  13570. case 119:
  13571. switch (d3[t4 + -2 >> 1] | 0) {
  13572. case 101: {
  13573. t4 = G2(t4 + -4 | 0, 110) | 0;
  13574. break e;
  13575. }
  13576. case 111: {
  13577. t4 = O(t4 + -4 | 0, 190, 3) | 0;
  13578. break e;
  13579. }
  13580. default: {
  13581. t4 = 0;
  13582. break e;
  13583. }
  13584. }
  13585. default:
  13586. t4 = 0;
  13587. }
  13588. while (false);
  13589. return t4 | 0;
  13590. }
  13591. f5(wt, "o");
  13592. function Le() {
  13593. var t4 = 0, a3 = 0, h4 = 0, l3 = 0;
  13594. a3 = n3[73] | 0, h4 = n3[72] | 0;
  13595. e: for (; ; ) {
  13596. if (t4 = h4 + 2 | 0, h4 >>> 0 >= a3 >>> 0) {
  13597. a3 = 10;
  13598. break;
  13599. }
  13600. switch (d3[t4 >> 1] | 0) {
  13601. case 96: {
  13602. a3 = 7;
  13603. break e;
  13604. }
  13605. case 36: {
  13606. if ((d3[h4 + 4 >> 1] | 0) == 123) {
  13607. a3 = 6;
  13608. break e;
  13609. }
  13610. break;
  13611. }
  13612. case 92: {
  13613. t4 = h4 + 4 | 0;
  13614. break;
  13615. }
  13616. default:
  13617. }
  13618. h4 = t4;
  13619. }
  13620. (a3 | 0) == 6 ? (t4 = h4 + 4 | 0, n3[72] = t4, a3 = n3[70] | 0, l3 = d3[400] | 0, h4 = l3 & 65535, n3[a3 + (h4 << 3) >> 2] = 4, d3[400] = l3 + 1 << 16 >> 16, n3[a3 + (h4 << 3) + 4 >> 2] = t4) : (a3 | 0) == 7 ? (n3[72] = t4, h4 = n3[70] | 0, l3 = (d3[400] | 0) + -1 << 16 >> 16, d3[400] = l3, (n3[h4 + ((l3 & 65535) << 3) >> 2] | 0) != 3 && M()) : (a3 | 0) == 10 && (n3[72] = t4, M());
  13621. }
  13622. f5(Le, "h");
  13623. function k3(t4) {
  13624. t4 = t4 | 0;
  13625. var a3 = 0, h4 = 0, l3 = 0;
  13626. h4 = n3[72] | 0;
  13627. e: do {
  13628. a3 = d3[h4 >> 1] | 0;
  13629. t: do
  13630. if (a3 << 16 >> 16 != 47) if (t4) {
  13631. if (q3(a3) | 0) break;
  13632. break e;
  13633. } else {
  13634. if (re(a3) | 0) break;
  13635. break e;
  13636. }
  13637. else switch (d3[h4 + 2 >> 1] | 0) {
  13638. case 47: {
  13639. de();
  13640. break t;
  13641. }
  13642. case 42: {
  13643. he(t4);
  13644. break t;
  13645. }
  13646. default: {
  13647. a3 = 47;
  13648. break e;
  13649. }
  13650. }
  13651. while (false);
  13652. l3 = n3[72] | 0, h4 = l3 + 2 | 0, n3[72] = h4;
  13653. } while (l3 >>> 0 < (n3[73] | 0) >>> 0);
  13654. return a3 | 0;
  13655. }
  13656. f5(k3, "w");
  13657. function ue(t4, a3, h4, l3) {
  13658. t4 = t4 | 0, a3 = a3 | 0, h4 = h4 | 0, l3 = l3 | 0;
  13659. var w3 = 0, m4 = 0;
  13660. m4 = n3[67] | 0, n3[67] = m4 + 36, w3 = n3[63] | 0, n3[(w3 | 0 ? w3 + 32 | 0 : 236) >> 2] = m4, n3[64] = w3, n3[63] = m4, n3[m4 + 8 >> 2] = t4, (l3 | 0) == 2 ? (t4 = 3, w3 = h4) : (w3 = (l3 | 0) == 1, t4 = w3 ? 1 : 2, w3 = w3 ? h4 + 2 | 0 : 0), n3[m4 + 12 >> 2] = w3, n3[m4 + 28 >> 2] = t4, n3[m4 >> 2] = a3, n3[m4 + 4 >> 2] = h4, n3[m4 + 16 >> 2] = 0, n3[m4 + 20 >> 2] = l3, a3 = (l3 | 0) == 1, b3[m4 + 24 >> 0] = a3 & 1, n3[m4 + 32 >> 2] = 0, a3 | (l3 | 0) == 2 && (b3[803] = 1);
  13661. }
  13662. f5(ue, "d");
  13663. function I2(t4) {
  13664. t4 = t4 | 0;
  13665. var a3 = 0, h4 = 0, l3 = 0, w3 = 0;
  13666. for (w3 = n3[73] | 0, a3 = n3[72] | 0; ; ) {
  13667. if (l3 = a3 + 2 | 0, a3 >>> 0 >= w3 >>> 0) {
  13668. a3 = 9;
  13669. break;
  13670. }
  13671. if (h4 = d3[l3 >> 1] | 0, h4 << 16 >> 16 == t4 << 16 >> 16) {
  13672. a3 = 10;
  13673. break;
  13674. }
  13675. if (h4 << 16 >> 16 == 92) h4 = a3 + 4 | 0, (d3[h4 >> 1] | 0) == 13 ? (a3 = a3 + 6 | 0, a3 = (d3[a3 >> 1] | 0) == 10 ? a3 : h4) : a3 = h4;
  13676. else if (Ae(h4) | 0) {
  13677. a3 = 9;
  13678. break;
  13679. } else a3 = l3;
  13680. }
  13681. (a3 | 0) == 9 ? (n3[72] = l3, M()) : (a3 | 0) == 10 && (n3[72] = l3);
  13682. }
  13683. f5(I2, "v");
  13684. function Oe(t4, a3) {
  13685. t4 = t4 | 0, a3 = a3 | 0;
  13686. var h4 = 0, l3 = 0, w3 = 0, m4 = 0;
  13687. return h4 = n3[72] | 0, l3 = d3[h4 >> 1] | 0, m4 = (t4 | 0) == (a3 | 0), w3 = m4 ? 0 : t4, m4 = m4 ? 0 : a3, l3 << 16 >> 16 == 97 && (n3[72] = h4 + 4, h4 = k3(1) | 0, t4 = n3[72] | 0, H2(h4) | 0 ? (I2(h4), a3 = (n3[72] | 0) + 2 | 0, n3[72] = a3) : ($(h4) | 0, a3 = n3[72] | 0), l3 = k3(1) | 0, h4 = n3[72] | 0), (h4 | 0) != (t4 | 0) && W(t4, a3, w3, m4), l3 | 0;
  13688. }
  13689. f5(Oe, "A");
  13690. function mt() {
  13691. var t4 = 0, a3 = 0, h4 = 0;
  13692. h4 = n3[73] | 0, a3 = n3[72] | 0;
  13693. e: for (; ; ) {
  13694. if (t4 = a3 + 2 | 0, a3 >>> 0 >= h4 >>> 0) {
  13695. a3 = 6;
  13696. break;
  13697. }
  13698. switch (d3[t4 >> 1] | 0) {
  13699. case 13:
  13700. case 10: {
  13701. a3 = 6;
  13702. break e;
  13703. }
  13704. case 93: {
  13705. a3 = 7;
  13706. break e;
  13707. }
  13708. case 92: {
  13709. t4 = a3 + 4 | 0;
  13710. break;
  13711. }
  13712. default:
  13713. }
  13714. a3 = t4;
  13715. }
  13716. return (a3 | 0) == 6 ? (n3[72] = t4, M(), t4 = 0) : (a3 | 0) == 7 && (n3[72] = t4, t4 = 93), t4 | 0;
  13717. }
  13718. f5(mt, "C");
  13719. function le() {
  13720. var t4 = 0, a3 = 0, h4 = 0;
  13721. e: for (; ; ) {
  13722. if (t4 = n3[72] | 0, a3 = t4 + 2 | 0, n3[72] = a3, t4 >>> 0 >= (n3[73] | 0) >>> 0) {
  13723. h4 = 7;
  13724. break;
  13725. }
  13726. switch (d3[a3 >> 1] | 0) {
  13727. case 13:
  13728. case 10: {
  13729. h4 = 7;
  13730. break e;
  13731. }
  13732. case 47:
  13733. break e;
  13734. case 91: {
  13735. mt() | 0;
  13736. break;
  13737. }
  13738. case 92: {
  13739. n3[72] = t4 + 4;
  13740. break;
  13741. }
  13742. default:
  13743. }
  13744. }
  13745. (h4 | 0) == 7 && M();
  13746. }
  13747. f5(le, "g");
  13748. function kt(t4) {
  13749. switch (t4 = t4 | 0, d3[t4 >> 1] | 0) {
  13750. case 62: {
  13751. t4 = (d3[t4 + -2 >> 1] | 0) == 61;
  13752. break;
  13753. }
  13754. case 41:
  13755. case 59: {
  13756. t4 = 1;
  13757. break;
  13758. }
  13759. case 104: {
  13760. t4 = O(t4 + -2 | 0, 210, 4) | 0;
  13761. break;
  13762. }
  13763. case 121: {
  13764. t4 = O(t4 + -2 | 0, 218, 6) | 0;
  13765. break;
  13766. }
  13767. case 101: {
  13768. t4 = O(t4 + -2 | 0, 230, 3) | 0;
  13769. break;
  13770. }
  13771. default:
  13772. t4 = 0;
  13773. }
  13774. return t4 | 0;
  13775. }
  13776. f5(kt, "p");
  13777. function he(t4) {
  13778. t4 = t4 | 0;
  13779. var a3 = 0, h4 = 0, l3 = 0, w3 = 0, m4 = 0;
  13780. for (w3 = (n3[72] | 0) + 2 | 0, n3[72] = w3, h4 = n3[73] | 0; a3 = w3 + 2 | 0, !(w3 >>> 0 >= h4 >>> 0 || (l3 = d3[a3 >> 1] | 0, !t4 && Ae(l3) | 0)); ) {
  13781. if (l3 << 16 >> 16 == 42 && (d3[w3 + 4 >> 1] | 0) == 47) {
  13782. m4 = 8;
  13783. break;
  13784. }
  13785. w3 = a3;
  13786. }
  13787. (m4 | 0) == 8 && (n3[72] = a3, a3 = w3 + 4 | 0), n3[72] = a3;
  13788. }
  13789. f5(he, "y");
  13790. function A3(t4, a3, h4) {
  13791. t4 = t4 | 0, a3 = a3 | 0, h4 = h4 | 0;
  13792. var l3 = 0, w3 = 0;
  13793. e: do
  13794. if (!h4) t4 = 0;
  13795. else {
  13796. for (; l3 = b3[t4 >> 0] | 0, w3 = b3[a3 >> 0] | 0, l3 << 24 >> 24 == w3 << 24 >> 24; ) if (h4 = h4 + -1 | 0, h4) t4 = t4 + 1 | 0, a3 = a3 + 1 | 0;
  13797. else {
  13798. t4 = 0;
  13799. break e;
  13800. }
  13801. t4 = (l3 & 255) - (w3 & 255) | 0;
  13802. }
  13803. while (false);
  13804. return t4 | 0;
  13805. }
  13806. f5(A3, "m");
  13807. function te(t4) {
  13808. t4 = t4 | 0;
  13809. e: do
  13810. switch (t4 << 16 >> 16) {
  13811. case 38:
  13812. case 37:
  13813. case 33: {
  13814. t4 = 1;
  13815. break;
  13816. }
  13817. default:
  13818. if ((t4 & -8) << 16 >> 16 == 40 | (t4 + -58 & 65535) < 6) t4 = 1;
  13819. else {
  13820. switch (t4 << 16 >> 16) {
  13821. case 91:
  13822. case 93:
  13823. case 94: {
  13824. t4 = 1;
  13825. break e;
  13826. }
  13827. default:
  13828. }
  13829. t4 = (t4 + -123 & 65535) < 4;
  13830. }
  13831. }
  13832. while (false);
  13833. return t4 | 0;
  13834. }
  13835. f5(te, "I");
  13836. function yt(t4) {
  13837. t4 = t4 | 0;
  13838. e: do
  13839. switch (t4 << 16 >> 16) {
  13840. case 38:
  13841. case 37:
  13842. case 33:
  13843. break;
  13844. default:
  13845. if (!((t4 + -58 & 65535) < 6 | (t4 + -40 & 65535) < 7 & t4 << 16 >> 16 != 41)) {
  13846. switch (t4 << 16 >> 16) {
  13847. case 91:
  13848. case 94:
  13849. break e;
  13850. default:
  13851. }
  13852. return t4 << 16 >> 16 != 125 & (t4 + -123 & 65535) < 4 | 0;
  13853. }
  13854. }
  13855. while (false);
  13856. return 1;
  13857. }
  13858. f5(yt, "U");
  13859. function Re(t4) {
  13860. t4 = t4 | 0;
  13861. var a3 = 0;
  13862. a3 = d3[t4 >> 1] | 0;
  13863. e: do
  13864. if ((a3 + -9 & 65535) >= 5) {
  13865. switch (a3 << 16 >> 16) {
  13866. case 160:
  13867. case 32: {
  13868. a3 = 1;
  13869. break e;
  13870. }
  13871. default:
  13872. }
  13873. if (te(a3) | 0) return a3 << 16 >> 16 != 46 | (ge(t4) | 0) | 0;
  13874. a3 = 0;
  13875. } else a3 = 1;
  13876. while (false);
  13877. return a3 | 0;
  13878. }
  13879. f5(Re, "x");
  13880. function Ct(t4) {
  13881. t4 = t4 | 0;
  13882. var a3 = 0, h4 = 0, l3 = 0, w3 = 0;
  13883. return h4 = E2, E2 = E2 + 16 | 0, l3 = h4, n3[l3 >> 2] = 0, n3[66] = t4, a3 = n3[3] | 0, w3 = a3 + (t4 << 1) | 0, t4 = w3 + 2 | 0, d3[w3 >> 1] = 0, n3[l3 >> 2] = t4, n3[67] = t4, n3[59] = 0, n3[63] = 0, n3[61] = 0, n3[60] = 0, n3[65] = 0, n3[62] = 0, E2 = h4, a3 | 0;
  13884. }
  13885. f5(Ct, "S");
  13886. function W(t4, a3, h4, l3) {
  13887. t4 = t4 | 0, a3 = a3 | 0, h4 = h4 | 0, l3 = l3 | 0;
  13888. var w3 = 0, m4 = 0;
  13889. w3 = n3[67] | 0, n3[67] = w3 + 20, m4 = n3[65] | 0, n3[(m4 | 0 ? m4 + 16 | 0 : 240) >> 2] = w3, n3[65] = w3, n3[w3 >> 2] = t4, n3[w3 + 4 >> 2] = a3, n3[w3 + 8 >> 2] = h4, n3[w3 + 12 >> 2] = l3, n3[w3 + 16 >> 2] = 0, b3[803] = 1;
  13890. }
  13891. f5(W, "O");
  13892. function O(t4, a3, h4) {
  13893. t4 = t4 | 0, a3 = a3 | 0, h4 = h4 | 0;
  13894. var l3 = 0, w3 = 0;
  13895. return l3 = t4 + (0 - h4 << 1) | 0, w3 = l3 + 2 | 0, t4 = n3[3] | 0, w3 >>> 0 >= t4 >>> 0 && !(A3(w3, a3, h4 << 1) | 0) ? (w3 | 0) == (t4 | 0) ? t4 = 1 : t4 = Re(l3) | 0 : t4 = 0, t4 | 0;
  13896. }
  13897. f5(O, "$");
  13898. function St(t4) {
  13899. switch (t4 = t4 | 0, d3[t4 >> 1] | 0) {
  13900. case 107: {
  13901. t4 = O(t4 + -2 | 0, 150, 4) | 0;
  13902. break;
  13903. }
  13904. case 101: {
  13905. (d3[t4 + -2 >> 1] | 0) == 117 ? t4 = O(t4 + -4 | 0, 122, 6) | 0 : t4 = 0;
  13906. break;
  13907. }
  13908. default:
  13909. t4 = 0;
  13910. }
  13911. return t4 | 0;
  13912. }
  13913. f5(St, "j");
  13914. function G2(t4, a3) {
  13915. t4 = t4 | 0, a3 = a3 | 0;
  13916. var h4 = 0;
  13917. return h4 = n3[3] | 0, h4 >>> 0 <= t4 >>> 0 && (d3[t4 >> 1] | 0) == a3 << 16 >> 16 ? (h4 | 0) == (t4 | 0) ? h4 = 1 : h4 = fe(d3[t4 + -2 >> 1] | 0) | 0 : h4 = 0, h4 | 0;
  13918. }
  13919. f5(G2, "B");
  13920. function fe(t4) {
  13921. t4 = t4 | 0;
  13922. e: do
  13923. if ((t4 + -9 & 65535) < 5) t4 = 1;
  13924. else {
  13925. switch (t4 << 16 >> 16) {
  13926. case 32:
  13927. case 160: {
  13928. t4 = 1;
  13929. break e;
  13930. }
  13931. default:
  13932. }
  13933. t4 = t4 << 16 >> 16 != 46 & (te(t4) | 0);
  13934. }
  13935. while (false);
  13936. return t4 | 0;
  13937. }
  13938. f5(fe, "E");
  13939. function de() {
  13940. var t4 = 0, a3 = 0, h4 = 0;
  13941. t4 = n3[73] | 0, h4 = n3[72] | 0;
  13942. e: for (; a3 = h4 + 2 | 0, !(h4 >>> 0 >= t4 >>> 0); ) switch (d3[a3 >> 1] | 0) {
  13943. case 13:
  13944. case 10:
  13945. break e;
  13946. default:
  13947. h4 = a3;
  13948. }
  13949. n3[72] = a3;
  13950. }
  13951. f5(de, "P");
  13952. function $(t4) {
  13953. for (t4 = t4 | 0; !(q3(t4) | 0 || te(t4) | 0); ) if (t4 = (n3[72] | 0) + 2 | 0, n3[72] = t4, t4 = d3[t4 >> 1] | 0, !(t4 << 16 >> 16)) {
  13954. t4 = 0;
  13955. break;
  13956. }
  13957. return t4 | 0;
  13958. }
  13959. f5($, "q");
  13960. function vt() {
  13961. var t4 = 0;
  13962. switch (t4 = n3[(n3[61] | 0) + 20 >> 2] | 0, t4 | 0) {
  13963. case 1: {
  13964. t4 = -1;
  13965. break;
  13966. }
  13967. case 2: {
  13968. t4 = -2;
  13969. break;
  13970. }
  13971. default:
  13972. t4 = t4 - (n3[3] | 0) >> 1;
  13973. }
  13974. return t4 | 0;
  13975. }
  13976. f5(vt, "z");
  13977. function xt(t4) {
  13978. return t4 = t4 | 0, !(O(t4, 196, 5) | 0) && !(O(t4, 44, 3) | 0) ? t4 = O(t4, 206, 2) | 0 : t4 = 1, t4 | 0;
  13979. }
  13980. f5(xt, "D");
  13981. function re(t4) {
  13982. switch (t4 = t4 | 0, t4 << 16 >> 16) {
  13983. case 160:
  13984. case 32:
  13985. case 12:
  13986. case 11:
  13987. case 9: {
  13988. t4 = 1;
  13989. break;
  13990. }
  13991. default:
  13992. t4 = 0;
  13993. }
  13994. return t4 | 0;
  13995. }
  13996. f5(re, "F");
  13997. function ge(t4) {
  13998. return t4 = t4 | 0, (d3[t4 >> 1] | 0) == 46 && (d3[t4 + -2 >> 1] | 0) == 46 ? t4 = (d3[t4 + -4 >> 1] | 0) == 46 : t4 = 0, t4 | 0;
  13999. }
  14000. f5(ge, "G");
  14001. function z2(t4) {
  14002. return t4 = t4 | 0, (n3[3] | 0) == (t4 | 0) ? t4 = 1 : t4 = Re(t4 + -2 | 0) | 0, t4 | 0;
  14003. }
  14004. f5(z2, "H");
  14005. function _t() {
  14006. var t4 = 0;
  14007. return t4 = n3[(n3[62] | 0) + 12 >> 2] | 0, t4 ? t4 = t4 - (n3[3] | 0) >> 1 : t4 = -1, t4 | 0;
  14008. }
  14009. f5(_t, "J");
  14010. function Et() {
  14011. var t4 = 0;
  14012. return t4 = n3[(n3[61] | 0) + 12 >> 2] | 0, t4 ? t4 = t4 - (n3[3] | 0) >> 1 : t4 = -1, t4 | 0;
  14013. }
  14014. f5(Et, "K");
  14015. function Lt() {
  14016. var t4 = 0;
  14017. return t4 = n3[(n3[62] | 0) + 8 >> 2] | 0, t4 ? t4 = t4 - (n3[3] | 0) >> 1 : t4 = -1, t4 | 0;
  14018. }
  14019. f5(Lt, "L");
  14020. function Ot() {
  14021. var t4 = 0;
  14022. return t4 = n3[(n3[61] | 0) + 16 >> 2] | 0, t4 ? t4 = t4 - (n3[3] | 0) >> 1 : t4 = -1, t4 | 0;
  14023. }
  14024. f5(Ot, "M");
  14025. function Rt() {
  14026. var t4 = 0;
  14027. return t4 = n3[(n3[61] | 0) + 4 >> 2] | 0, t4 ? t4 = t4 - (n3[3] | 0) >> 1 : t4 = -1, t4 | 0;
  14028. }
  14029. f5(Rt, "N");
  14030. function At() {
  14031. var t4 = 0;
  14032. return t4 = n3[61] | 0, t4 = n3[(t4 | 0 ? t4 + 32 | 0 : 236) >> 2] | 0, n3[61] = t4, (t4 | 0) != 0 | 0;
  14033. }
  14034. f5(At, "Q");
  14035. function Nt() {
  14036. var t4 = 0;
  14037. return t4 = n3[62] | 0, t4 = n3[(t4 | 0 ? t4 + 16 | 0 : 240) >> 2] | 0, n3[62] = t4, (t4 | 0) != 0 | 0;
  14038. }
  14039. f5(Nt, "R");
  14040. function M() {
  14041. b3[802] = 1, n3[68] = (n3[72] | 0) - (n3[3] | 0) >> 1, n3[72] = (n3[73] | 0) + 2;
  14042. }
  14043. f5(M, "T");
  14044. function q3(t4) {
  14045. return t4 = t4 | 0, (t4 | 128) << 16 >> 16 == 160 | (t4 + -9 & 65535) < 5 | 0;
  14046. }
  14047. f5(q3, "V");
  14048. function H2(t4) {
  14049. return t4 = t4 | 0, t4 << 16 >> 16 == 39 | t4 << 16 >> 16 == 34 | 0;
  14050. }
  14051. f5(H2, "W");
  14052. function It() {
  14053. return (n3[(n3[61] | 0) + 8 >> 2] | 0) - (n3[3] | 0) >> 1 | 0;
  14054. }
  14055. f5(It, "X");
  14056. function Mt() {
  14057. return (n3[(n3[62] | 0) + 4 >> 2] | 0) - (n3[3] | 0) >> 1 | 0;
  14058. }
  14059. f5(Mt, "Y");
  14060. function Ae(t4) {
  14061. return t4 = t4 | 0, t4 << 16 >> 16 == 13 | t4 << 16 >> 16 == 10 | 0;
  14062. }
  14063. f5(Ae, "Z");
  14064. function Ut() {
  14065. return (n3[n3[61] >> 2] | 0) - (n3[3] | 0) >> 1 | 0;
  14066. }
  14067. f5(Ut, "_");
  14068. function jt() {
  14069. return (n3[n3[62] >> 2] | 0) - (n3[3] | 0) >> 1 | 0;
  14070. }
  14071. f5(jt, "ee");
  14072. function $t() {
  14073. return R[(n3[61] | 0) + 24 >> 0] | 0 | 0;
  14074. }
  14075. f5($t, "ae");
  14076. function Dt(t4) {
  14077. t4 = t4 | 0, n3[3] = t4;
  14078. }
  14079. f5(Dt, "re");
  14080. function Tt() {
  14081. return n3[(n3[61] | 0) + 28 >> 2] | 0;
  14082. }
  14083. f5(Tt, "ie");
  14084. function Ft() {
  14085. return (b3[803] | 0) != 0 | 0;
  14086. }
  14087. f5(Ft, "se");
  14088. function Pt() {
  14089. return (b3[804] | 0) != 0 | 0;
  14090. }
  14091. f5(Pt, "fe");
  14092. function Wt() {
  14093. return n3[68] | 0;
  14094. }
  14095. f5(Wt, "te");
  14096. function qt(t4) {
  14097. return t4 = t4 | 0, E2 = t4 + 992 + 15 & -16, 992;
  14098. }
  14099. return f5(qt, "ce"), { su: qt, ai: Ot, e: Wt, ee: Mt, ele: _t, els: Lt, es: jt, f: Pt, id: vt, ie: Rt, ip: $t, is: Ut, it: Tt, ms: Ft, p: N, re: Nt, ri: At, sa: Ct, se: Et, ses: Dt, ss: It };
  14100. }(typeof self < "u" ? self : global, {}, ie), ye = x4.su(Z2 - (2 << 17));
  14101. }
  14102. const i4 = _3.length + 1;
  14103. x4.ses(ye), x4.sa(i4 - 1), Pe(_3, new Uint16Array(ie, ye, i4)), x4.p() || (y2 = x4.e(), D2());
  14104. const o3 = [], c3 = [];
  14105. for (; x4.ri(); ) {
  14106. const u3 = x4.is(), p3 = x4.ie(), g3 = x4.ai(), b3 = x4.id(), d3 = x4.ss(), n3 = x4.se(), R = x4.it();
  14107. let L;
  14108. x4.ip() && (L = Ce(b3 === -1 ? u3 : u3 + 1, _3.charCodeAt(b3 === -1 ? u3 - 1 : u3))), o3.push({ t: R, n: L, s: u3, e: p3, ss: d3, se: n3, d: b3, a: g3 });
  14109. }
  14110. for (; x4.re(); ) {
  14111. const u3 = x4.es(), p3 = x4.ee(), g3 = x4.els(), b3 = x4.ele(), d3 = _3.charCodeAt(u3), n3 = g3 >= 0 ? _3.charCodeAt(g3) : -1;
  14112. c3.push({ s: u3, e: p3, ls: g3, le: b3, n: d3 === 34 || d3 === 39 ? Ce(u3 + 1, d3) : _3.slice(u3, p3), ln: g3 < 0 ? void 0 : n3 === 34 || n3 === 39 ? Ce(g3 + 1, n3) : _3.slice(g3, b3) });
  14113. }
  14114. return [o3, c3, !!x4.f(), !!x4.ms()];
  14115. }
  14116. f5(cr, "parse");
  14117. function Ce(s4, e4) {
  14118. y2 = s4;
  14119. let r4 = "", i4 = y2;
  14120. for (; ; ) {
  14121. y2 >= _3.length && D2();
  14122. const o3 = _3.charCodeAt(y2);
  14123. if (o3 === e4) break;
  14124. o3 === 92 ? (r4 += _3.slice(i4, y2), r4 += ur(), i4 = y2) : (o3 === 8232 || o3 === 8233 || qe(o3) && D2(), ++y2);
  14125. }
  14126. return r4 += _3.slice(i4, y2++), r4;
  14127. }
  14128. f5(Ce, "b");
  14129. function ur() {
  14130. let s4 = _3.charCodeAt(++y2);
  14131. switch (++y2, s4) {
  14132. case 110:
  14133. return `
  14134. `;
  14135. case 114:
  14136. return "\r";
  14137. case 120:
  14138. return String.fromCharCode(Se(2));
  14139. case 117:
  14140. return function() {
  14141. const e4 = _3.charCodeAt(y2);
  14142. let r4;
  14143. return e4 === 123 ? (++y2, r4 = Se(_3.indexOf("}", y2) - y2), ++y2, r4 > 1114111 && D2()) : r4 = Se(4), r4 <= 65535 ? String.fromCharCode(r4) : (r4 -= 65536, String.fromCharCode(55296 + (r4 >> 10), 56320 + (1023 & r4)));
  14144. }();
  14145. case 116:
  14146. return " ";
  14147. case 98:
  14148. return "\b";
  14149. case 118:
  14150. return "\v";
  14151. case 102:
  14152. return "\f";
  14153. case 13:
  14154. _3.charCodeAt(y2) === 10 && ++y2;
  14155. case 10:
  14156. return "";
  14157. case 56:
  14158. case 57:
  14159. D2();
  14160. default:
  14161. if (s4 >= 48 && s4 <= 55) {
  14162. let e4 = _3.substr(y2 - 1, 3).match(/^[0-7]+/)[0], r4 = parseInt(e4, 8);
  14163. return r4 > 255 && (e4 = e4.slice(0, -1), r4 = parseInt(e4, 8)), y2 += e4.length - 1, s4 = _3.charCodeAt(y2), e4 === "0" && s4 !== 56 && s4 !== 57 || D2(), String.fromCharCode(r4);
  14164. }
  14165. return qe(s4) ? "" : String.fromCharCode(s4);
  14166. }
  14167. }
  14168. f5(ur, "k");
  14169. function Se(s4) {
  14170. const e4 = y2;
  14171. let r4 = 0, i4 = 0;
  14172. for (let o3 = 0; o3 < s4; ++o3, ++y2) {
  14173. let c3, u3 = _3.charCodeAt(y2);
  14174. if (u3 !== 95) {
  14175. if (u3 >= 97) c3 = u3 - 97 + 10;
  14176. else if (u3 >= 65) c3 = u3 - 65 + 10;
  14177. else {
  14178. if (!(u3 >= 48 && u3 <= 57)) break;
  14179. c3 = u3 - 48;
  14180. }
  14181. if (c3 >= 16) break;
  14182. i4 = u3, r4 = 16 * r4 + c3;
  14183. } else i4 !== 95 && o3 !== 0 || D2(), i4 = u3;
  14184. }
  14185. return i4 !== 95 && y2 - e4 === s4 || D2(), r4;
  14186. }
  14187. f5(Se, "l");
  14188. function qe(s4) {
  14189. return s4 === 13 || s4 === 10;
  14190. }
  14191. f5(qe, "u");
  14192. function D2() {
  14193. throw Object.assign(Error(`Parse error ${We}:${_3.slice(0, y2).split(`
  14194. `).length}:${y2 - _3.lastIndexOf(`
  14195. `, y2 - 1)}`), { idx: y2 });
  14196. }
  14197. f5(D2, "o");
  14198. var ve;
  14199. typeof WebAssembly < "u" && (async () => {
  14200. const { parse: s4, init: e4 } = await Promise.resolve().then(function() {
  14201. return require_lexer_DgIbo0BU();
  14202. });
  14203. await e4, ve = s4;
  14204. })();
  14205. var Be = f5((s4, e4) => ve ? ve(s4, e4) : cr(s4, e4), "parseEsm");
  14206. var lr = f5((s4) => {
  14207. if (!s4.includes("import") && !s4.includes("export")) return false;
  14208. try {
  14209. return Be(s4)[3];
  14210. } catch {
  14211. return true;
  14212. }
  14213. }, "isESM");
  14214. var Je = "2";
  14215. var hr = ((s4) => {
  14216. const e4 = "default";
  14217. return s4[e4] && typeof s4[e4] == "object" && "__esModule" in s4[e4] ? s4[e4] : s4;
  14218. }).toString();
  14219. var fr = `.then(${hr})`;
  14220. var xe = f5((s4, e4, r4) => {
  14221. if (r4) {
  14222. if (!e4.includes("import(")) return;
  14223. } else if (!e4.includes("import")) return;
  14224. const o3 = Be(e4, s4)[0].filter((g3) => g3.d > -1);
  14225. if (o3.length === 0) return;
  14226. const c3 = new Ee(e4);
  14227. for (const g3 of o3) c3.appendRight(g3.se, fr);
  14228. const u3 = c3.toString(), p3 = c3.generateMap({ source: s4, includeContent: false, hires: "boundary" });
  14229. return { code: u3, map: p3 };
  14230. }, "transformDynamicImport");
  14231. var Ge = f5((s4) => {
  14232. try {
  14233. const e4 = j3.readFileSync(s4, "utf8");
  14234. return JSON.parse(e4);
  14235. } catch {
  14236. }
  14237. }, "readJsonFile");
  14238. var ze = f5(() => {
  14239. }, "noop");
  14240. var He = f5(() => Math.floor(Date.now() / 1e8), "getTime");
  14241. var _dr = class _dr extends Map {
  14242. cacheDirectory = zt.tmpdir;
  14243. oldCacheDirectory = X.join(Gt.tmpdir(), "tsx");
  14244. cacheFiles;
  14245. constructor() {
  14246. super(), j3.mkdirSync(this.cacheDirectory, { recursive: true }), this.cacheFiles = j3.readdirSync(this.cacheDirectory).map((e4) => {
  14247. const [r4, i4] = e4.split("-");
  14248. return { time: Number(r4), key: i4, fileName: e4 };
  14249. }), setImmediate(() => {
  14250. this.expireDiskCache(), this.removeOldCacheDirectory();
  14251. });
  14252. }
  14253. get(e4) {
  14254. const r4 = super.get(e4);
  14255. if (r4) return r4;
  14256. const i4 = this.cacheFiles.find((u3) => u3.key === e4);
  14257. if (!i4) return;
  14258. const o3 = X.join(this.cacheDirectory, i4.fileName), c3 = Ge(o3);
  14259. if (!c3) {
  14260. j3.promises.unlink(o3).then(() => {
  14261. const u3 = this.cacheFiles.indexOf(i4);
  14262. this.cacheFiles.splice(u3, 1);
  14263. }, () => {
  14264. });
  14265. return;
  14266. }
  14267. return super.set(e4, c3), c3;
  14268. }
  14269. set(e4, r4) {
  14270. if (super.set(e4, r4), r4) {
  14271. const i4 = He();
  14272. j3.promises.writeFile(X.join(this.cacheDirectory, `${i4}-${e4}`), JSON.stringify(r4)).catch(ze);
  14273. }
  14274. return this;
  14275. }
  14276. expireDiskCache() {
  14277. const e4 = He();
  14278. for (const r4 of this.cacheFiles) e4 - r4.time > 7 && j3.promises.unlink(X.join(this.cacheDirectory, r4.fileName)).catch(ze);
  14279. }
  14280. async removeOldCacheDirectory() {
  14281. try {
  14282. await j3.promises.access(this.oldCacheDirectory).then(() => true) && ("rm" in j3.promises ? await j3.promises.rm(this.oldCacheDirectory, { recursive: true, force: true }) : await j3.promises.rmdir(this.oldCacheDirectory, { recursive: true }));
  14283. } catch {
  14284. }
  14285. }
  14286. };
  14287. f5(_dr, "FileCache");
  14288. var dr = _dr;
  14289. var se = process.env.TSX_DISABLE_CACHE ? /* @__PURE__ */ new Map() : new dr();
  14290. var gr = /^[\w+.-]+:\/\//;
  14291. var br = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  14292. var pr = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  14293. function wr(s4) {
  14294. return gr.test(s4);
  14295. }
  14296. f5(wr, "isAbsoluteUrl");
  14297. function mr(s4) {
  14298. return s4.startsWith("//");
  14299. }
  14300. f5(mr, "isSchemeRelativeUrl");
  14301. function Xe(s4) {
  14302. return s4.startsWith("/");
  14303. }
  14304. f5(Xe, "isAbsolutePath");
  14305. function kr(s4) {
  14306. return s4.startsWith("file:");
  14307. }
  14308. f5(kr, "isFileUrl");
  14309. function Ke(s4) {
  14310. return /^[.?#]/.test(s4);
  14311. }
  14312. f5(Ke, "isRelative");
  14313. function oe(s4) {
  14314. const e4 = br.exec(s4);
  14315. return Ye(e4[1], e4[2] || "", e4[3], e4[4] || "", e4[5] || "/", e4[6] || "", e4[7] || "");
  14316. }
  14317. f5(oe, "parseAbsoluteUrl");
  14318. function yr(s4) {
  14319. const e4 = pr.exec(s4), r4 = e4[2];
  14320. return Ye("file:", "", e4[1] || "", "", Xe(r4) ? r4 : "/" + r4, e4[3] || "", e4[4] || "");
  14321. }
  14322. f5(yr, "parseFileUrl");
  14323. function Ye(s4, e4, r4, i4, o3, c3, u3) {
  14324. return { scheme: s4, user: e4, host: r4, port: i4, path: o3, query: c3, hash: u3, type: 7 };
  14325. }
  14326. f5(Ye, "makeUrl");
  14327. function Qe(s4) {
  14328. if (mr(s4)) {
  14329. const r4 = oe("http:" + s4);
  14330. return r4.scheme = "", r4.type = 6, r4;
  14331. }
  14332. if (Xe(s4)) {
  14333. const r4 = oe("http://foo.com" + s4);
  14334. return r4.scheme = "", r4.host = "", r4.type = 5, r4;
  14335. }
  14336. if (kr(s4)) return yr(s4);
  14337. if (wr(s4)) return oe(s4);
  14338. const e4 = oe("http://foo.com/" + s4);
  14339. return e4.scheme = "", e4.host = "", e4.type = s4 ? s4.startsWith("?") ? 3 : s4.startsWith("#") ? 2 : 4 : 1, e4;
  14340. }
  14341. f5(Qe, "parseUrl");
  14342. function Cr(s4) {
  14343. if (s4.endsWith("/..")) return s4;
  14344. const e4 = s4.lastIndexOf("/");
  14345. return s4.slice(0, e4 + 1);
  14346. }
  14347. f5(Cr, "stripPathFilename");
  14348. function Sr(s4, e4) {
  14349. Ze(e4, e4.type), s4.path === "/" ? s4.path = e4.path : s4.path = Cr(e4.path) + s4.path;
  14350. }
  14351. f5(Sr, "mergePaths");
  14352. function Ze(s4, e4) {
  14353. const r4 = e4 <= 4, i4 = s4.path.split("/");
  14354. let o3 = 1, c3 = 0, u3 = false;
  14355. for (let g3 = 1; g3 < i4.length; g3++) {
  14356. const b3 = i4[g3];
  14357. if (!b3) {
  14358. u3 = true;
  14359. continue;
  14360. }
  14361. if (u3 = false, b3 !== ".") {
  14362. if (b3 === "..") {
  14363. c3 ? (u3 = true, c3--, o3--) : r4 && (i4[o3++] = b3);
  14364. continue;
  14365. }
  14366. i4[o3++] = b3, c3++;
  14367. }
  14368. }
  14369. let p3 = "";
  14370. for (let g3 = 1; g3 < o3; g3++) p3 += "/" + i4[g3];
  14371. (!p3 || u3 && !p3.endsWith("/..")) && (p3 += "/"), s4.path = p3;
  14372. }
  14373. f5(Ze, "normalizePath");
  14374. function vr(s4, e4) {
  14375. if (!s4 && !e4) return "";
  14376. const r4 = Qe(s4);
  14377. let i4 = r4.type;
  14378. if (e4 && i4 !== 7) {
  14379. const c3 = Qe(e4), u3 = c3.type;
  14380. switch (i4) {
  14381. case 1:
  14382. r4.hash = c3.hash;
  14383. case 2:
  14384. r4.query = c3.query;
  14385. case 3:
  14386. case 4:
  14387. Sr(r4, c3);
  14388. case 5:
  14389. r4.user = c3.user, r4.host = c3.host, r4.port = c3.port;
  14390. case 6:
  14391. r4.scheme = c3.scheme;
  14392. }
  14393. u3 > i4 && (i4 = u3);
  14394. }
  14395. Ze(r4, i4);
  14396. const o3 = r4.query + r4.hash;
  14397. switch (i4) {
  14398. case 2:
  14399. case 3:
  14400. return o3;
  14401. case 4: {
  14402. const c3 = r4.path.slice(1);
  14403. return c3 ? Ke(e4 || s4) && !Ke(c3) ? "./" + c3 + o3 : c3 + o3 : o3 || ".";
  14404. }
  14405. case 5:
  14406. return r4.path + o3;
  14407. default:
  14408. return r4.scheme + "//" + r4.user + r4.host + r4.port + r4.path + o3;
  14409. }
  14410. }
  14411. f5(vr, "resolve$1");
  14412. function Ve(s4, e4) {
  14413. return e4 && !e4.endsWith("/") && (e4 += "/"), vr(s4, e4);
  14414. }
  14415. f5(Ve, "resolve");
  14416. function xr(s4) {
  14417. if (!s4) return "";
  14418. const e4 = s4.lastIndexOf("/");
  14419. return s4.slice(0, e4 + 1);
  14420. }
  14421. f5(xr, "stripFilename");
  14422. var F3 = 0;
  14423. function _r(s4, e4) {
  14424. const r4 = et(s4, 0);
  14425. if (r4 === s4.length) return s4;
  14426. e4 || (s4 = s4.slice());
  14427. for (let i4 = r4; i4 < s4.length; i4 = et(s4, i4 + 1)) s4[i4] = Lr(s4[i4], e4);
  14428. return s4;
  14429. }
  14430. f5(_r, "maybeSort");
  14431. function et(s4, e4) {
  14432. for (let r4 = e4; r4 < s4.length; r4++) if (!Er(s4[r4])) return r4;
  14433. return s4.length;
  14434. }
  14435. f5(et, "nextUnsortedSegmentLine");
  14436. function Er(s4) {
  14437. for (let e4 = 1; e4 < s4.length; e4++) if (s4[e4][F3] < s4[e4 - 1][F3]) return false;
  14438. return true;
  14439. }
  14440. f5(Er, "isSorted");
  14441. function Lr(s4, e4) {
  14442. return e4 || (s4 = s4.slice()), s4.sort(Or);
  14443. }
  14444. f5(Lr, "sortSegments");
  14445. function Or(s4, e4) {
  14446. return s4[F3] - e4[F3];
  14447. }
  14448. f5(Or, "sortComparator");
  14449. var ae = false;
  14450. function Rr(s4, e4, r4, i4) {
  14451. for (; r4 <= i4; ) {
  14452. const o3 = r4 + (i4 - r4 >> 1), c3 = s4[o3][F3] - e4;
  14453. if (c3 === 0) return ae = true, o3;
  14454. c3 < 0 ? r4 = o3 + 1 : i4 = o3 - 1;
  14455. }
  14456. return ae = false, r4 - 1;
  14457. }
  14458. f5(Rr, "binarySearch");
  14459. function Ar(s4, e4, r4) {
  14460. for (let i4 = r4 - 1; i4 >= 0 && s4[i4][F3] === e4; r4 = i4--) ;
  14461. return r4;
  14462. }
  14463. f5(Ar, "lowerBound");
  14464. function Nr() {
  14465. return { lastKey: -1, lastNeedle: -1, lastIndex: -1 };
  14466. }
  14467. f5(Nr, "memoizedState");
  14468. function Ir(s4, e4, r4, i4) {
  14469. const { lastKey: o3, lastNeedle: c3, lastIndex: u3 } = r4;
  14470. let p3 = 0, g3 = s4.length - 1;
  14471. if (i4 === o3) {
  14472. if (e4 === c3) return ae = u3 !== -1 && s4[u3][F3] === e4, u3;
  14473. e4 >= c3 ? p3 = u3 === -1 ? 0 : u3 : g3 = u3;
  14474. }
  14475. return r4.lastKey = i4, r4.lastNeedle = e4, r4.lastIndex = Rr(s4, e4, p3, g3);
  14476. }
  14477. f5(Ir, "memoizedBinarySearch");
  14478. var _tt = class _tt {
  14479. constructor(e4, r4) {
  14480. const i4 = typeof e4 == "string";
  14481. if (!i4 && e4._decodedMemo) return e4;
  14482. const o3 = i4 ? JSON.parse(e4) : e4, { version: c3, file: u3, names: p3, sourceRoot: g3, sources: b3, sourcesContent: d3 } = o3;
  14483. this.version = c3, this.file = u3, this.names = p3 || [], this.sourceRoot = g3, this.sources = b3, this.sourcesContent = d3, this.ignoreList = o3.ignoreList || o3.x_google_ignoreList || void 0;
  14484. const n3 = Ve(g3 || "", xr(r4));
  14485. this.resolvedSources = b3.map((L) => Ve(L || "", n3));
  14486. const { mappings: R } = o3;
  14487. typeof R == "string" ? (this._encoded = R, this._decoded = void 0) : (this._encoded = void 0, this._decoded = _r(R, i4)), this._decodedMemo = Nr(), this._bySources = void 0, this._bySourceMemos = void 0;
  14488. }
  14489. };
  14490. f5(_tt, "TraceMap");
  14491. var tt = _tt;
  14492. function gn(s4) {
  14493. return s4;
  14494. }
  14495. f5(gn, "cast$2");
  14496. function rt(s4) {
  14497. var e4;
  14498. return (e4 = s4)._decoded || (e4._decoded = Xt(s4._encoded));
  14499. }
  14500. f5(rt, "decodedMappings");
  14501. function Mr(s4, e4, r4) {
  14502. const i4 = rt(s4);
  14503. if (e4 >= i4.length) return null;
  14504. const o3 = i4[e4], c3 = Ur(o3, s4._decodedMemo, e4, r4);
  14505. return c3 === -1 ? null : o3[c3];
  14506. }
  14507. f5(Mr, "traceSegment");
  14508. function Ur(s4, e4, r4, i4, o3) {
  14509. let c3 = Ir(s4, i4, e4, r4);
  14510. return ae && (c3 = Ar(s4, i4, c3)), c3 === -1 || c3 === s4.length ? -1 : c3;
  14511. }
  14512. f5(Ur, "traceSegmentInternal");
  14513. var __e = class __e {
  14514. constructor() {
  14515. this._indexes = { __proto__: null }, this.array = [];
  14516. }
  14517. };
  14518. f5(__e, "SetArray");
  14519. var _e = __e;
  14520. function bn(s4) {
  14521. return s4;
  14522. }
  14523. f5(bn, "cast$1");
  14524. function nt(s4, e4) {
  14525. return s4._indexes[e4];
  14526. }
  14527. f5(nt, "get");
  14528. function V(s4, e4) {
  14529. const r4 = nt(s4, e4);
  14530. if (r4 !== void 0) return r4;
  14531. const { array: i4, _indexes: o3 } = s4, c3 = i4.push(e4);
  14532. return o3[e4] = c3 - 1;
  14533. }
  14534. f5(V, "put");
  14535. function jr(s4, e4) {
  14536. const r4 = nt(s4, e4);
  14537. if (r4 === void 0) return;
  14538. const { array: i4, _indexes: o3 } = s4;
  14539. for (let c3 = r4 + 1; c3 < i4.length; c3++) {
  14540. const u3 = i4[c3];
  14541. i4[c3 - 1] = u3, o3[u3]--;
  14542. }
  14543. o3[e4] = void 0, i4.pop();
  14544. }
  14545. f5(jr, "remove");
  14546. var $r = 0;
  14547. var Dr = 1;
  14548. var Tr = 2;
  14549. var Fr = 3;
  14550. var Pr = 4;
  14551. var it = -1;
  14552. var _Wr = class _Wr {
  14553. constructor({ file: e4, sourceRoot: r4 } = {}) {
  14554. this._names = new _e(), this._sources = new _e(), this._sourcesContent = [], this._mappings = [], this.file = e4, this.sourceRoot = r4, this._ignoreList = new _e();
  14555. }
  14556. };
  14557. f5(_Wr, "GenMapping");
  14558. var Wr = _Wr;
  14559. function pn(s4) {
  14560. return s4;
  14561. }
  14562. f5(pn, "cast");
  14563. var qr = f5((s4, e4, r4, i4, o3, c3, u3, p3) => zr(true, s4, e4, r4, i4, o3, c3, u3), "maybeAddSegment");
  14564. function Br(s4, e4, r4) {
  14565. const { _sources: i4, _sourcesContent: o3 } = s4, c3 = V(i4, e4);
  14566. o3[c3] = r4;
  14567. }
  14568. f5(Br, "setSourceContent");
  14569. function Jr(s4, e4, r4 = true) {
  14570. const { _sources: i4, _sourcesContent: o3, _ignoreList: c3 } = s4, u3 = V(i4, e4);
  14571. u3 === o3.length && (o3[u3] = null), r4 ? V(c3, u3) : jr(c3, u3);
  14572. }
  14573. f5(Jr, "setIgnore");
  14574. function st(s4) {
  14575. const { _mappings: e4, _sources: r4, _sourcesContent: i4, _names: o3, _ignoreList: c3 } = s4;
  14576. return Kr(e4), { version: 3, file: s4.file || void 0, names: o3.array, sourceRoot: s4.sourceRoot || void 0, sources: r4.array, sourcesContent: i4, mappings: e4, ignoreList: c3.array };
  14577. }
  14578. f5(st, "toDecodedMap");
  14579. function Gr(s4) {
  14580. const e4 = st(s4);
  14581. return Object.assign(Object.assign({}, e4), { mappings: Te(e4.mappings) });
  14582. }
  14583. f5(Gr, "toEncodedMap");
  14584. function zr(s4, e4, r4, i4, o3, c3, u3, p3, g3) {
  14585. const { _mappings: b3, _sources: d3, _sourcesContent: n3, _names: R } = e4, L = Hr(b3, r4), E2 = Xr(L, i4);
  14586. if (!o3) return Yr(L, E2) ? void 0 : ot(L, E2, [i4]);
  14587. const N = V(d3, o3), U = p3 ? V(R, p3) : it;
  14588. if (N === n3.length && (n3[N] = null), !Qr(L, E2, N, c3, u3, U)) return ot(L, E2, p3 ? [i4, N, c3, u3, U] : [i4, N, c3, u3]);
  14589. }
  14590. f5(zr, "addSegmentInternal");
  14591. function Hr(s4, e4) {
  14592. for (let r4 = s4.length; r4 <= e4; r4++) s4[r4] = [];
  14593. return s4[e4];
  14594. }
  14595. f5(Hr, "getLine");
  14596. function Xr(s4, e4) {
  14597. let r4 = s4.length;
  14598. for (let i4 = r4 - 1; i4 >= 0; r4 = i4--) {
  14599. const o3 = s4[i4];
  14600. if (e4 >= o3[$r]) break;
  14601. }
  14602. return r4;
  14603. }
  14604. f5(Xr, "getColumnIndex");
  14605. function ot(s4, e4, r4) {
  14606. for (let i4 = s4.length; i4 > e4; i4--) s4[i4] = s4[i4 - 1];
  14607. s4[e4] = r4;
  14608. }
  14609. f5(ot, "insert");
  14610. function Kr(s4) {
  14611. const { length: e4 } = s4;
  14612. let r4 = e4;
  14613. for (let i4 = r4 - 1; i4 >= 0 && !(s4[i4].length > 0); r4 = i4, i4--) ;
  14614. r4 < e4 && (s4.length = r4);
  14615. }
  14616. f5(Kr, "removeEmptyFinalLines");
  14617. function Yr(s4, e4) {
  14618. return e4 === 0 ? true : s4[e4 - 1].length === 1;
  14619. }
  14620. f5(Yr, "skipSourceless");
  14621. function Qr(s4, e4, r4, i4, o3, c3) {
  14622. if (e4 === 0) return false;
  14623. const u3 = s4[e4 - 1];
  14624. return u3.length === 1 ? false : r4 === u3[Dr] && i4 === u3[Tr] && o3 === u3[Fr] && c3 === (u3.length === 5 ? u3[Pr] : it);
  14625. }
  14626. f5(Qr, "skipSource");
  14627. var at = ct("", -1, -1, "", null, false);
  14628. var Zr = [];
  14629. function ct(s4, e4, r4, i4, o3, c3) {
  14630. return { source: s4, line: e4, column: r4, name: i4, content: o3, ignore: c3 };
  14631. }
  14632. f5(ct, "SegmentObject");
  14633. function ut(s4, e4, r4, i4, o3) {
  14634. return { map: s4, sources: e4, source: r4, content: i4, ignore: o3 };
  14635. }
  14636. f5(ut, "Source");
  14637. function lt(s4, e4) {
  14638. return ut(s4, e4, "", null, false);
  14639. }
  14640. f5(lt, "MapSource");
  14641. function Vr(s4, e4, r4) {
  14642. return ut(null, Zr, s4, e4, r4);
  14643. }
  14644. f5(Vr, "OriginalSource");
  14645. function en(s4) {
  14646. const e4 = new Wr({ file: s4.map.file }), { sources: r4, map: i4 } = s4, o3 = i4.names, c3 = rt(i4);
  14647. for (let u3 = 0; u3 < c3.length; u3++) {
  14648. const p3 = c3[u3];
  14649. for (let g3 = 0; g3 < p3.length; g3++) {
  14650. const b3 = p3[g3], d3 = b3[0];
  14651. let n3 = at;
  14652. if (b3.length !== 1) {
  14653. const J2 = r4[b3[1]];
  14654. if (n3 = ht(J2, b3[2], b3[3], b3.length === 5 ? o3[b3[4]] : ""), n3 == null) continue;
  14655. }
  14656. const { column: R, line: L, name: E2, content: N, source: U, ignore: P } = n3;
  14657. qr(e4, u3, d3, U, L, R, E2), U && N != null && Br(e4, U, N), P && Jr(e4, U, true);
  14658. }
  14659. }
  14660. return e4;
  14661. }
  14662. f5(en, "traceMappings");
  14663. function ht(s4, e4, r4, i4) {
  14664. if (!s4.map) return ct(s4.source, e4, r4, i4, s4.content, s4.ignore);
  14665. const o3 = Mr(s4.map, e4, r4);
  14666. return o3 == null ? null : o3.length === 1 ? at : ht(s4.sources[o3[1]], o3[2], o3[3], o3.length === 5 ? s4.map.names[o3[4]] : i4);
  14667. }
  14668. f5(ht, "originalPositionFor");
  14669. function tn(s4) {
  14670. return Array.isArray(s4) ? s4 : [s4];
  14671. }
  14672. f5(tn, "asArray");
  14673. function rn(s4, e4) {
  14674. const r4 = tn(s4).map((c3) => new tt(c3, "")), i4 = r4.pop();
  14675. for (let c3 = 0; c3 < r4.length; c3++) if (r4[c3].sources.length > 1) throw new Error(`Transformation map ${c3} must have exactly one source file.
  14676. Did you specify these with the most recent transformation maps first?`);
  14677. let o3 = ft(i4, e4, "", 0);
  14678. for (let c3 = r4.length - 1; c3 >= 0; c3--) o3 = lt(r4[c3], [o3]);
  14679. return o3;
  14680. }
  14681. f5(rn, "buildSourceMapTree");
  14682. function ft(s4, e4, r4, i4) {
  14683. const { resolvedSources: o3, sourcesContent: c3, ignoreList: u3 } = s4, p3 = i4 + 1, g3 = o3.map((b3, d3) => {
  14684. const n3 = { importer: r4, depth: p3, source: b3 || "", content: void 0, ignore: void 0 }, R = e4(n3.source, n3), { source: L, content: E2, ignore: N } = n3;
  14685. if (R) return ft(new tt(R, L), e4, L, p3);
  14686. const U = E2 !== void 0 ? E2 : c3 ? c3[d3] : null, P = N !== void 0 ? N : u3 ? u3.includes(d3) : false;
  14687. return Vr(L, U, P);
  14688. });
  14689. return lt(s4, g3);
  14690. }
  14691. f5(ft, "build");
  14692. var _nn = class _nn {
  14693. constructor(e4, r4) {
  14694. const i4 = r4.decodedMappings ? st(e4) : Gr(e4);
  14695. this.version = i4.version, this.file = i4.file, this.mappings = i4.mappings, this.names = i4.names, this.ignoreList = i4.ignoreList, this.sourceRoot = i4.sourceRoot, this.sources = i4.sources, r4.excludeContent || (this.sourcesContent = i4.sourcesContent);
  14696. }
  14697. toString() {
  14698. return JSON.stringify(this);
  14699. }
  14700. };
  14701. f5(_nn, "SourceMap");
  14702. var nn = _nn;
  14703. function dt(s4, e4, r4) {
  14704. const i4 = { excludeContent: !!r4, decodedMappings: false }, o3 = rn(s4, e4);
  14705. return new nn(en(o3), i4);
  14706. }
  14707. f5(dt, "remapping");
  14708. var sn = f5((s4, e4, r4) => {
  14709. const i4 = [], o3 = { code: e4 };
  14710. for (const c3 of r4) {
  14711. const u3 = c3(s4, o3.code);
  14712. u3 && (Object.assign(o3, u3), i4.unshift(u3.map));
  14713. }
  14714. return { ...o3, map: dt(i4, () => null) };
  14715. }, "applyTransformersSync");
  14716. var on = f5(async (s4, e4, r4) => {
  14717. const i4 = [], o3 = { code: e4 };
  14718. for (const c3 of r4) {
  14719. const u3 = await c3(s4, o3.code);
  14720. u3 && (Object.assign(o3, u3), i4.unshift(u3.map));
  14721. }
  14722. return { ...o3, map: dt(i4, () => null) };
  14723. }, "applyTransformers");
  14724. var an = Object.freeze({ target: `node${process.versions.node}`, loader: "default" });
  14725. var cn = /^--inspect(?:-brk|-port|-publish-uid|-wait)?(?:=|$)/;
  14726. var un = process.execArgv.some((s4) => cn.test(s4));
  14727. var gt = { ...an, sourcemap: true, sourcesContent: !!process.env.NODE_V8_COVERAGE || un, minifyWhitespace: true, keepNames: true };
  14728. var bt = f5((s4) => {
  14729. const e4 = s4.sourcefile;
  14730. if (e4) {
  14731. const r4 = X.extname(e4.split("?")[0]);
  14732. r4 ? r4 === ".cts" || r4 === ".mts" ? s4.sourcefile = `${e4.slice(0, -3)}ts` : r4 === ".mjs" && (s4.sourcefile = `${e4.slice(0, -3)}js`) : s4.sourcefile += ".js";
  14733. }
  14734. return (r4) => (r4.map && (s4.sourcefile !== e4 && (r4.map = r4.map.replace(JSON.stringify(s4.sourcefile), JSON.stringify(e4))), r4.map = JSON.parse(r4.map)), r4);
  14735. }, "patchOptions");
  14736. var pt = f5((s4) => {
  14737. throw s4.name = "TransformError", delete s4.errors, delete s4.warnings, s4;
  14738. }, "formatEsbuildError");
  14739. var ln = f5((s4, e4, r4) => {
  14740. const i4 = {};
  14741. let o3, c3, u3;
  14742. if (e4.startsWith("file://")) {
  14743. o3 = e4;
  14744. const d3 = new URL(e4);
  14745. c3 = Ne.fileURLToPath(d3);
  14746. } else [c3, u3] = e4.split("?"), o3 = Ne.pathToFileURL(c3) + (u3 ? `?${u3}` : "");
  14747. c3.endsWith(".cjs") || c3.endsWith(".cts") || (i4["import.meta.url"] = JSON.stringify(o3));
  14748. const p3 = { ...gt, format: "cjs", sourcefile: c3, define: i4, banner: `__filename=${JSON.stringify(c3)};(()=>{`, footer: "})()", platform: "node", ...r4 }, g3 = Ie([s4, JSON.stringify(p3), ne.version, Je].join("-"));
  14749. let b3 = se.get(g3);
  14750. return b3 || (b3 = sn(e4, s4, [(d3, n3) => {
  14751. const R = bt(p3);
  14752. let L;
  14753. try {
  14754. L = ne.transformSync(n3, p3);
  14755. } catch (E2) {
  14756. throw pt(E2);
  14757. }
  14758. return R(L);
  14759. }, (d3, n3) => xe(d3, n3, true)]), se.set(g3, b3)), b3;
  14760. }, "transformSync");
  14761. var hn = f5(async (s4, e4, r4) => {
  14762. const i4 = { ...gt, format: "esm", sourcefile: e4, ...r4 }, o3 = Ie([s4, JSON.stringify(i4), ne.version, Je].join("-"));
  14763. let c3 = se.get(o3);
  14764. return c3 || (c3 = await on(e4, s4, [async (u3, p3) => {
  14765. const g3 = bt(i4);
  14766. let b3;
  14767. try {
  14768. b3 = await ne.transform(p3, i4);
  14769. } catch (d3) {
  14770. throw pt(d3);
  14771. }
  14772. return g3(b3);
  14773. }, (u3, p3) => xe(u3, p3, true)]), se.set(o3, c3)), c3;
  14774. }, "transform");
  14775. exports2.isESM = lr, exports2.readJsonFile = Ge, exports2.transform = hn, exports2.transformDynamicImport = xe, exports2.transformSync = ln;
  14776. }
  14777. });
  14778. // ../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/client-D6NvIMSC.cjs
  14779. var require_client_D6NvIMSC = __commonJS({
  14780. "../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/client-D6NvIMSC.cjs"(exports2) {
  14781. "use strict";
  14782. var f5 = Object.defineProperty;
  14783. var r4 = (e4, n3) => f5(e4, "name", { value: n3, configurable: true });
  14784. var p3 = require("node:net");
  14785. var u3 = require_get_pipe_path_BoR10qr8();
  14786. var g3 = r4(() => new Promise((e4) => {
  14787. const n3 = u3.getPipePath(process.ppid), t4 = p3.createConnection(n3, () => {
  14788. e4(r4((a3) => {
  14789. const o3 = Buffer.from(JSON.stringify(a3)), c3 = Buffer.alloc(4);
  14790. c3.writeInt32BE(o3.length, 0), t4.write(Buffer.concat([c3, o3]));
  14791. }, "sendToParent"));
  14792. });
  14793. t4.on("error", () => {
  14794. e4();
  14795. }), t4.unref();
  14796. }), "connectToServer");
  14797. var s4 = { send: void 0 };
  14798. var i4 = g3();
  14799. i4.then((e4) => {
  14800. s4.send = e4;
  14801. }, () => {
  14802. }), exports2.connectingToServer = i4, exports2.parent = s4;
  14803. }
  14804. });
  14805. // ../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/index-BWFBUo6r.cjs
  14806. var require_index_BWFBUo6r = __commonJS({
  14807. "../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/index-BWFBUo6r.cjs"(exports2) {
  14808. "use strict";
  14809. var b3 = Object.defineProperty;
  14810. var p3 = (s4, l3) => b3(s4, "name", { value: l3, configurable: true });
  14811. var t4 = true;
  14812. var n3 = typeof self < "u" ? self : typeof window < "u" ? window : typeof global < "u" ? global : {};
  14813. var r4 = 0;
  14814. if (n3.process && n3.process.env && n3.process.stdout) {
  14815. const { FORCE_COLOR: s4, NODE_DISABLE_COLORS: l3, NO_COLOR: c3, TERM: o3, COLORTERM: i4 } = n3.process.env;
  14816. l3 || c3 || s4 === "0" ? t4 = false : s4 === "1" || s4 === "2" || s4 === "3" ? t4 = true : o3 === "dumb" ? t4 = false : "CI" in n3.process.env && ["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((g3) => g3 in n3.process.env) ? t4 = true : t4 = process.stdout.isTTY, t4 && (process.platform === "win32" || i4 && (i4 === "truecolor" || i4 === "24bit") ? r4 = 3 : o3 && (o3.endsWith("-256color") || o3.endsWith("256")) ? r4 = 2 : r4 = 1);
  14817. }
  14818. var a3 = { enabled: t4, supportLevel: r4 };
  14819. function e4(s4, l3, c3 = 1) {
  14820. const o3 = `\x1B[${s4}m`, i4 = `\x1B[${l3}m`, g3 = new RegExp(`\\x1b\\[${l3}m`, "g");
  14821. return (f5) => a3.enabled && a3.supportLevel >= c3 ? o3 + ("" + f5).replace(g3, o3) + i4 : "" + f5;
  14822. }
  14823. p3(e4, "kolorist");
  14824. var u3 = e4(30, 39);
  14825. var d3 = e4(33, 39);
  14826. var O = e4(90, 39);
  14827. var C2 = e4(92, 39);
  14828. var L = e4(95, 39);
  14829. var R = e4(96, 39);
  14830. var y2 = e4(44, 49);
  14831. var I2 = e4(100, 49);
  14832. var h4 = e4(103, 49);
  14833. exports2.bgBlue = y2, exports2.bgGray = I2, exports2.bgLightYellow = h4, exports2.black = u3, exports2.gray = O, exports2.lightCyan = R, exports2.lightGreen = C2, exports2.lightMagenta = L, exports2.options = a3, exports2.yellow = d3;
  14834. }
  14835. });
  14836. // ../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/register-D46fvsV_.cjs
  14837. var require_register_D46fvsV = __commonJS({
  14838. "../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/register-D46fvsV_.cjs"(exports2, module2) {
  14839. "use strict";
  14840. var K = Object.defineProperty;
  14841. var o3 = (s4, e4) => K(s4, "name", { value: e4, configurable: true });
  14842. var Y = require_get_pipe_path_BoR10qr8();
  14843. var u3 = require("node:module");
  14844. var m4 = require("node:path");
  14845. var L = require("node:url");
  14846. var b3 = require_dist2();
  14847. var O = require("node:fs");
  14848. var w3 = require_index_gckBtVBf();
  14849. var R = require_client_D6NvIMSC();
  14850. var V = require("node:util");
  14851. var g3 = require_index_BWFBUo6r();
  14852. var W = o3((s4) => {
  14853. if (!s4.startsWith("data:text/javascript,")) return;
  14854. const e4 = s4.indexOf("?");
  14855. if (e4 === -1) return;
  14856. const n3 = new URLSearchParams(s4.slice(e4 + 1)).get("filePath");
  14857. if (n3) return n3;
  14858. }, "getOriginalFilePath");
  14859. var D2 = o3((s4) => {
  14860. const e4 = W(s4);
  14861. return e4 && (u3._cache[e4] = u3._cache[s4], delete u3._cache[s4], s4 = e4), s4;
  14862. }, "interopCjsExports");
  14863. var Z2 = o3((s4) => {
  14864. const e4 = s4.indexOf(":");
  14865. if (e4 !== -1) return s4.slice(0, e4);
  14866. }, "getScheme");
  14867. var N = o3((s4) => s4[0] === "." && (s4[1] === "/" || s4[1] === "." || s4[2] === "/"), "isRelativePath");
  14868. var j3 = o3((s4) => N(s4) || m4.isAbsolute(s4), "isFilePath");
  14869. var q3 = o3((s4) => {
  14870. if (j3(s4)) return true;
  14871. const e4 = Z2(s4);
  14872. return e4 && e4 !== "node";
  14873. }, "requestAcceptsQuery");
  14874. var v6 = "file://";
  14875. var ee = [".ts", ".tsx", ".jsx", ".mts", ".cts"];
  14876. var C2 = /\.([cm]?ts|[tj]sx)($|\?)/;
  14877. var se = /[/\\].+\.(?:cts|cjs)(?:$|\?)/;
  14878. var te = /\.json($|\?)/;
  14879. var _3 = /\/(?:$|\?)/;
  14880. var ne = /^(?:@[^/]+\/)?[^/\\]+$/;
  14881. var J2 = `${m4.sep}node_modules${m4.sep}`;
  14882. exports2.fileMatcher = void 0, exports2.tsconfigPathsMatcher = void 0, exports2.allowJs = false;
  14883. var Q = o3((s4) => {
  14884. var _a2;
  14885. let e4 = null;
  14886. if (s4) {
  14887. const r4 = m4.resolve(s4);
  14888. e4 = { path: r4, config: b3.parseTsconfig(r4) };
  14889. } else {
  14890. try {
  14891. e4 = b3.getTsconfig();
  14892. } catch {
  14893. }
  14894. if (!e4) return;
  14895. }
  14896. exports2.fileMatcher = b3.createFilesMatcher(e4), exports2.tsconfigPathsMatcher = b3.createPathsMatcher(e4), exports2.allowJs = ((_a2 = e4 == null ? void 0 : e4.config.compilerOptions) == null ? void 0 : _a2.allowJs) ?? false;
  14897. }, "loadTsconfig");
  14898. var T = o3((s4) => Array.from(s4).length > 0 ? `?${s4.toString()}` : "", "urlSearchParamsStringify");
  14899. var re = `
  14900. //# sourceMappingURL=data:application/json;base64,`;
  14901. var A3 = o3(() => process.sourceMapsEnabled ?? true, "shouldApplySourceMap");
  14902. var $ = o3(({ code: s4, map: e4 }) => s4 + re + Buffer.from(JSON.stringify(e4), "utf8").toString("base64"), "inlineSourceMap");
  14903. var M = Number(process.env.TSX_DEBUG);
  14904. M && (g3.options.enabled = true, g3.options.supportLevel = 3);
  14905. var I2 = o3((s4) => (e4, ...r4) => {
  14906. if (!M || e4 > M) return;
  14907. const n3 = `${g3.bgGray(` tsx P${process.pid} `)} ${s4}`, t4 = r4.map((a3) => typeof a3 == "string" ? a3 : V.inspect(a3, { colors: true })).join(" ");
  14908. O.writeSync(1, `${n3} ${t4}
  14909. `);
  14910. }, "createLog");
  14911. var x4 = I2(g3.bgLightYellow(g3.black(" CJS ")));
  14912. var ae = I2(g3.bgBlue(" ESM "));
  14913. var oe = [".cts", ".mts", ".ts", ".tsx", ".jsx"];
  14914. var ie = [".js", ".cjs", ".mjs"];
  14915. var k3 = [".ts", ".tsx", ".jsx"];
  14916. var F3 = o3((s4, e4, r4, n3) => {
  14917. const t4 = Object.getOwnPropertyDescriptor(s4, e4);
  14918. (t4 == null ? void 0 : t4.set) ? s4[e4] = r4 : (!t4 || t4.configurable) && Object.defineProperty(s4, e4, { value: r4, enumerable: (t4 == null ? void 0 : t4.enumerable) || (n3 == null ? void 0 : n3.enumerable), writable: (n3 == null ? void 0 : n3.writable) ?? (t4 ? t4.writable : true), configurable: (n3 == null ? void 0 : n3.configurable) ?? (t4 ? t4.configurable : true) });
  14919. }, "safeSet");
  14920. var ce = o3((s4, e4, r4) => {
  14921. const n3 = e4[".js"], t4 = o3((a3, i4) => {
  14922. var _a2, _b;
  14923. if (s4.enabled === false) return n3(a3, i4);
  14924. const [c3, f5] = i4.split("?");
  14925. if ((new URLSearchParams(f5).get("namespace") ?? void 0) !== r4) return n3(a3, i4);
  14926. x4(2, "load", { filePath: i4 }), a3.id.startsWith("data:text/javascript,") && (a3.path = m4.dirname(c3)), ((_a2 = R.parent) == null ? void 0 : _a2.send) && R.parent.send({ type: "dependency", path: c3 });
  14927. const p3 = oe.some((h4) => c3.endsWith(h4)), P = ie.some((h4) => c3.endsWith(h4));
  14928. if (!p3 && !P) return n3(a3, c3);
  14929. let d3 = O.readFileSync(c3, "utf8");
  14930. if (c3.endsWith(".cjs")) {
  14931. const h4 = w3.transformDynamicImport(i4, d3);
  14932. h4 && (d3 = A3() ? $(h4) : h4.code);
  14933. } else if (p3 || w3.isESM(d3)) {
  14934. const h4 = w3.transformSync(d3, i4, { tsconfigRaw: (_b = exports2.fileMatcher) == null ? void 0 : _b.call(exports2, c3) });
  14935. d3 = A3() ? $(h4) : h4.code;
  14936. }
  14937. x4(1, "loaded", { filePath: c3 }), a3._compile(d3, c3);
  14938. }, "transformer");
  14939. F3(e4, ".js", t4);
  14940. for (const a3 of k3) F3(e4, a3, t4, { enumerable: !r4, writable: true, configurable: true });
  14941. return F3(e4, ".mjs", t4, { writable: true, configurable: true }), () => {
  14942. e4[".js"] === t4 && (e4[".js"] = n3);
  14943. for (const a3 of [...k3, ".mjs"]) e4[a3] === t4 && delete e4[a3];
  14944. };
  14945. }, "createExtensions");
  14946. var le = o3((s4) => (e4) => {
  14947. if ((e4 === "." || e4 === ".." || e4.endsWith("/..")) && (e4 += "/"), _3.test(e4)) {
  14948. let r4 = m4.join(e4, "index.js");
  14949. e4.startsWith("./") && (r4 = `./${r4}`);
  14950. try {
  14951. return s4(r4);
  14952. } catch {
  14953. }
  14954. }
  14955. try {
  14956. return s4(e4);
  14957. } catch (r4) {
  14958. const n3 = r4;
  14959. if (n3.code === "MODULE_NOT_FOUND") try {
  14960. return s4(`${e4}${m4.sep}index.js`);
  14961. } catch {
  14962. }
  14963. throw n3;
  14964. }
  14965. }, "createImplicitResolver");
  14966. var B2 = [".js", ".json"];
  14967. var G2 = [".ts", ".tsx", ".jsx"];
  14968. var fe = [...G2, ...B2];
  14969. var he = [...B2, ...G2];
  14970. var y2 = /* @__PURE__ */ Object.create(null);
  14971. y2[".js"] = [".ts", ".tsx", ".js", ".jsx"], y2[".jsx"] = [".tsx", ".ts", ".jsx", ".js"], y2[".cjs"] = [".cts"], y2[".mjs"] = [".mts"];
  14972. var X = o3((s4) => {
  14973. const e4 = s4.split("?"), r4 = e4[1] ? `?${e4[1]}` : "", [n3] = e4, t4 = m4.extname(n3), a3 = [], i4 = y2[t4];
  14974. if (i4) {
  14975. const f5 = n3.slice(0, -t4.length);
  14976. a3.push(...i4.map((l3) => f5 + l3 + r4));
  14977. }
  14978. const c3 = !(s4.startsWith(v6) || j3(n3)) || n3.includes(J2) || n3.includes("/node_modules/") ? he : fe;
  14979. return a3.push(...c3.map((f5) => n3 + f5 + r4)), a3;
  14980. }, "mapTsExtensions");
  14981. var S2 = o3((s4, e4, r4) => {
  14982. if (x4(3, "resolveTsFilename", { request: e4, isDirectory: _3.test(e4), isTsParent: r4, allowJs: exports2.allowJs }), _3.test(e4) || !r4 && !exports2.allowJs) return;
  14983. const n3 = X(e4);
  14984. if (n3) for (const t4 of n3) try {
  14985. return s4(t4);
  14986. } catch (a3) {
  14987. const { code: i4 } = a3;
  14988. if (i4 !== "MODULE_NOT_FOUND" && i4 !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw a3;
  14989. }
  14990. }, "resolveTsFilename");
  14991. var me = o3((s4, e4) => (r4) => {
  14992. if (x4(3, "resolveTsFilename", { request: r4, isTsParent: e4, isFilePath: j3(r4) }), j3(r4)) {
  14993. const n3 = S2(s4, r4, e4);
  14994. if (n3) return n3;
  14995. }
  14996. try {
  14997. return s4(r4);
  14998. } catch (n3) {
  14999. const t4 = n3;
  15000. if (t4.code === "MODULE_NOT_FOUND") {
  15001. if (t4.path) {
  15002. const i4 = t4.message.match(/^Cannot find module '([^']+)'$/);
  15003. if (i4) {
  15004. const f5 = i4[1], l3 = S2(s4, f5, e4);
  15005. if (l3) return l3;
  15006. }
  15007. const c3 = t4.message.match(/^Cannot find module '([^']+)'. Please verify that the package.json has a valid "main" entry$/);
  15008. if (c3) {
  15009. const f5 = c3[1], l3 = S2(s4, f5, e4);
  15010. if (l3) return l3;
  15011. }
  15012. }
  15013. const a3 = S2(s4, r4, e4);
  15014. if (a3) return a3;
  15015. }
  15016. throw t4;
  15017. }
  15018. }, "createTsExtensionResolver");
  15019. var z2 = "at cjsPreparseModuleExports (node:internal";
  15020. var de = o3((s4) => {
  15021. const e4 = s4.stack.split(`
  15022. `).slice(1);
  15023. return e4[1].includes(z2) || e4[2].includes(z2);
  15024. }, "isFromCjsLexer");
  15025. var ue = o3((s4, e4) => {
  15026. const r4 = s4.split("?"), n3 = new URLSearchParams(r4[1]);
  15027. if (e4 == null ? void 0 : e4.filename) {
  15028. const t4 = W(e4.filename);
  15029. let a3;
  15030. if (t4) {
  15031. const f5 = t4.split("?"), l3 = f5[0];
  15032. a3 = f5[1], e4.filename = l3, e4.path = m4.dirname(l3), e4.paths = u3._nodeModulePaths(e4.path), u3._cache[l3] = e4;
  15033. }
  15034. a3 || (a3 = e4.filename.split("?")[1]);
  15035. const c3 = new URLSearchParams(a3).get("namespace");
  15036. c3 && n3.append("namespace", c3);
  15037. }
  15038. return [r4[0], n3, (t4, a3) => (m4.isAbsolute(t4) && !t4.endsWith(".json") && !t4.endsWith(".node") && !(a3 === 0 && de(new Error())) && (t4 += T(n3)), t4)];
  15039. }, "preserveQuery");
  15040. var pe = o3((s4, e4, r4) => {
  15041. var _a2;
  15042. if (s4.startsWith(v6) && (s4 = L.fileURLToPath(s4)), exports2.tsconfigPathsMatcher && !j3(s4) && !((_a2 = e4 == null ? void 0 : e4.filename) == null ? void 0 : _a2.includes(J2))) {
  15043. const n3 = exports2.tsconfigPathsMatcher(s4);
  15044. for (const t4 of n3) try {
  15045. return r4(t4);
  15046. } catch {
  15047. }
  15048. }
  15049. return r4(s4);
  15050. }, "resolveTsPaths");
  15051. var Pe = o3((s4, e4, r4) => (n3, t4, ...a3) => {
  15052. if (s4.enabled === false) return e4(n3, t4, ...a3);
  15053. n3 = D2(n3);
  15054. const [i4, c3, f5] = ue(n3, t4);
  15055. if ((c3.get("namespace") ?? void 0) !== r4) return e4(n3, t4, ...a3);
  15056. x4(2, "resolve", { request: n3, parent: (t4 == null ? void 0 : t4.filename) ?? t4, restOfArgs: a3 });
  15057. let l3 = o3((P) => e4(P, t4, ...a3), "nextResolveSimple");
  15058. l3 = me(l3, !!(r4 || (t4 == null ? void 0 : t4.filename) && C2.test(t4.filename))), l3 = le(l3);
  15059. const p3 = f5(pe(i4, t4, l3), a3.length);
  15060. return x4(1, "resolved", { request: n3, parent: (t4 == null ? void 0 : t4.filename) ?? t4, resolved: p3 }), p3;
  15061. }, "createResolveFilename");
  15062. var H2 = o3((s4, e4) => {
  15063. if (!e4) throw new Error("The current file path (__filename or import.meta.url) must be provided in the second argument of tsx.require()");
  15064. return s4.startsWith(".") ? ((typeof e4 == "string" && e4.startsWith(v6) || e4 instanceof URL) && (e4 = L.fileURLToPath(e4)), m4.resolve(m4.dirname(e4), s4)) : s4;
  15065. }, "resolveContext");
  15066. var ge = o3((s4) => {
  15067. const { sourceMapsEnabled: e4 } = process, r4 = { enabled: true };
  15068. Q(process.env.TSX_TSCONFIG_PATH), process.setSourceMapsEnabled(true);
  15069. const n3 = u3._resolveFilename, t4 = Pe(r4, n3, s4 == null ? void 0 : s4.namespace);
  15070. u3._resolveFilename = t4;
  15071. const a3 = ce(r4, u3._extensions, s4 == null ? void 0 : s4.namespace), i4 = o3(() => {
  15072. e4 === false && process.setSourceMapsEnabled(false), r4.enabled = false, u3._resolveFilename === t4 && (u3._resolveFilename = n3), a3();
  15073. }, "unregister");
  15074. if (s4 == null ? void 0 : s4.namespace) {
  15075. const c3 = o3((l3, p3) => {
  15076. const P = H2(l3, p3), [d3, h4] = P.split("?"), E2 = new URLSearchParams(h4);
  15077. return s4.namespace && !d3.startsWith("node:") && E2.set("namespace", s4.namespace), Y.require(d3 + T(E2));
  15078. }, "scopedRequire");
  15079. i4.require = c3;
  15080. const f5 = o3((l3, p3, P) => {
  15081. const d3 = H2(l3, p3), [h4, E2] = d3.split("?"), U = new URLSearchParams(E2);
  15082. return s4.namespace && !h4.startsWith("node:") && U.set("namespace", s4.namespace), t4(h4 + T(U), module2, false, P);
  15083. }, "scopedResolve");
  15084. i4.resolve = f5, i4.unregister = i4;
  15085. }
  15086. return i4;
  15087. }, "register");
  15088. exports2.cjsExtensionPattern = se, exports2.debugEnabled = M, exports2.fileUrlPrefix = v6, exports2.inlineSourceMap = $, exports2.interopCjsExports = D2, exports2.isBarePackageNamePattern = ne, exports2.isDirectoryPattern = _3, exports2.isJsonPattern = te, exports2.isRelativePath = N, exports2.loadTsconfig = Q, exports2.logEsm = ae, exports2.mapTsExtensions = X, exports2.register = ge, exports2.requestAcceptsQuery = q3, exports2.tsExtensions = ee, exports2.tsExtensionsPattern = C2;
  15089. }
  15090. });
  15091. // ../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/require-D4F1Lv60.cjs
  15092. var require_require_D4F1Lv60 = __commonJS({
  15093. "../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/require-D4F1Lv60.cjs"(exports2) {
  15094. "use strict";
  15095. var c3 = Object.defineProperty;
  15096. var a3 = (r4, t4) => c3(r4, "name", { value: t4, configurable: true });
  15097. var s4 = require_get_pipe_path_BoR10qr8();
  15098. var n3 = require_register_D46fvsV();
  15099. var e4;
  15100. var i4 = a3((r4, t4) => (e4 || (e4 = n3.register({ namespace: Date.now().toString() })), e4.require(r4, t4)), "tsxRequire");
  15101. var o3 = a3((r4, t4, u3) => (e4 || (e4 = n3.register({ namespace: Date.now().toString() })), e4.resolve(r4, t4, u3)), "resolve");
  15102. o3.paths = s4.require.resolve.paths, i4.resolve = o3, i4.main = s4.require.main, i4.extensions = s4.require.extensions, i4.cache = s4.require.cache, exports2.tsxRequire = i4;
  15103. }
  15104. });
  15105. // ../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/cjs/api/index.cjs
  15106. var require_api = __commonJS({
  15107. "../node_modules/.pnpm/tsx@4.21.0/node_modules/tsx/dist/cjs/api/index.cjs"(exports2) {
  15108. "use strict";
  15109. require_get_pipe_path_BoR10qr8();
  15110. var r4 = require_register_D46fvsV();
  15111. var e4 = require_require_D4F1Lv60();
  15112. require("module"), require("node:path"), require_temporary_directory_B83uKxJF(), require("node:os"), require("node:module"), require("node:url"), require_dist2(), require("node:fs"), require_index_gckBtVBf(), require("esbuild"), require("node:crypto"), require_client_D6NvIMSC(), require("node:net"), require("node:util"), require_index_BWFBUo6r(), exports2.register = r4.register, exports2.require = e4.tsxRequire;
  15113. }
  15114. });
  15115. // src/cli/commands/utils.ts
  15116. var import_fs3, import_hanji2, import_path3, assertES5, InMemoryMutex, registerMutex, tsxRegistered, ensureTsxRegistered, safeRegister, prepareCheckParams, prepareDropParams, prepareGenerateConfig, prepareExportConfig, flattenDatabaseCredentials, flattenPull, preparePushConfig, preparePullConfig, prepareStudioConfig, migrateConfig, prepareMigrateConfig, drizzleConfigFromFile;
  15117. var init_utils3 = __esm({
  15118. "src/cli/commands/utils.ts"() {
  15119. "use strict";
  15120. init_source();
  15121. import_fs3 = require("fs");
  15122. import_hanji2 = __toESM(require_hanji());
  15123. import_path3 = require("path");
  15124. init_esm();
  15125. init_getTablesFilterByExtensions();
  15126. init_global();
  15127. init_schemaValidator();
  15128. init_serializer();
  15129. init_cli();
  15130. init_common();
  15131. init_gel();
  15132. init_libsql();
  15133. init_mysql();
  15134. init_outputs();
  15135. init_postgres();
  15136. init_singlestore();
  15137. init_sqlite();
  15138. init_studio();
  15139. init_views();
  15140. assertES5 = async () => {
  15141. try {
  15142. await Promise.resolve().then(() => (init_es5(), es5_exports));
  15143. } catch (e4) {
  15144. if ("errors" in e4 && Array.isArray(e4.errors) && e4.errors.length > 0) {
  15145. const es5Error = e4.errors.filter((it) => {
  15146. var _a2;
  15147. return (_a2 = it.text) == null ? void 0 : _a2.includes(`("es5") is not supported yet`);
  15148. }).length > 0;
  15149. if (es5Error) {
  15150. console.log(
  15151. error(
  15152. `Please change compilerOptions.target from 'es5' to 'es6' or above in your tsconfig.json`
  15153. )
  15154. );
  15155. process.exit(1);
  15156. }
  15157. }
  15158. console.error(e4);
  15159. process.exit(1);
  15160. }
  15161. };
  15162. InMemoryMutex = class {
  15163. constructor() {
  15164. this.lockPromise = null;
  15165. }
  15166. async withLock(fn) {
  15167. while (this.lockPromise) {
  15168. await this.lockPromise;
  15169. }
  15170. let resolveLock;
  15171. this.lockPromise = new Promise((resolve2) => {
  15172. resolveLock = resolve2;
  15173. });
  15174. try {
  15175. return await fn();
  15176. } finally {
  15177. this.lockPromise = null;
  15178. resolveLock();
  15179. }
  15180. }
  15181. };
  15182. registerMutex = new InMemoryMutex();
  15183. tsxRegistered = false;
  15184. ensureTsxRegistered = () => {
  15185. if (tsxRegistered) return;
  15186. const isBun = typeof globalThis.Bun !== "undefined";
  15187. const isDeno = typeof globalThis.Deno !== "undefined";
  15188. if (isBun || isDeno) {
  15189. tsxRegistered = true;
  15190. return;
  15191. }
  15192. const tsx = require_api();
  15193. tsx.register();
  15194. tsxRegistered = true;
  15195. };
  15196. safeRegister = async (fn) => {
  15197. return registerMutex.withLock(async () => {
  15198. ensureTsxRegistered();
  15199. await assertES5();
  15200. return fn();
  15201. });
  15202. };
  15203. prepareCheckParams = async (options, from) => {
  15204. const config = from === "config" ? await drizzleConfigFromFile(options.config) : options;
  15205. if (!config.out || !config.dialect) {
  15206. let text = `Please provide required params for AWS Data API driver:
  15207. `;
  15208. console.log(error(text));
  15209. console.log(wrapParam("database", config.out));
  15210. console.log(wrapParam("secretArn", config.dialect));
  15211. process.exit(1);
  15212. }
  15213. return { out: config.out, dialect: config.dialect };
  15214. };
  15215. prepareDropParams = async (options, from) => {
  15216. const config = from === "config" ? await drizzleConfigFromFile(options.config) : options;
  15217. if (config.dialect === "gel") {
  15218. console.log(
  15219. error(
  15220. `You can't use 'drop' command with Gel dialect`
  15221. )
  15222. );
  15223. process.exit(1);
  15224. }
  15225. return { out: config.out || "drizzle", bundle: config.driver === "expo" };
  15226. };
  15227. prepareGenerateConfig = async (options, from) => {
  15228. var _a2;
  15229. const config = from === "config" ? await drizzleConfigFromFile(options.config) : options;
  15230. const { schema: schema6, out, breakpoints, dialect: dialect6, driver: driver2, casing: casing2 } = config;
  15231. if (!schema6 || !dialect6) {
  15232. console.log(error("Please provide required params:"));
  15233. console.log(wrapParam("schema", schema6));
  15234. console.log(wrapParam("dialect", dialect6));
  15235. console.log(wrapParam("out", out, true));
  15236. process.exit(1);
  15237. }
  15238. const fileNames = prepareFilenames(schema6);
  15239. if (fileNames.length === 0) {
  15240. (0, import_hanji2.render)(`[${source_default.blue("i")}] No schema file in ${schema6} was found`);
  15241. process.exit(0);
  15242. }
  15243. const prefix2 = ("migrations" in config ? (_a2 = config.migrations) == null ? void 0 : _a2.prefix : options.prefix) || "index";
  15244. return {
  15245. dialect: dialect6,
  15246. name: options.name,
  15247. custom: options.custom || false,
  15248. prefix: prefix2,
  15249. breakpoints: breakpoints ?? true,
  15250. schema: schema6,
  15251. out: out || "drizzle",
  15252. bundle: driver2 === "expo" || driver2 === "durable-sqlite",
  15253. casing: casing2,
  15254. driver: driver2
  15255. };
  15256. };
  15257. prepareExportConfig = async (options, from) => {
  15258. const config = from === "config" ? await drizzleConfigFromFile(options.config, true) : options;
  15259. const { schema: schema6, dialect: dialect6, sql } = config;
  15260. if (!schema6 || !dialect6) {
  15261. console.log(error("Please provide required params:"));
  15262. console.log(wrapParam("schema", schema6));
  15263. console.log(wrapParam("dialect", dialect6));
  15264. process.exit(1);
  15265. }
  15266. const fileNames = prepareFilenames(schema6);
  15267. if (fileNames.length === 0) {
  15268. (0, import_hanji2.render)(`[${source_default.blue("i")}] No schema file in ${schema6} was found`);
  15269. process.exit(0);
  15270. }
  15271. return {
  15272. dialect: dialect6,
  15273. schema: schema6,
  15274. sql
  15275. };
  15276. };
  15277. flattenDatabaseCredentials = (config) => {
  15278. if ("dbCredentials" in config) {
  15279. const { dbCredentials, ...rest } = config;
  15280. return {
  15281. ...rest,
  15282. ...dbCredentials
  15283. };
  15284. }
  15285. return config;
  15286. };
  15287. flattenPull = (config) => {
  15288. if ("dbCredentials" in config) {
  15289. const { dbCredentials, introspect, ...rest } = config;
  15290. return {
  15291. ...rest,
  15292. ...dbCredentials,
  15293. casing: introspect == null ? void 0 : introspect.casing
  15294. };
  15295. }
  15296. return config;
  15297. };
  15298. preparePushConfig = async (options, from) => {
  15299. const raw2 = flattenDatabaseCredentials(
  15300. from === "config" ? await drizzleConfigFromFile(options.config) : options
  15301. );
  15302. raw2.verbose ||= options.verbose;
  15303. raw2.strict ||= options.strict;
  15304. const parsed = pushParams.safeParse(raw2);
  15305. if (parsed.error) {
  15306. console.log(error("Please provide required params:"));
  15307. console.log(wrapParam("dialect", raw2.dialect));
  15308. console.log(wrapParam("schema", raw2.schema));
  15309. process.exit(1);
  15310. }
  15311. const config = parsed.data;
  15312. const schemaFiles = prepareFilenames(config.schema);
  15313. if (schemaFiles.length === 0) {
  15314. (0, import_hanji2.render)(`[${source_default.blue("i")}] No schema file in ${config.schema} was found`);
  15315. process.exit(0);
  15316. }
  15317. const tablesFilterConfig = config.tablesFilter;
  15318. const tablesFilter = tablesFilterConfig ? typeof tablesFilterConfig === "string" ? [tablesFilterConfig] : tablesFilterConfig : [];
  15319. const schemasFilterConfig = config.schemaFilter;
  15320. const schemasFilter = schemasFilterConfig ? typeof schemasFilterConfig === "string" ? [schemasFilterConfig] : schemasFilterConfig : [];
  15321. tablesFilter.push(...getTablesFilterByExtensions(config));
  15322. if (config.dialect === "postgresql") {
  15323. const parsed2 = postgresCredentials.safeParse(config);
  15324. if (!parsed2.success) {
  15325. printConfigConnectionIssues4(config);
  15326. process.exit(1);
  15327. }
  15328. return {
  15329. dialect: "postgresql",
  15330. schemaPath: config.schema,
  15331. strict: config.strict ?? false,
  15332. verbose: config.verbose ?? false,
  15333. force: options.force ?? false,
  15334. credentials: parsed2.data,
  15335. casing: config.casing,
  15336. tablesFilter,
  15337. schemasFilter,
  15338. entities: config.entities
  15339. };
  15340. }
  15341. if (config.dialect === "mysql") {
  15342. const parsed2 = mysqlCredentials.safeParse(config);
  15343. if (!parsed2.success) {
  15344. printConfigConnectionIssues3(config);
  15345. process.exit(1);
  15346. }
  15347. return {
  15348. dialect: "mysql",
  15349. schemaPath: config.schema,
  15350. strict: config.strict ?? false,
  15351. verbose: config.verbose ?? false,
  15352. force: options.force ?? false,
  15353. credentials: parsed2.data,
  15354. casing: config.casing,
  15355. tablesFilter,
  15356. schemasFilter
  15357. };
  15358. }
  15359. if (config.dialect === "singlestore") {
  15360. const parsed2 = singlestoreCredentials.safeParse(config);
  15361. if (!parsed2.success) {
  15362. printConfigConnectionIssues5(config);
  15363. process.exit(1);
  15364. }
  15365. return {
  15366. dialect: "singlestore",
  15367. schemaPath: config.schema,
  15368. strict: config.strict ?? false,
  15369. verbose: config.verbose ?? false,
  15370. force: options.force ?? false,
  15371. credentials: parsed2.data,
  15372. tablesFilter,
  15373. schemasFilter
  15374. };
  15375. }
  15376. if (config.dialect === "sqlite") {
  15377. const parsed2 = sqliteCredentials.safeParse(config);
  15378. if (!parsed2.success) {
  15379. printConfigConnectionIssues6(config, "push");
  15380. process.exit(1);
  15381. }
  15382. return {
  15383. dialect: "sqlite",
  15384. schemaPath: config.schema,
  15385. strict: config.strict ?? false,
  15386. verbose: config.verbose ?? false,
  15387. force: options.force ?? false,
  15388. credentials: parsed2.data,
  15389. casing: config.casing,
  15390. tablesFilter,
  15391. schemasFilter
  15392. };
  15393. }
  15394. if (config.dialect === "turso") {
  15395. const parsed2 = libSQLCredentials.safeParse(config);
  15396. if (!parsed2.success) {
  15397. printConfigConnectionIssues6(config, "push");
  15398. process.exit(1);
  15399. }
  15400. return {
  15401. dialect: "turso",
  15402. schemaPath: config.schema,
  15403. strict: config.strict ?? false,
  15404. verbose: config.verbose ?? false,
  15405. force: options.force ?? false,
  15406. credentials: parsed2.data,
  15407. casing: config.casing,
  15408. tablesFilter,
  15409. schemasFilter
  15410. };
  15411. }
  15412. if (config.dialect === "gel") {
  15413. console.log(
  15414. error(
  15415. `You can't use 'push' command with Gel dialect`
  15416. )
  15417. );
  15418. process.exit(1);
  15419. }
  15420. assertUnreachable(config.dialect);
  15421. };
  15422. preparePullConfig = async (options, from) => {
  15423. var _a2, _b, _c, _d, _e, _f;
  15424. const raw2 = flattenPull(
  15425. from === "config" ? await drizzleConfigFromFile(options.config) : options
  15426. );
  15427. const parsed = pullParams.safeParse(raw2);
  15428. if (parsed.error) {
  15429. console.log(error("Please provide required params:"));
  15430. console.log(wrapParam("dialect", raw2.dialect));
  15431. process.exit(1);
  15432. }
  15433. const config = parsed.data;
  15434. const dialect6 = config.dialect;
  15435. const tablesFilterConfig = config.tablesFilter;
  15436. const tablesFilter = tablesFilterConfig ? typeof tablesFilterConfig === "string" ? [tablesFilterConfig] : tablesFilterConfig : [];
  15437. if (config.extensionsFilters) {
  15438. if (config.extensionsFilters.includes("postgis") && dialect6 === "postgresql") {
  15439. tablesFilter.push(
  15440. ...["!geography_columns", "!geometry_columns", "!spatial_ref_sys"]
  15441. );
  15442. }
  15443. }
  15444. const schemasFilterConfig = config.schemaFilter;
  15445. const schemasFilter = schemasFilterConfig ? typeof schemasFilterConfig === "string" ? [schemasFilterConfig] : schemasFilterConfig : [];
  15446. if (dialect6 === "postgresql") {
  15447. const parsed2 = postgresCredentials.safeParse(config);
  15448. if (!parsed2.success) {
  15449. printConfigConnectionIssues4(config);
  15450. process.exit(1);
  15451. }
  15452. return {
  15453. dialect: "postgresql",
  15454. out: config.out,
  15455. breakpoints: config.breakpoints,
  15456. casing: config.casing,
  15457. credentials: parsed2.data,
  15458. tablesFilter,
  15459. schemasFilter,
  15460. prefix: ((_a2 = config.migrations) == null ? void 0 : _a2.prefix) || "index",
  15461. entities: config.entities
  15462. };
  15463. }
  15464. if (dialect6 === "mysql") {
  15465. const parsed2 = mysqlCredentials.safeParse(config);
  15466. if (!parsed2.success) {
  15467. printConfigConnectionIssues3(config);
  15468. process.exit(1);
  15469. }
  15470. return {
  15471. dialect: "mysql",
  15472. out: config.out,
  15473. breakpoints: config.breakpoints,
  15474. casing: config.casing,
  15475. credentials: parsed2.data,
  15476. tablesFilter,
  15477. schemasFilter,
  15478. prefix: ((_b = config.migrations) == null ? void 0 : _b.prefix) || "index",
  15479. entities: config.entities
  15480. };
  15481. }
  15482. if (dialect6 === "singlestore") {
  15483. const parsed2 = singlestoreCredentials.safeParse(config);
  15484. if (!parsed2.success) {
  15485. printConfigConnectionIssues5(config);
  15486. process.exit(1);
  15487. }
  15488. return {
  15489. dialect: "singlestore",
  15490. out: config.out,
  15491. breakpoints: config.breakpoints,
  15492. casing: config.casing,
  15493. credentials: parsed2.data,
  15494. tablesFilter,
  15495. schemasFilter,
  15496. prefix: ((_c = config.migrations) == null ? void 0 : _c.prefix) || "index",
  15497. entities: config.entities
  15498. };
  15499. }
  15500. if (dialect6 === "sqlite") {
  15501. const parsed2 = sqliteCredentials.safeParse(config);
  15502. if (!parsed2.success) {
  15503. printConfigConnectionIssues6(config, "pull");
  15504. process.exit(1);
  15505. }
  15506. return {
  15507. dialect: "sqlite",
  15508. out: config.out,
  15509. breakpoints: config.breakpoints,
  15510. casing: config.casing,
  15511. credentials: parsed2.data,
  15512. tablesFilter,
  15513. schemasFilter,
  15514. prefix: ((_d = config.migrations) == null ? void 0 : _d.prefix) || "index",
  15515. entities: config.entities
  15516. };
  15517. }
  15518. if (dialect6 === "turso") {
  15519. const parsed2 = libSQLCredentials.safeParse(config);
  15520. if (!parsed2.success) {
  15521. printConfigConnectionIssues2(config, "pull");
  15522. process.exit(1);
  15523. }
  15524. return {
  15525. dialect: dialect6,
  15526. out: config.out,
  15527. breakpoints: config.breakpoints,
  15528. casing: config.casing,
  15529. credentials: parsed2.data,
  15530. tablesFilter,
  15531. schemasFilter,
  15532. prefix: ((_e = config.migrations) == null ? void 0 : _e.prefix) || "index",
  15533. entities: config.entities
  15534. };
  15535. }
  15536. if (dialect6 === "gel") {
  15537. const parsed2 = gelCredentials.safeParse(config);
  15538. if (!parsed2.success) {
  15539. printConfigConnectionIssues(config);
  15540. process.exit(1);
  15541. }
  15542. return {
  15543. dialect: dialect6,
  15544. out: config.out,
  15545. breakpoints: config.breakpoints,
  15546. casing: config.casing,
  15547. credentials: parsed2.data,
  15548. tablesFilter,
  15549. schemasFilter,
  15550. prefix: ((_f = config.migrations) == null ? void 0 : _f.prefix) || "index",
  15551. entities: config.entities
  15552. };
  15553. }
  15554. assertUnreachable(dialect6);
  15555. };
  15556. prepareStudioConfig = async (options) => {
  15557. const params = studioCliParams.parse(options);
  15558. const config = await drizzleConfigFromFile(params.config);
  15559. const result = studioConfig.safeParse(config);
  15560. if (!result.success) {
  15561. if (!("dialect" in config)) {
  15562. console.log(outputs.studio.noDialect());
  15563. }
  15564. process.exit(1);
  15565. }
  15566. if (!("dbCredentials" in config)) {
  15567. console.log(outputs.studio.noCredentials());
  15568. process.exit(1);
  15569. }
  15570. const { host, port } = params;
  15571. const { dialect: dialect6, schema: schema6, casing: casing2 } = result.data;
  15572. const flattened = flattenDatabaseCredentials(config);
  15573. if (dialect6 === "postgresql") {
  15574. const parsed = postgresCredentials.safeParse(flattened);
  15575. if (!parsed.success) {
  15576. printConfigConnectionIssues4(flattened);
  15577. process.exit(1);
  15578. }
  15579. const credentials2 = parsed.data;
  15580. return {
  15581. dialect: dialect6,
  15582. schema: schema6,
  15583. host,
  15584. port,
  15585. credentials: credentials2,
  15586. casing: casing2
  15587. };
  15588. }
  15589. if (dialect6 === "mysql") {
  15590. const parsed = mysqlCredentials.safeParse(flattened);
  15591. if (!parsed.success) {
  15592. printConfigConnectionIssues3(flattened);
  15593. process.exit(1);
  15594. }
  15595. const credentials2 = parsed.data;
  15596. return {
  15597. dialect: dialect6,
  15598. schema: schema6,
  15599. host,
  15600. port,
  15601. credentials: credentials2,
  15602. casing: casing2
  15603. };
  15604. }
  15605. if (dialect6 === "singlestore") {
  15606. const parsed = singlestoreCredentials.safeParse(flattened);
  15607. if (!parsed.success) {
  15608. printConfigConnectionIssues5(flattened);
  15609. process.exit(1);
  15610. }
  15611. const credentials2 = parsed.data;
  15612. return {
  15613. dialect: dialect6,
  15614. schema: schema6,
  15615. host,
  15616. port,
  15617. credentials: credentials2,
  15618. casing: casing2
  15619. };
  15620. }
  15621. if (dialect6 === "sqlite") {
  15622. const parsed = sqliteCredentials.safeParse(flattened);
  15623. if (!parsed.success) {
  15624. printConfigConnectionIssues6(flattened, "studio");
  15625. process.exit(1);
  15626. }
  15627. const credentials2 = parsed.data;
  15628. return {
  15629. dialect: dialect6,
  15630. schema: schema6,
  15631. host,
  15632. port,
  15633. credentials: credentials2,
  15634. casing: casing2
  15635. };
  15636. }
  15637. if (dialect6 === "turso") {
  15638. const parsed = libSQLCredentials.safeParse(flattened);
  15639. if (!parsed.success) {
  15640. printConfigConnectionIssues2(flattened, "studio");
  15641. process.exit(1);
  15642. }
  15643. const credentials2 = parsed.data;
  15644. return {
  15645. dialect: dialect6,
  15646. schema: schema6,
  15647. host,
  15648. port,
  15649. credentials: credentials2,
  15650. casing: casing2
  15651. };
  15652. }
  15653. if (dialect6 === "gel") {
  15654. console.log(
  15655. error(
  15656. `You can't use 'studio' command with Gel dialect`
  15657. )
  15658. );
  15659. process.exit(1);
  15660. }
  15661. assertUnreachable(dialect6);
  15662. };
  15663. migrateConfig = objectType({
  15664. dialect: dialect4,
  15665. out: stringType().optional().default("drizzle"),
  15666. migrations: configMigrations
  15667. });
  15668. prepareMigrateConfig = async (configPath) => {
  15669. const config = await drizzleConfigFromFile(configPath);
  15670. const parsed = migrateConfig.safeParse(config);
  15671. if (parsed.error) {
  15672. console.log(error("Please provide required params:"));
  15673. console.log(wrapParam("dialect", config.dialect));
  15674. process.exit(1);
  15675. }
  15676. const { dialect: dialect6, out } = parsed.data;
  15677. const { schema: schema6, table: table6 } = parsed.data.migrations || {};
  15678. const flattened = flattenDatabaseCredentials(config);
  15679. if (dialect6 === "postgresql") {
  15680. const parsed2 = postgresCredentials.safeParse(flattened);
  15681. if (!parsed2.success) {
  15682. printConfigConnectionIssues4(flattened);
  15683. process.exit(1);
  15684. }
  15685. const credentials2 = parsed2.data;
  15686. return {
  15687. dialect: dialect6,
  15688. out,
  15689. credentials: credentials2,
  15690. schema: schema6,
  15691. table: table6
  15692. };
  15693. }
  15694. if (dialect6 === "mysql") {
  15695. const parsed2 = mysqlCredentials.safeParse(flattened);
  15696. if (!parsed2.success) {
  15697. printConfigConnectionIssues3(flattened);
  15698. process.exit(1);
  15699. }
  15700. const credentials2 = parsed2.data;
  15701. return {
  15702. dialect: dialect6,
  15703. out,
  15704. credentials: credentials2,
  15705. schema: schema6,
  15706. table: table6
  15707. };
  15708. }
  15709. if (dialect6 === "singlestore") {
  15710. const parsed2 = singlestoreCredentials.safeParse(flattened);
  15711. if (!parsed2.success) {
  15712. printConfigConnectionIssues5(flattened);
  15713. process.exit(1);
  15714. }
  15715. const credentials2 = parsed2.data;
  15716. return {
  15717. dialect: dialect6,
  15718. out,
  15719. credentials: credentials2,
  15720. schema: schema6,
  15721. table: table6
  15722. };
  15723. }
  15724. if (dialect6 === "sqlite") {
  15725. const parsed2 = sqliteCredentials.safeParse(flattened);
  15726. if (!parsed2.success) {
  15727. printConfigConnectionIssues6(flattened, "migrate");
  15728. process.exit(1);
  15729. }
  15730. const credentials2 = parsed2.data;
  15731. return {
  15732. dialect: dialect6,
  15733. out,
  15734. credentials: credentials2,
  15735. schema: schema6,
  15736. table: table6
  15737. };
  15738. }
  15739. if (dialect6 === "turso") {
  15740. const parsed2 = libSQLCredentials.safeParse(flattened);
  15741. if (!parsed2.success) {
  15742. printConfigConnectionIssues2(flattened, "migrate");
  15743. process.exit(1);
  15744. }
  15745. const credentials2 = parsed2.data;
  15746. return {
  15747. dialect: dialect6,
  15748. out,
  15749. credentials: credentials2,
  15750. schema: schema6,
  15751. table: table6
  15752. };
  15753. }
  15754. if (dialect6 === "gel") {
  15755. console.log(
  15756. error(
  15757. `You can't use 'migrate' command with Gel dialect`
  15758. )
  15759. );
  15760. process.exit(1);
  15761. }
  15762. assertUnreachable(dialect6);
  15763. };
  15764. drizzleConfigFromFile = async (configPath, isExport) => {
  15765. const prefix2 = process.env.TEST_CONFIG_PATH_PREFIX || "";
  15766. const defaultTsConfigExists = (0, import_fs3.existsSync)((0, import_path3.resolve)((0, import_path3.join)(prefix2, "drizzle.config.ts")));
  15767. const defaultJsConfigExists = (0, import_fs3.existsSync)((0, import_path3.resolve)((0, import_path3.join)(prefix2, "drizzle.config.js")));
  15768. (0, import_fs3.existsSync)(
  15769. (0, import_path3.join)((0, import_path3.resolve)("drizzle.config.json"))
  15770. );
  15771. const defaultConfigPath = defaultTsConfigExists ? "drizzle.config.ts" : defaultJsConfigExists ? "drizzle.config.js" : "drizzle.config.json";
  15772. if (!configPath && !isExport) {
  15773. console.log(
  15774. source_default.gray(
  15775. `No config path provided, using default '${defaultConfigPath}'`
  15776. )
  15777. );
  15778. }
  15779. const path4 = (0, import_path3.resolve)((0, import_path3.join)(prefix2, configPath ?? defaultConfigPath));
  15780. if (!(0, import_fs3.existsSync)(path4)) {
  15781. console.log(`${path4} file does not exist`);
  15782. process.exit(1);
  15783. }
  15784. if (!isExport) console.log(source_default.grey(`Reading config file '${path4}'`));
  15785. return safeRegister(async () => {
  15786. const required = require(`${path4}`);
  15787. const content = required.default ?? required;
  15788. const res = configCommonSchema.safeParse(content);
  15789. if (!res.success) {
  15790. console.log(res.error);
  15791. if (!("dialect" in content)) {
  15792. console.log(error("Please specify 'dialect' param in config file"));
  15793. }
  15794. process.exit(1);
  15795. }
  15796. return res.data;
  15797. });
  15798. };
  15799. }
  15800. });
  15801. // src/serializer/mysqlImports.ts
  15802. var mysqlImports_exports = {};
  15803. __export(mysqlImports_exports, {
  15804. prepareFromExports: () => prepareFromExports,
  15805. prepareFromMySqlImports: () => prepareFromMySqlImports
  15806. });
  15807. var import_drizzle_orm, import_mysql_core, prepareFromExports, prepareFromMySqlImports;
  15808. var init_mysqlImports = __esm({
  15809. "src/serializer/mysqlImports.ts"() {
  15810. "use strict";
  15811. import_drizzle_orm = require("drizzle-orm");
  15812. import_mysql_core = require("drizzle-orm/mysql-core");
  15813. init_utils3();
  15814. prepareFromExports = (exports2) => {
  15815. const tables = [];
  15816. const views = [];
  15817. const i0values = Object.values(exports2);
  15818. i0values.forEach((t4) => {
  15819. if ((0, import_drizzle_orm.is)(t4, import_mysql_core.MySqlTable)) {
  15820. tables.push(t4);
  15821. }
  15822. if ((0, import_drizzle_orm.is)(t4, import_mysql_core.MySqlView)) {
  15823. views.push(t4);
  15824. }
  15825. });
  15826. return { tables, views };
  15827. };
  15828. prepareFromMySqlImports = async (imports) => {
  15829. const tables = [];
  15830. const views = [];
  15831. await safeRegister(async () => {
  15832. for (let i4 = 0; i4 < imports.length; i4++) {
  15833. const it = imports[i4];
  15834. const i0 = require(`${it}`);
  15835. const prepared = prepareFromExports(i0);
  15836. tables.push(...prepared.tables);
  15837. views.push(...prepared.views);
  15838. }
  15839. });
  15840. return { tables: Array.from(new Set(tables)), views };
  15841. };
  15842. }
  15843. });
  15844. // src/serializer/utils.ts
  15845. function getColumnCasing(column11, casing2) {
  15846. if (!column11.name) return "";
  15847. return !column11.keyAsName || casing2 === void 0 ? column11.name : casing2 === "camelCase" ? (0, import_casing.toCamelCase)(column11.name) : (0, import_casing.toSnakeCase)(column11.name);
  15848. }
  15849. var import_casing, sqlToStr;
  15850. var init_utils4 = __esm({
  15851. "src/serializer/utils.ts"() {
  15852. "use strict";
  15853. import_casing = require("drizzle-orm/casing");
  15854. sqlToStr = (sql, casing2) => {
  15855. return sql.toQuery({
  15856. escapeName: () => {
  15857. throw new Error("we don't support params for `sql` default values");
  15858. },
  15859. escapeParam: () => {
  15860. throw new Error("we don't support params for `sql` default values");
  15861. },
  15862. escapeString: () => {
  15863. throw new Error("we don't support params for `sql` default values");
  15864. },
  15865. casing: new import_casing.CasingCache(casing2)
  15866. }).sql;
  15867. };
  15868. }
  15869. });
  15870. // src/serializer/mysqlSerializer.ts
  15871. var mysqlSerializer_exports = {};
  15872. __export(mysqlSerializer_exports, {
  15873. fromDatabase: () => fromDatabase,
  15874. generateMySqlSnapshot: () => generateMySqlSnapshot,
  15875. indexName: () => indexName
  15876. });
  15877. function clearDefaults(defaultValue, collate) {
  15878. if (typeof collate === "undefined" || collate === null) {
  15879. collate = `utf8mb4`;
  15880. }
  15881. let resultDefault = defaultValue;
  15882. collate = `_${collate}`;
  15883. if (defaultValue.startsWith(collate)) {
  15884. resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
  15885. if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
  15886. return `('${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}')`;
  15887. } else {
  15888. return `'${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}'`;
  15889. }
  15890. } else {
  15891. return `(${resultDefault})`;
  15892. }
  15893. }
  15894. var import_drizzle_orm2, import_mysql_core2, indexName, handleEnumType, generateMySqlSnapshot, fromDatabase;
  15895. var init_mysqlSerializer = __esm({
  15896. "src/serializer/mysqlSerializer.ts"() {
  15897. "use strict";
  15898. init_source();
  15899. import_drizzle_orm2 = require("drizzle-orm");
  15900. import_mysql_core2 = require("drizzle-orm/mysql-core");
  15901. init_outputs();
  15902. init_utils2();
  15903. init_utils4();
  15904. indexName = (tableName, columns) => {
  15905. return `${tableName}_${columns.join("_")}_index`;
  15906. };
  15907. handleEnumType = (type) => {
  15908. let str = type.split("(")[1];
  15909. str = str.substring(0, str.length - 1);
  15910. const values = str.split(",").map((v6) => `'${escapeSingleQuotes(v6.substring(1, v6.length - 1))}'`);
  15911. return `enum(${values.join(",")})`;
  15912. };
  15913. generateMySqlSnapshot = (tables, views, casing2) => {
  15914. const dialect6 = new import_mysql_core2.MySqlDialect({ casing: casing2 });
  15915. const result = {};
  15916. const resultViews = {};
  15917. const internal = { tables: {}, indexes: {} };
  15918. for (const table6 of tables) {
  15919. const {
  15920. name: tableName,
  15921. columns,
  15922. indexes,
  15923. foreignKeys,
  15924. schema: schema6,
  15925. checks,
  15926. primaryKeys,
  15927. uniqueConstraints
  15928. } = (0, import_mysql_core2.getTableConfig)(table6);
  15929. const columnsObject = {};
  15930. const indexesObject = {};
  15931. const foreignKeysObject = {};
  15932. const primaryKeysObject = {};
  15933. const uniqueConstraintObject = {};
  15934. const checkConstraintObject = {};
  15935. let checksInTable = {};
  15936. columns.forEach((column11) => {
  15937. const name = getColumnCasing(column11, casing2);
  15938. const notNull = column11.notNull;
  15939. const sqlType = column11.getSQLType();
  15940. const sqlTypeLowered = sqlType.toLowerCase();
  15941. const autoIncrement = typeof column11.autoIncrement === "undefined" ? false : column11.autoIncrement;
  15942. const generated = column11.generated;
  15943. const columnToSet = {
  15944. name,
  15945. type: sqlType.startsWith("enum") ? handleEnumType(sqlType) : sqlType,
  15946. primaryKey: false,
  15947. // If field is autoincrement it's notNull by default
  15948. // notNull: autoIncrement ? true : notNull,
  15949. notNull,
  15950. autoincrement: autoIncrement,
  15951. onUpdate: column11.hasOnUpdateNow,
  15952. generated: generated ? {
  15953. as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm2.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
  15954. type: generated.mode ?? "stored"
  15955. } : void 0
  15956. };
  15957. if (column11.primary) {
  15958. primaryKeysObject[`${tableName}_${name}`] = {
  15959. name: `${tableName}_${name}`,
  15960. columns: [name]
  15961. };
  15962. }
  15963. if (column11.isUnique) {
  15964. const existingUnique = uniqueConstraintObject[column11.uniqueName];
  15965. if (typeof existingUnique !== "undefined") {
  15966. console.log(
  15967. `
  15968. ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
  15969. tableName
  15970. )} table.
  15971. The unique constraint ${source_default.underline.blue(
  15972. column11.uniqueName
  15973. )} on the ${source_default.underline.blue(
  15974. name
  15975. )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  15976. existingUnique.columns.join(",")
  15977. )} columns
  15978. `)}`
  15979. );
  15980. process.exit(1);
  15981. }
  15982. uniqueConstraintObject[column11.uniqueName] = {
  15983. name: column11.uniqueName,
  15984. columns: [columnToSet.name]
  15985. };
  15986. }
  15987. if (column11.default !== void 0) {
  15988. if ((0, import_drizzle_orm2.is)(column11.default, import_drizzle_orm2.SQL)) {
  15989. columnToSet.default = sqlToStr(column11.default, casing2);
  15990. } else {
  15991. if (typeof column11.default === "string") {
  15992. columnToSet.default = `'${escapeSingleQuotes(column11.default)}'`;
  15993. } else {
  15994. if (sqlTypeLowered === "json") {
  15995. columnToSet.default = `'${JSON.stringify(column11.default)}'`;
  15996. } else if (column11.default instanceof Date) {
  15997. if (sqlTypeLowered === "date") {
  15998. columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`;
  15999. } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
  16000. columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`;
  16001. }
  16002. } else {
  16003. columnToSet.default = column11.default;
  16004. }
  16005. }
  16006. if (["blob", "text", "json"].includes(column11.getSQLType())) {
  16007. columnToSet.default = `(${columnToSet.default})`;
  16008. }
  16009. }
  16010. }
  16011. columnsObject[name] = columnToSet;
  16012. });
  16013. primaryKeys.map((pk) => {
  16014. const originalColumnNames = pk.columns.map((c3) => c3.name);
  16015. const columnNames = pk.columns.map((c3) => getColumnCasing(c3, casing2));
  16016. let name = pk.getName();
  16017. if (casing2 !== void 0) {
  16018. for (let i4 = 0; i4 < originalColumnNames.length; i4++) {
  16019. name = name.replace(originalColumnNames[i4], columnNames[i4]);
  16020. }
  16021. }
  16022. primaryKeysObject[name] = {
  16023. name,
  16024. columns: columnNames
  16025. };
  16026. for (const column11 of pk.columns) {
  16027. columnsObject[getColumnCasing(column11, casing2)].notNull = true;
  16028. }
  16029. });
  16030. uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
  16031. const columnNames = unq.columns.map((c3) => getColumnCasing(c3, casing2));
  16032. const name = unq.name ?? (0, import_mysql_core2.uniqueKeyName)(table6, columnNames);
  16033. const existingUnique = uniqueConstraintObject[name];
  16034. if (typeof existingUnique !== "undefined") {
  16035. console.log(
  16036. `
  16037. ${withStyle.errorWarning(
  16038. `We've found duplicated unique constraint names in ${source_default.underline.blue(
  16039. tableName
  16040. )} table.
  16041. The unique constraint ${source_default.underline.blue(
  16042. name
  16043. )} on the ${source_default.underline.blue(
  16044. columnNames.join(",")
  16045. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  16046. existingUnique.columns.join(",")
  16047. )} columns
  16048. `
  16049. )}`
  16050. );
  16051. process.exit(1);
  16052. }
  16053. uniqueConstraintObject[name] = {
  16054. name: unq.name,
  16055. columns: columnNames
  16056. };
  16057. });
  16058. const fks = foreignKeys.map((fk5) => {
  16059. const tableFrom = tableName;
  16060. const onDelete = fk5.onDelete ?? "no action";
  16061. const onUpdate = fk5.onUpdate ?? "no action";
  16062. const reference = fk5.reference();
  16063. const referenceFT = reference.foreignTable;
  16064. const tableTo = (0, import_drizzle_orm2.getTableName)(referenceFT);
  16065. const originalColumnsFrom = reference.columns.map((it) => it.name);
  16066. const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
  16067. const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
  16068. const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
  16069. let name = fk5.getName();
  16070. if (casing2 !== void 0) {
  16071. for (let i4 = 0; i4 < originalColumnsFrom.length; i4++) {
  16072. name = name.replace(originalColumnsFrom[i4], columnsFrom[i4]);
  16073. }
  16074. for (let i4 = 0; i4 < originalColumnsTo.length; i4++) {
  16075. name = name.replace(originalColumnsTo[i4], columnsTo[i4]);
  16076. }
  16077. }
  16078. return {
  16079. name,
  16080. tableFrom,
  16081. tableTo,
  16082. columnsFrom,
  16083. columnsTo,
  16084. onDelete,
  16085. onUpdate
  16086. };
  16087. });
  16088. fks.forEach((it) => {
  16089. foreignKeysObject[it.name] = it;
  16090. });
  16091. indexes.forEach((value) => {
  16092. const columns2 = value.config.columns;
  16093. const name = value.config.name;
  16094. let indexColumns = columns2.map((it) => {
  16095. var _a2;
  16096. if ((0, import_drizzle_orm2.is)(it, import_drizzle_orm2.SQL)) {
  16097. const sql = dialect6.sqlToQuery(it, "indexes").sql;
  16098. if (typeof internal.indexes[name] === "undefined") {
  16099. internal.indexes[name] = {
  16100. columns: {
  16101. [sql]: {
  16102. isExpression: true
  16103. }
  16104. }
  16105. };
  16106. } else {
  16107. if (typeof ((_a2 = internal.indexes[name]) == null ? void 0 : _a2.columns[sql]) === "undefined") {
  16108. internal.indexes[name].columns[sql] = {
  16109. isExpression: true
  16110. };
  16111. } else {
  16112. internal.indexes[name].columns[sql].isExpression = true;
  16113. }
  16114. }
  16115. return sql;
  16116. } else {
  16117. return `${getColumnCasing(it, casing2)}`;
  16118. }
  16119. });
  16120. if (value.config.unique) {
  16121. if (typeof uniqueConstraintObject[name] !== "undefined") {
  16122. console.log(
  16123. `
  16124. ${withStyle.errorWarning(
  16125. `We've found duplicated unique constraint names in ${source_default.underline.blue(
  16126. tableName
  16127. )} table.
  16128. The unique index ${source_default.underline.blue(
  16129. name
  16130. )} on the ${source_default.underline.blue(
  16131. indexColumns.join(",")
  16132. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  16133. uniqueConstraintObject[name].columns.join(",")
  16134. )} columns
  16135. `
  16136. )}`
  16137. );
  16138. process.exit(1);
  16139. }
  16140. } else {
  16141. if (typeof foreignKeysObject[name] !== "undefined") {
  16142. console.log(
  16143. `
  16144. ${withStyle.errorWarning(
  16145. `In MySQL, when creating a foreign key, an index is automatically generated with the same name as the foreign key constraint.
  16146. We have encountered a collision between the index name on columns ${source_default.underline.blue(
  16147. indexColumns.join(",")
  16148. )} and the foreign key on columns ${source_default.underline.blue(
  16149. foreignKeysObject[name].columnsFrom.join(",")
  16150. )}. Please change either the index name or the foreign key name. For more information, please refer to https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html
  16151. `
  16152. )}`
  16153. );
  16154. process.exit(1);
  16155. }
  16156. }
  16157. indexesObject[name] = {
  16158. name,
  16159. columns: indexColumns,
  16160. isUnique: value.config.unique ?? false,
  16161. using: value.config.using,
  16162. algorithm: value.config.algorithm,
  16163. lock: value.config.lock
  16164. };
  16165. });
  16166. checks.forEach((check2) => {
  16167. check2;
  16168. const checkName = check2.name;
  16169. if (typeof checksInTable[tableName] !== "undefined") {
  16170. if (checksInTable[tableName].includes(check2.name)) {
  16171. console.log(
  16172. `
  16173. ${withStyle.errorWarning(
  16174. `We've found duplicated check constraint name in ${source_default.underline.blue(
  16175. tableName
  16176. )}. Please rename your check constraint in the ${source_default.underline.blue(
  16177. tableName
  16178. )} table`
  16179. )}`
  16180. );
  16181. process.exit(1);
  16182. }
  16183. checksInTable[tableName].push(checkName);
  16184. } else {
  16185. checksInTable[tableName] = [check2.name];
  16186. }
  16187. checkConstraintObject[checkName] = {
  16188. name: checkName,
  16189. value: dialect6.sqlToQuery(check2.value).sql
  16190. };
  16191. });
  16192. if (!schema6) {
  16193. result[tableName] = {
  16194. name: tableName,
  16195. columns: columnsObject,
  16196. indexes: indexesObject,
  16197. foreignKeys: foreignKeysObject,
  16198. compositePrimaryKeys: primaryKeysObject,
  16199. uniqueConstraints: uniqueConstraintObject,
  16200. checkConstraint: checkConstraintObject
  16201. };
  16202. }
  16203. }
  16204. for (const view5 of views) {
  16205. const {
  16206. isExisting,
  16207. name,
  16208. query,
  16209. schema: schema6,
  16210. selectedFields,
  16211. algorithm,
  16212. sqlSecurity,
  16213. withCheckOption
  16214. } = (0, import_mysql_core2.getViewConfig)(view5);
  16215. const columnsObject = {};
  16216. const existingView = resultViews[name];
  16217. if (typeof existingView !== "undefined") {
  16218. console.log(
  16219. `
  16220. ${withStyle.errorWarning(
  16221. `We've found duplicated view name across ${source_default.underline.blue(
  16222. schema6 ?? "public"
  16223. )} schema. Please rename your view`
  16224. )}`
  16225. );
  16226. process.exit(1);
  16227. }
  16228. for (const key in selectedFields) {
  16229. if ((0, import_drizzle_orm2.is)(selectedFields[key], import_mysql_core2.MySqlColumn)) {
  16230. const column11 = selectedFields[key];
  16231. const notNull = column11.notNull;
  16232. const sqlTypeLowered = column11.getSQLType().toLowerCase();
  16233. const autoIncrement = typeof column11.autoIncrement === "undefined" ? false : column11.autoIncrement;
  16234. const generated = column11.generated;
  16235. const columnToSet = {
  16236. name: column11.name,
  16237. type: column11.getSQLType(),
  16238. primaryKey: false,
  16239. // If field is autoincrement it's notNull by default
  16240. // notNull: autoIncrement ? true : notNull,
  16241. notNull,
  16242. autoincrement: autoIncrement,
  16243. onUpdate: column11.hasOnUpdateNow,
  16244. generated: generated ? {
  16245. as: (0, import_drizzle_orm2.is)(generated.as, import_drizzle_orm2.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
  16246. type: generated.mode ?? "stored"
  16247. } : void 0
  16248. };
  16249. if (column11.default !== void 0) {
  16250. if ((0, import_drizzle_orm2.is)(column11.default, import_drizzle_orm2.SQL)) {
  16251. columnToSet.default = sqlToStr(column11.default, casing2);
  16252. } else {
  16253. if (typeof column11.default === "string") {
  16254. columnToSet.default = `'${column11.default}'`;
  16255. } else {
  16256. if (sqlTypeLowered === "json") {
  16257. columnToSet.default = `'${JSON.stringify(column11.default)}'`;
  16258. } else if (column11.default instanceof Date) {
  16259. if (sqlTypeLowered === "date") {
  16260. columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`;
  16261. } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
  16262. columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`;
  16263. }
  16264. } else {
  16265. columnToSet.default = column11.default;
  16266. }
  16267. }
  16268. if (["blob", "text", "json"].includes(column11.getSQLType())) {
  16269. columnToSet.default = `(${columnToSet.default})`;
  16270. }
  16271. }
  16272. }
  16273. columnsObject[column11.name] = columnToSet;
  16274. }
  16275. }
  16276. resultViews[name] = {
  16277. columns: columnsObject,
  16278. name,
  16279. isExisting,
  16280. definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql,
  16281. withCheckOption,
  16282. algorithm: algorithm ?? "undefined",
  16283. // set default values
  16284. sqlSecurity: sqlSecurity ?? "definer"
  16285. // set default values
  16286. };
  16287. }
  16288. return {
  16289. version: "5",
  16290. dialect: "mysql",
  16291. tables: result,
  16292. views: resultViews,
  16293. _meta: {
  16294. tables: {},
  16295. columns: {}
  16296. },
  16297. internal
  16298. };
  16299. };
  16300. fromDatabase = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => {
  16301. const result = {};
  16302. const internals = { tables: {}, indexes: {} };
  16303. const columns = await db.query(`select * from information_schema.columns
  16304. where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
  16305. order by table_name, ordinal_position;`);
  16306. const response = columns;
  16307. const schemas = [];
  16308. let columnsCount = 0;
  16309. let tablesCount = /* @__PURE__ */ new Set();
  16310. let indexesCount = 0;
  16311. let foreignKeysCount = 0;
  16312. let checksCount = 0;
  16313. let viewsCount = 0;
  16314. const idxs = await db.query(
  16315. `select * from INFORMATION_SCHEMA.STATISTICS
  16316. WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
  16317. );
  16318. const idxRows = idxs;
  16319. for (const column11 of response) {
  16320. if (!tablesFilter(column11["TABLE_NAME"])) continue;
  16321. columnsCount += 1;
  16322. if (progressCallback) {
  16323. progressCallback("columns", columnsCount, "fetching");
  16324. }
  16325. const schema6 = column11["TABLE_SCHEMA"];
  16326. const tableName = column11["TABLE_NAME"];
  16327. tablesCount.add(`${schema6}.${tableName}`);
  16328. if (progressCallback) {
  16329. progressCallback("columns", tablesCount.size, "fetching");
  16330. }
  16331. const columnName = column11["COLUMN_NAME"];
  16332. const isNullable = column11["IS_NULLABLE"] === "YES";
  16333. const dataType = column11["DATA_TYPE"];
  16334. const columnType = column11["COLUMN_TYPE"];
  16335. const isPrimary = column11["COLUMN_KEY"] === "PRI";
  16336. const columnDefault = column11["COLUMN_DEFAULT"];
  16337. const collation = column11["CHARACTER_SET_NAME"];
  16338. const geenratedExpression = column11["GENERATION_EXPRESSION"];
  16339. let columnExtra = column11["EXTRA"];
  16340. let isAutoincrement = false;
  16341. let isDefaultAnExpression = false;
  16342. if (typeof column11["EXTRA"] !== "undefined") {
  16343. columnExtra = column11["EXTRA"];
  16344. isAutoincrement = column11["EXTRA"] === "auto_increment";
  16345. isDefaultAnExpression = column11["EXTRA"].includes("DEFAULT_GENERATED");
  16346. }
  16347. if (schema6 !== inputSchema) {
  16348. schemas.push(schema6);
  16349. }
  16350. const table6 = result[tableName];
  16351. let changedType = columnType;
  16352. if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) {
  16353. const uniqueIdx = idxRows.filter(
  16354. (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0
  16355. );
  16356. if (uniqueIdx && uniqueIdx.length === 1) {
  16357. changedType = columnType.replace("bigint unsigned", "serial");
  16358. }
  16359. }
  16360. if (columnType.includes("decimal(10,0)")) {
  16361. changedType = columnType.replace("decimal(10,0)", "decimal");
  16362. }
  16363. let onUpdate = void 0;
  16364. if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) {
  16365. onUpdate = true;
  16366. }
  16367. const newColumn = {
  16368. default: columnDefault === null || columnDefault === void 0 ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `'${escapeSingleQuotes(columnDefault)}'`,
  16369. autoincrement: isAutoincrement,
  16370. name: columnName,
  16371. type: changedType,
  16372. primaryKey: false,
  16373. notNull: !isNullable,
  16374. onUpdate,
  16375. generated: geenratedExpression ? {
  16376. as: geenratedExpression,
  16377. type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored"
  16378. } : void 0
  16379. };
  16380. if (isDefaultAnExpression) {
  16381. if (typeof internals.tables[tableName] === "undefined") {
  16382. internals.tables[tableName] = {
  16383. columns: {
  16384. [columnName]: {
  16385. isDefaultAnExpression: true
  16386. }
  16387. }
  16388. };
  16389. } else {
  16390. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  16391. internals.tables[tableName].columns[columnName] = {
  16392. isDefaultAnExpression: true
  16393. };
  16394. } else {
  16395. internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
  16396. }
  16397. }
  16398. }
  16399. if (!table6) {
  16400. result[tableName] = {
  16401. name: tableName,
  16402. columns: {
  16403. [columnName]: newColumn
  16404. },
  16405. compositePrimaryKeys: {},
  16406. indexes: {},
  16407. foreignKeys: {},
  16408. uniqueConstraints: {},
  16409. checkConstraint: {}
  16410. };
  16411. } else {
  16412. result[tableName].columns[columnName] = newColumn;
  16413. }
  16414. }
  16415. const tablePks = await db.query(
  16416. `SELECT table_name, column_name, ordinal_position
  16417. FROM information_schema.table_constraints t
  16418. LEFT JOIN information_schema.key_column_usage k
  16419. USING(constraint_name,table_schema,table_name)
  16420. WHERE t.constraint_type='PRIMARY KEY'
  16421. and table_name != '__drizzle_migrations'
  16422. AND t.table_schema = '${inputSchema}'
  16423. ORDER BY ordinal_position`
  16424. );
  16425. const tableToPk = {};
  16426. const tableToPkRows = tablePks;
  16427. for (const tableToPkRow of tableToPkRows) {
  16428. const tableName = tableToPkRow["TABLE_NAME"];
  16429. const columnName = tableToPkRow["COLUMN_NAME"];
  16430. const position = tableToPkRow["ordinal_position"];
  16431. if (typeof result[tableName] === "undefined") {
  16432. continue;
  16433. }
  16434. if (typeof tableToPk[tableName] === "undefined") {
  16435. tableToPk[tableName] = [columnName];
  16436. } else {
  16437. tableToPk[tableName].push(columnName);
  16438. }
  16439. }
  16440. for (const [key, value] of Object.entries(tableToPk)) {
  16441. result[key].compositePrimaryKeys = {
  16442. [`${key}_${value.join("_")}`]: {
  16443. name: `${key}_${value.join("_")}`,
  16444. columns: value
  16445. }
  16446. };
  16447. }
  16448. if (progressCallback) {
  16449. progressCallback("columns", columnsCount, "done");
  16450. progressCallback("tables", tablesCount.size, "done");
  16451. }
  16452. try {
  16453. const fks = await db.query(
  16454. `SELECT
  16455. kcu.TABLE_SCHEMA,
  16456. kcu.TABLE_NAME,
  16457. kcu.CONSTRAINT_NAME,
  16458. kcu.COLUMN_NAME,
  16459. kcu.REFERENCED_TABLE_SCHEMA,
  16460. kcu.REFERENCED_TABLE_NAME,
  16461. kcu.REFERENCED_COLUMN_NAME,
  16462. rc.UPDATE_RULE,
  16463. rc.DELETE_RULE
  16464. FROM
  16465. INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
  16466. LEFT JOIN
  16467. information_schema.referential_constraints rc
  16468. ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
  16469. WHERE kcu.TABLE_SCHEMA = '${inputSchema}' AND kcu.CONSTRAINT_NAME != 'PRIMARY'
  16470. AND kcu.REFERENCED_TABLE_NAME IS NOT NULL;`
  16471. );
  16472. const fkRows = fks;
  16473. for (const fkRow of fkRows) {
  16474. foreignKeysCount += 1;
  16475. if (progressCallback) {
  16476. progressCallback("fks", foreignKeysCount, "fetching");
  16477. }
  16478. const tableSchema = fkRow["TABLE_SCHEMA"];
  16479. const tableName = fkRow["TABLE_NAME"];
  16480. const constraintName = fkRow["CONSTRAINT_NAME"];
  16481. const columnName = fkRow["COLUMN_NAME"];
  16482. const refTableSchema = fkRow["REFERENCED_TABLE_SCHEMA"];
  16483. const refTableName = fkRow["REFERENCED_TABLE_NAME"];
  16484. const refColumnName = fkRow["REFERENCED_COLUMN_NAME"];
  16485. const updateRule = fkRow["UPDATE_RULE"];
  16486. const deleteRule = fkRow["DELETE_RULE"];
  16487. const tableInResult = result[tableName];
  16488. if (typeof tableInResult === "undefined") continue;
  16489. if (typeof tableInResult.foreignKeys[constraintName] !== "undefined") {
  16490. tableInResult.foreignKeys[constraintName].columnsFrom.push(columnName);
  16491. tableInResult.foreignKeys[constraintName].columnsTo.push(
  16492. refColumnName
  16493. );
  16494. } else {
  16495. tableInResult.foreignKeys[constraintName] = {
  16496. name: constraintName,
  16497. tableFrom: tableName,
  16498. tableTo: refTableName,
  16499. columnsFrom: [columnName],
  16500. columnsTo: [refColumnName],
  16501. onDelete: deleteRule == null ? void 0 : deleteRule.toLowerCase(),
  16502. onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
  16503. };
  16504. }
  16505. tableInResult.foreignKeys[constraintName].columnsFrom = [
  16506. ...new Set(tableInResult.foreignKeys[constraintName].columnsFrom)
  16507. ];
  16508. tableInResult.foreignKeys[constraintName].columnsTo = [
  16509. ...new Set(tableInResult.foreignKeys[constraintName].columnsTo)
  16510. ];
  16511. }
  16512. } catch (e4) {
  16513. }
  16514. if (progressCallback) {
  16515. progressCallback("fks", foreignKeysCount, "done");
  16516. }
  16517. for (const idxRow of idxRows) {
  16518. const tableSchema = idxRow["TABLE_SCHEMA"];
  16519. const tableName = idxRow["TABLE_NAME"];
  16520. const constraintName = idxRow["INDEX_NAME"];
  16521. const columnName = idxRow["COLUMN_NAME"];
  16522. const isUnique = idxRow["NON_UNIQUE"] === 0;
  16523. const tableInResult = result[tableName];
  16524. if (typeof tableInResult === "undefined") continue;
  16525. indexesCount += 1;
  16526. if (progressCallback) {
  16527. progressCallback("indexes", indexesCount, "fetching");
  16528. }
  16529. if (isUnique) {
  16530. if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") {
  16531. tableInResult.uniqueConstraints[constraintName].columns.push(
  16532. columnName
  16533. );
  16534. } else {
  16535. tableInResult.uniqueConstraints[constraintName] = {
  16536. name: constraintName,
  16537. columns: [columnName]
  16538. };
  16539. }
  16540. } else {
  16541. if (typeof tableInResult.foreignKeys[constraintName] === "undefined") {
  16542. if (typeof tableInResult.indexes[constraintName] !== "undefined") {
  16543. tableInResult.indexes[constraintName].columns.push(columnName);
  16544. } else {
  16545. tableInResult.indexes[constraintName] = {
  16546. name: constraintName,
  16547. columns: [columnName],
  16548. isUnique
  16549. };
  16550. }
  16551. }
  16552. }
  16553. }
  16554. const views = await db.query(
  16555. `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';`
  16556. );
  16557. const resultViews = {};
  16558. viewsCount = views.length;
  16559. if (progressCallback) {
  16560. progressCallback("views", viewsCount, "fetching");
  16561. }
  16562. for await (const view5 of views) {
  16563. const viewName = view5["TABLE_NAME"];
  16564. const definition = view5["VIEW_DEFINITION"];
  16565. const withCheckOption = view5["CHECK_OPTION"] === "NONE" ? void 0 : view5["CHECK_OPTION"].toLowerCase();
  16566. const sqlSecurity = view5["SECURITY_TYPE"].toLowerCase();
  16567. const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`);
  16568. const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/);
  16569. const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0;
  16570. const columns2 = result[viewName].columns;
  16571. delete result[viewName];
  16572. resultViews[viewName] = {
  16573. columns: columns2,
  16574. isExisting: false,
  16575. name: viewName,
  16576. algorithm,
  16577. definition,
  16578. sqlSecurity,
  16579. withCheckOption
  16580. };
  16581. }
  16582. if (progressCallback) {
  16583. progressCallback("indexes", indexesCount, "done");
  16584. progressCallback("enums", 0, "done");
  16585. progressCallback("views", viewsCount, "done");
  16586. }
  16587. const checkConstraints = await db.query(
  16588. `SELECT
  16589. tc.table_name,
  16590. tc.constraint_name,
  16591. cc.check_clause
  16592. FROM
  16593. information_schema.table_constraints tc
  16594. JOIN
  16595. information_schema.check_constraints cc
  16596. ON tc.constraint_name = cc.constraint_name
  16597. WHERE
  16598. tc.constraint_schema = '${inputSchema}'
  16599. AND
  16600. tc.constraint_type = 'CHECK';`
  16601. );
  16602. checksCount += checkConstraints.length;
  16603. if (progressCallback) {
  16604. progressCallback("checks", checksCount, "fetching");
  16605. }
  16606. for (const checkConstraintRow of checkConstraints) {
  16607. const constraintName = checkConstraintRow["CONSTRAINT_NAME"];
  16608. const constraintValue = checkConstraintRow["CHECK_CLAUSE"];
  16609. const tableName = checkConstraintRow["TABLE_NAME"];
  16610. const tableInResult = result[tableName];
  16611. tableInResult.checkConstraint[constraintName] = {
  16612. name: constraintName,
  16613. value: constraintValue
  16614. };
  16615. }
  16616. if (progressCallback) {
  16617. progressCallback("checks", checksCount, "done");
  16618. }
  16619. return {
  16620. version: "5",
  16621. dialect: "mysql",
  16622. tables: result,
  16623. views: resultViews,
  16624. _meta: {
  16625. tables: {},
  16626. columns: {}
  16627. },
  16628. internal: internals
  16629. };
  16630. };
  16631. }
  16632. });
  16633. // src/serializer/pgImports.ts
  16634. var pgImports_exports = {};
  16635. __export(pgImports_exports, {
  16636. prepareFromExports: () => prepareFromExports2,
  16637. prepareFromPgImports: () => prepareFromPgImports
  16638. });
  16639. var import_drizzle_orm3, import_pg_core, import_relations, prepareFromExports2, prepareFromPgImports;
  16640. var init_pgImports = __esm({
  16641. "src/serializer/pgImports.ts"() {
  16642. "use strict";
  16643. import_drizzle_orm3 = require("drizzle-orm");
  16644. import_pg_core = require("drizzle-orm/pg-core");
  16645. import_relations = require("drizzle-orm/relations");
  16646. init_utils3();
  16647. prepareFromExports2 = (exports2) => {
  16648. const tables = [];
  16649. const enums = [];
  16650. const schemas = [];
  16651. const sequences = [];
  16652. const roles = [];
  16653. const policies = [];
  16654. const views = [];
  16655. const matViews = [];
  16656. const relations5 = [];
  16657. const i0values = Object.values(exports2);
  16658. i0values.forEach((t4) => {
  16659. if ((0, import_pg_core.isPgEnum)(t4)) {
  16660. enums.push(t4);
  16661. return;
  16662. }
  16663. if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgTable)) {
  16664. tables.push(t4);
  16665. }
  16666. if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgSchema)) {
  16667. schemas.push(t4);
  16668. }
  16669. if ((0, import_pg_core.isPgView)(t4)) {
  16670. views.push(t4);
  16671. }
  16672. if ((0, import_pg_core.isPgMaterializedView)(t4)) {
  16673. matViews.push(t4);
  16674. }
  16675. if ((0, import_pg_core.isPgSequence)(t4)) {
  16676. sequences.push(t4);
  16677. }
  16678. if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgRole)) {
  16679. roles.push(t4);
  16680. }
  16681. if ((0, import_drizzle_orm3.is)(t4, import_pg_core.PgPolicy)) {
  16682. policies.push(t4);
  16683. }
  16684. if ((0, import_drizzle_orm3.is)(t4, import_relations.Relations)) {
  16685. relations5.push(t4);
  16686. }
  16687. });
  16688. return { tables, enums, schemas, sequences, views, matViews, roles, policies, relations: relations5 };
  16689. };
  16690. prepareFromPgImports = async (imports) => {
  16691. const tables = [];
  16692. const enums = [];
  16693. const schemas = [];
  16694. const sequences = [];
  16695. const views = [];
  16696. const roles = [];
  16697. const policies = [];
  16698. const matViews = [];
  16699. const relations5 = [];
  16700. await safeRegister(async () => {
  16701. for (let i4 = 0; i4 < imports.length; i4++) {
  16702. const it = imports[i4];
  16703. const i0 = require(`${it}`);
  16704. const prepared = prepareFromExports2(i0);
  16705. tables.push(...prepared.tables);
  16706. enums.push(...prepared.enums);
  16707. schemas.push(...prepared.schemas);
  16708. sequences.push(...prepared.sequences);
  16709. views.push(...prepared.views);
  16710. matViews.push(...prepared.matViews);
  16711. roles.push(...prepared.roles);
  16712. policies.push(...prepared.policies);
  16713. relations5.push(...prepared.relations);
  16714. }
  16715. });
  16716. return {
  16717. tables: Array.from(new Set(tables)),
  16718. enums,
  16719. schemas,
  16720. sequences,
  16721. views,
  16722. matViews,
  16723. roles,
  16724. policies,
  16725. relations: relations5
  16726. };
  16727. };
  16728. }
  16729. });
  16730. // src/extensions/vector.ts
  16731. var vectorOps;
  16732. var init_vector = __esm({
  16733. "src/extensions/vector.ts"() {
  16734. "use strict";
  16735. vectorOps = [
  16736. "vector_l2_ops",
  16737. "vector_ip_ops",
  16738. "vector_cosine_ops",
  16739. "vector_l1_ops",
  16740. "bit_hamming_ops",
  16741. "bit_jaccard_ops",
  16742. "halfvec_l2_ops",
  16743. "sparsevec_l2_ops"
  16744. ];
  16745. }
  16746. });
  16747. // src/serializer/pgSerializer.ts
  16748. var pgSerializer_exports = {};
  16749. __export(pgSerializer_exports, {
  16750. buildArrayString: () => buildArrayString,
  16751. fromDatabase: () => fromDatabase2,
  16752. generatePgSnapshot: () => generatePgSnapshot,
  16753. indexName: () => indexName2
  16754. });
  16755. function stringFromIdentityProperty(field) {
  16756. return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : String(field);
  16757. }
  16758. function maxRangeForIdentityBasedOn(columnType) {
  16759. return columnType === "integer" ? "2147483647" : columnType === "bigint" ? "9223372036854775807" : "32767";
  16760. }
  16761. function minRangeForIdentityBasedOn(columnType) {
  16762. return columnType === "integer" ? "-2147483648" : columnType === "bigint" ? "-9223372036854775808" : "-32768";
  16763. }
  16764. function stringFromDatabaseIdentityProperty(field) {
  16765. return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
  16766. }
  16767. function buildArrayString(array2, sqlType) {
  16768. sqlType = sqlType.split("[")[0];
  16769. const values = array2.map((value) => {
  16770. if (typeof value === "number" || typeof value === "bigint") {
  16771. return value.toString();
  16772. } else if (typeof value === "boolean") {
  16773. return value ? "true" : "false";
  16774. } else if (Array.isArray(value)) {
  16775. return buildArrayString(value, sqlType);
  16776. } else if (value instanceof Date) {
  16777. if (sqlType === "date") {
  16778. return `"${value.toISOString().split("T")[0]}"`;
  16779. } else if (sqlType === "timestamp") {
  16780. return `"${value.toISOString().replace("T", " ").slice(0, 23)}"`;
  16781. } else {
  16782. return `"${value.toISOString()}"`;
  16783. }
  16784. } else if (typeof value === "object") {
  16785. return `"${JSON.stringify(value).replaceAll('"', '\\"')}"`;
  16786. }
  16787. return `"${value}"`;
  16788. }).join(",");
  16789. return `{${values}}`;
  16790. }
  16791. function prepareRoles(entities) {
  16792. let useRoles = false;
  16793. const includeRoles = [];
  16794. const excludeRoles = [];
  16795. if (entities && entities.roles) {
  16796. if (typeof entities.roles === "object") {
  16797. if (entities.roles.provider) {
  16798. if (entities.roles.provider === "supabase") {
  16799. excludeRoles.push(...[
  16800. "anon",
  16801. "authenticator",
  16802. "authenticated",
  16803. "service_role",
  16804. "supabase_auth_admin",
  16805. "supabase_storage_admin",
  16806. "dashboard_user",
  16807. "supabase_admin"
  16808. ]);
  16809. } else if (entities.roles.provider === "neon") {
  16810. excludeRoles.push(...["authenticated", "anonymous"]);
  16811. }
  16812. }
  16813. if (entities.roles.include) {
  16814. includeRoles.push(...entities.roles.include);
  16815. }
  16816. if (entities.roles.exclude) {
  16817. excludeRoles.push(...entities.roles.exclude);
  16818. }
  16819. } else {
  16820. useRoles = entities.roles;
  16821. }
  16822. }
  16823. return { useRoles, includeRoles, excludeRoles };
  16824. }
  16825. var import_drizzle_orm4, import_pg_core2, indexName2, generatePgSnapshot, trimChar, fromDatabase2, defaultForColumn, getColumnsInfoQuery;
  16826. var init_pgSerializer = __esm({
  16827. "src/serializer/pgSerializer.ts"() {
  16828. "use strict";
  16829. init_source();
  16830. import_drizzle_orm4 = require("drizzle-orm");
  16831. import_pg_core2 = require("drizzle-orm/pg-core");
  16832. init_vector();
  16833. init_outputs();
  16834. init_utils2();
  16835. init_utils4();
  16836. indexName2 = (tableName, columns) => {
  16837. return `${tableName}_${columns.join("_")}_index`;
  16838. };
  16839. generatePgSnapshot = (tables, enums, schemas, sequences, roles, policies, views, matViews, casing2, schemaFilter) => {
  16840. var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o;
  16841. const dialect6 = new import_pg_core2.PgDialect({ casing: casing2 });
  16842. const result = {};
  16843. const resultViews = {};
  16844. const sequencesToReturn = {};
  16845. const rolesToReturn = {};
  16846. const policiesToReturn = {};
  16847. const indexesInSchema = {};
  16848. for (const table6 of tables) {
  16849. const checksInTable = {};
  16850. const {
  16851. name: tableName,
  16852. columns,
  16853. indexes,
  16854. foreignKeys,
  16855. checks,
  16856. schema: schema6,
  16857. primaryKeys,
  16858. uniqueConstraints,
  16859. policies: policies2,
  16860. enableRLS
  16861. } = (0, import_pg_core2.getTableConfig)(table6);
  16862. if (schemaFilter && !schemaFilter.includes(schema6 ?? "public")) {
  16863. continue;
  16864. }
  16865. const columnsObject = {};
  16866. const indexesObject = {};
  16867. const checksObject = {};
  16868. const foreignKeysObject = {};
  16869. const primaryKeysObject = {};
  16870. const uniqueConstraintObject = {};
  16871. const policiesObject = {};
  16872. columns.forEach((column11) => {
  16873. var _a3, _b2, _c2, _d2, _e2, _f2;
  16874. const name = getColumnCasing(column11, casing2);
  16875. const notNull = column11.notNull;
  16876. const primaryKey = column11.primary;
  16877. const sqlTypeLowered = column11.getSQLType().toLowerCase();
  16878. const getEnumSchema = (column12) => {
  16879. while ((0, import_drizzle_orm4.is)(column12, import_pg_core2.PgArray)) {
  16880. column12 = column12.baseColumn;
  16881. }
  16882. return (0, import_drizzle_orm4.is)(column12, import_pg_core2.PgEnumColumn) ? column12.enum.schema || "public" : void 0;
  16883. };
  16884. const typeSchema = getEnumSchema(column11);
  16885. const generated = column11.generated;
  16886. const identity = column11.generatedIdentity;
  16887. const increment = stringFromIdentityProperty((_a3 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _a3.increment) ?? "1";
  16888. const minValue = stringFromIdentityProperty((_b2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _b2.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column11.columnType) : "1");
  16889. const maxValue = stringFromIdentityProperty((_c2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _c2.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column11.getSQLType()));
  16890. const startWith = stringFromIdentityProperty((_d2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _d2.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
  16891. const cache3 = stringFromIdentityProperty((_e2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _e2.cache) ?? "1";
  16892. const columnToSet = {
  16893. name,
  16894. type: column11.getSQLType(),
  16895. typeSchema,
  16896. primaryKey,
  16897. notNull,
  16898. generated: generated ? {
  16899. as: (0, import_drizzle_orm4.is)(generated.as, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
  16900. type: "stored"
  16901. } : void 0,
  16902. identity: identity ? {
  16903. type: identity.type,
  16904. name: identity.sequenceName ?? `${tableName}_${name}_seq`,
  16905. schema: schema6 ?? "public",
  16906. increment,
  16907. startWith,
  16908. minValue,
  16909. maxValue,
  16910. cache: cache3,
  16911. cycle: ((_f2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _f2.cycle) ?? false
  16912. } : void 0
  16913. };
  16914. if (column11.isUnique) {
  16915. const existingUnique = uniqueConstraintObject[column11.uniqueName];
  16916. if (typeof existingUnique !== "undefined") {
  16917. console.log(
  16918. `
  16919. ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
  16920. tableName
  16921. )} table.
  16922. The unique constraint ${source_default.underline.blue(
  16923. column11.uniqueName
  16924. )} on the ${source_default.underline.blue(
  16925. name
  16926. )} column is conflicting with a unique constraint name already defined for ${source_default.underline.blue(
  16927. existingUnique.columns.join(",")
  16928. )} columns
  16929. `)}`
  16930. );
  16931. process.exit(1);
  16932. }
  16933. uniqueConstraintObject[column11.uniqueName] = {
  16934. name: column11.uniqueName,
  16935. nullsNotDistinct: column11.uniqueType === "not distinct",
  16936. columns: [columnToSet.name]
  16937. };
  16938. }
  16939. if (column11.default !== void 0) {
  16940. if ((0, import_drizzle_orm4.is)(column11.default, import_drizzle_orm4.SQL)) {
  16941. columnToSet.default = sqlToStr(column11.default, casing2);
  16942. } else {
  16943. if (typeof column11.default === "string") {
  16944. columnToSet.default = `'${escapeSingleQuotes(column11.default)}'`;
  16945. } else {
  16946. if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
  16947. columnToSet.default = `'${JSON.stringify(column11.default)}'::${sqlTypeLowered}`;
  16948. } else if (column11.default instanceof Date) {
  16949. if (sqlTypeLowered === "date") {
  16950. columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`;
  16951. } else if (sqlTypeLowered === "timestamp") {
  16952. columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`;
  16953. } else {
  16954. columnToSet.default = `'${column11.default.toISOString()}'`;
  16955. }
  16956. } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column11.default)) {
  16957. columnToSet.default = `'${buildArrayString(column11.default, sqlTypeLowered)}'`;
  16958. } else {
  16959. columnToSet.default = column11.default;
  16960. }
  16961. }
  16962. }
  16963. }
  16964. columnsObject[name] = columnToSet;
  16965. });
  16966. primaryKeys.map((pk) => {
  16967. const originalColumnNames = pk.columns.map((c3) => c3.name);
  16968. const columnNames = pk.columns.map((c3) => getColumnCasing(c3, casing2));
  16969. let name = pk.getName();
  16970. if (casing2 !== void 0) {
  16971. for (let i4 = 0; i4 < originalColumnNames.length; i4++) {
  16972. name = name.replace(originalColumnNames[i4], columnNames[i4]);
  16973. }
  16974. }
  16975. primaryKeysObject[name] = {
  16976. name,
  16977. columns: columnNames
  16978. };
  16979. });
  16980. uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
  16981. const columnNames = unq.columns.map((c3) => getColumnCasing(c3, casing2));
  16982. const name = unq.name ?? (0, import_pg_core2.uniqueKeyName)(table6, columnNames);
  16983. const existingUnique = uniqueConstraintObject[name];
  16984. if (typeof existingUnique !== "undefined") {
  16985. console.log(
  16986. `
  16987. ${withStyle.errorWarning(
  16988. `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table.
  16989. The unique constraint ${source_default.underline.blue(name)} on the ${source_default.underline.blue(
  16990. columnNames.join(",")
  16991. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
  16992. `
  16993. )}`
  16994. );
  16995. process.exit(1);
  16996. }
  16997. uniqueConstraintObject[name] = {
  16998. name: unq.name,
  16999. nullsNotDistinct: unq.nullsNotDistinct,
  17000. columns: columnNames
  17001. };
  17002. });
  17003. const fks = foreignKeys.map((fk5) => {
  17004. const tableFrom = tableName;
  17005. const onDelete = fk5.onDelete;
  17006. const onUpdate = fk5.onUpdate;
  17007. const reference = fk5.reference();
  17008. const tableTo = (0, import_drizzle_orm4.getTableName)(reference.foreignTable);
  17009. const schemaTo = (0, import_pg_core2.getTableConfig)(reference.foreignTable).schema;
  17010. const originalColumnsFrom = reference.columns.map((it) => it.name);
  17011. const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
  17012. const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
  17013. const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
  17014. let name = fk5.getName();
  17015. if (casing2 !== void 0) {
  17016. for (let i4 = 0; i4 < originalColumnsFrom.length; i4++) {
  17017. name = name.replace(originalColumnsFrom[i4], columnsFrom[i4]);
  17018. }
  17019. for (let i4 = 0; i4 < originalColumnsTo.length; i4++) {
  17020. name = name.replace(originalColumnsTo[i4], columnsTo[i4]);
  17021. }
  17022. }
  17023. return {
  17024. name,
  17025. tableFrom,
  17026. tableTo,
  17027. schemaTo,
  17028. columnsFrom,
  17029. columnsTo,
  17030. onDelete,
  17031. onUpdate
  17032. };
  17033. });
  17034. fks.forEach((it) => {
  17035. foreignKeysObject[it.name] = it;
  17036. });
  17037. indexes.forEach((value) => {
  17038. const columns2 = value.config.columns;
  17039. let indexColumnNames = [];
  17040. columns2.forEach((it) => {
  17041. if ((0, import_drizzle_orm4.is)(it, import_drizzle_orm4.SQL)) {
  17042. if (typeof value.config.name === "undefined") {
  17043. console.log(
  17044. `
  17045. ${withStyle.errorWarning(
  17046. `Please specify an index name in ${(0, import_drizzle_orm4.getTableName)(value.config.table)} table that has "${dialect6.sqlToQuery(it).sql}" expression. We can generate index names for indexes on columns only; for expressions in indexes, you need to specify the name yourself.`
  17047. )}`
  17048. );
  17049. process.exit(1);
  17050. }
  17051. }
  17052. it = it;
  17053. const name2 = getColumnCasing(it, casing2);
  17054. if (!(0, import_drizzle_orm4.is)(it, import_drizzle_orm4.SQL) && it.type === "PgVector" && typeof it.indexConfig.opClass === "undefined") {
  17055. console.log(
  17056. `
  17057. ${withStyle.errorWarning(
  17058. `You are specifying an index on the ${source_default.blueBright(
  17059. name2
  17060. )} column inside the ${source_default.blueBright(
  17061. tableName
  17062. )} table with the ${source_default.blueBright(
  17063. "vector"
  17064. )} type without specifying an operator class. Vector extension doesn't have a default operator class, so you need to specify one of the available options. Here is a list of available op classes for the vector extension: [${vectorOps.map((it2) => `${source_default.underline(`${it2}`)}`).join(", ")}].
  17065. You can specify it using current syntax: ${source_default.underline(
  17066. `index("${value.config.name}").using("${value.config.method}", table.${name2}.op("${vectorOps[0]}"))`
  17067. )}
  17068. You can check the "pg_vector" docs for more info: https://github.com/pgvector/pgvector?tab=readme-ov-file#indexing
  17069. `
  17070. )}`
  17071. );
  17072. process.exit(1);
  17073. }
  17074. indexColumnNames.push(name2);
  17075. });
  17076. const name = value.config.name ? value.config.name : indexName2(tableName, indexColumnNames);
  17077. let indexColumns = columns2.map(
  17078. (it) => {
  17079. var _a3, _b2, _c2, _d2, _e2;
  17080. if ((0, import_drizzle_orm4.is)(it, import_drizzle_orm4.SQL)) {
  17081. return {
  17082. expression: dialect6.sqlToQuery(it, "indexes").sql,
  17083. asc: true,
  17084. isExpression: true,
  17085. nulls: "last"
  17086. };
  17087. } else {
  17088. it = it;
  17089. return {
  17090. expression: getColumnCasing(it, casing2),
  17091. isExpression: false,
  17092. asc: ((_a3 = it.indexConfig) == null ? void 0 : _a3.order) === "asc",
  17093. nulls: ((_b2 = it.indexConfig) == null ? void 0 : _b2.nulls) ? (_c2 = it.indexConfig) == null ? void 0 : _c2.nulls : ((_d2 = it.indexConfig) == null ? void 0 : _d2.order) === "desc" ? "first" : "last",
  17094. opclass: (_e2 = it.indexConfig) == null ? void 0 : _e2.opClass
  17095. };
  17096. }
  17097. }
  17098. );
  17099. if (typeof indexesInSchema[schema6 ?? "public"] !== "undefined") {
  17100. if (indexesInSchema[schema6 ?? "public"].includes(name)) {
  17101. console.log(
  17102. `
  17103. ${withStyle.errorWarning(
  17104. `We've found duplicated index name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your index in either the ${source_default.underline.blue(
  17105. tableName
  17106. )} table or the table with the duplicated index name`
  17107. )}`
  17108. );
  17109. process.exit(1);
  17110. }
  17111. indexesInSchema[schema6 ?? "public"].push(name);
  17112. } else {
  17113. indexesInSchema[schema6 ?? "public"] = [name];
  17114. }
  17115. indexesObject[name] = {
  17116. name,
  17117. columns: indexColumns,
  17118. isUnique: value.config.unique ?? false,
  17119. where: value.config.where ? dialect6.sqlToQuery(value.config.where).sql : void 0,
  17120. concurrently: value.config.concurrently ?? false,
  17121. method: value.config.method ?? "btree",
  17122. with: value.config.with ?? {}
  17123. };
  17124. });
  17125. policies2.forEach((policy5) => {
  17126. var _a3, _b2;
  17127. const mappedTo = [];
  17128. if (!policy5.to) {
  17129. mappedTo.push("public");
  17130. } else {
  17131. if (policy5.to && typeof policy5.to === "string") {
  17132. mappedTo.push(policy5.to);
  17133. } else if (policy5.to && (0, import_drizzle_orm4.is)(policy5.to, import_pg_core2.PgRole)) {
  17134. mappedTo.push(policy5.to.name);
  17135. } else if (policy5.to && Array.isArray(policy5.to)) {
  17136. policy5.to.forEach((it) => {
  17137. if (typeof it === "string") {
  17138. mappedTo.push(it);
  17139. } else if ((0, import_drizzle_orm4.is)(it, import_pg_core2.PgRole)) {
  17140. mappedTo.push(it.name);
  17141. }
  17142. });
  17143. }
  17144. }
  17145. if (policiesObject[policy5.name] !== void 0) {
  17146. console.log(
  17147. `
  17148. ${withStyle.errorWarning(
  17149. `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue(
  17150. policy5.name
  17151. )} name`
  17152. )}`
  17153. );
  17154. process.exit(1);
  17155. }
  17156. policiesObject[policy5.name] = {
  17157. name: policy5.name,
  17158. as: ((_a3 = policy5.as) == null ? void 0 : _a3.toUpperCase()) ?? "PERMISSIVE",
  17159. for: ((_b2 = policy5.for) == null ? void 0 : _b2.toUpperCase()) ?? "ALL",
  17160. to: mappedTo.sort(),
  17161. using: (0, import_drizzle_orm4.is)(policy5.using, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0,
  17162. withCheck: (0, import_drizzle_orm4.is)(policy5.withCheck, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0
  17163. };
  17164. });
  17165. checks.forEach((check2) => {
  17166. const checkName = check2.name;
  17167. if (typeof checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] !== "undefined") {
  17168. if (checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].includes(check2.name)) {
  17169. console.log(
  17170. `
  17171. ${withStyle.errorWarning(
  17172. `We've found duplicated check constraint name across ${source_default.underline.blue(
  17173. schema6 ?? "public"
  17174. )} schema in ${source_default.underline.blue(
  17175. tableName
  17176. )}. Please rename your check constraint in either the ${source_default.underline.blue(
  17177. tableName
  17178. )} table or the table with the duplicated check contraint name`
  17179. )}`
  17180. );
  17181. process.exit(1);
  17182. }
  17183. checksInTable[`"${schema6 ?? "public"}"."${tableName}"`].push(checkName);
  17184. } else {
  17185. checksInTable[`"${schema6 ?? "public"}"."${tableName}"`] = [check2.name];
  17186. }
  17187. checksObject[checkName] = {
  17188. name: checkName,
  17189. value: dialect6.sqlToQuery(check2.value).sql
  17190. };
  17191. });
  17192. const tableKey2 = `${schema6 ?? "public"}.${tableName}`;
  17193. result[tableKey2] = {
  17194. name: tableName,
  17195. schema: schema6 ?? "",
  17196. columns: columnsObject,
  17197. indexes: indexesObject,
  17198. foreignKeys: foreignKeysObject,
  17199. compositePrimaryKeys: primaryKeysObject,
  17200. uniqueConstraints: uniqueConstraintObject,
  17201. policies: policiesObject,
  17202. checkConstraints: checksObject,
  17203. isRLSEnabled: enableRLS
  17204. };
  17205. }
  17206. for (const policy5 of policies) {
  17207. if (!policy5._linkedTable) {
  17208. console.log(
  17209. `
  17210. ${withStyle.errorWarning(
  17211. `"Policy ${policy5.name} was skipped because it was not linked to any table. You should either include the policy in a table or use .link() on the policy to link it to any table you have. For more information, please check:`
  17212. )}`
  17213. );
  17214. continue;
  17215. }
  17216. const tableConfig = (0, import_pg_core2.getTableConfig)(policy5._linkedTable);
  17217. const tableKey2 = `${tableConfig.schema ?? "public"}.${tableConfig.name}`;
  17218. const mappedTo = [];
  17219. if (!policy5.to) {
  17220. mappedTo.push("public");
  17221. } else {
  17222. if (policy5.to && typeof policy5.to === "string") {
  17223. mappedTo.push(policy5.to);
  17224. } else if (policy5.to && (0, import_drizzle_orm4.is)(policy5.to, import_pg_core2.PgRole)) {
  17225. mappedTo.push(policy5.to.name);
  17226. } else if (policy5.to && Array.isArray(policy5.to)) {
  17227. policy5.to.forEach((it) => {
  17228. if (typeof it === "string") {
  17229. mappedTo.push(it);
  17230. } else if ((0, import_drizzle_orm4.is)(it, import_pg_core2.PgRole)) {
  17231. mappedTo.push(it.name);
  17232. }
  17233. });
  17234. }
  17235. }
  17236. if (((_a2 = result[tableKey2]) == null ? void 0 : _a2.policies[policy5.name]) !== void 0 || policiesToReturn[policy5.name] !== void 0) {
  17237. console.log(
  17238. `
  17239. ${withStyle.errorWarning(
  17240. `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue(
  17241. policy5.name
  17242. )} name`
  17243. )}`
  17244. );
  17245. process.exit(1);
  17246. }
  17247. const mappedPolicy = {
  17248. name: policy5.name,
  17249. as: ((_b = policy5.as) == null ? void 0 : _b.toUpperCase()) ?? "PERMISSIVE",
  17250. for: ((_c = policy5.for) == null ? void 0 : _c.toUpperCase()) ?? "ALL",
  17251. to: mappedTo.sort(),
  17252. using: (0, import_drizzle_orm4.is)(policy5.using, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0,
  17253. withCheck: (0, import_drizzle_orm4.is)(policy5.withCheck, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0
  17254. };
  17255. if (result[tableKey2]) {
  17256. result[tableKey2].policies[policy5.name] = mappedPolicy;
  17257. } else {
  17258. policiesToReturn[policy5.name] = {
  17259. ...mappedPolicy,
  17260. schema: tableConfig.schema ?? "public",
  17261. on: `"${tableConfig.schema ?? "public"}"."${tableConfig.name}"`
  17262. };
  17263. }
  17264. }
  17265. for (const sequence of sequences) {
  17266. const name = sequence.seqName;
  17267. if (typeof sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] === "undefined") {
  17268. const increment = stringFromIdentityProperty((_d = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _d.increment) ?? "1";
  17269. const minValue = stringFromIdentityProperty((_e = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _e.minValue) ?? (parseFloat(increment) < 0 ? "-9223372036854775808" : "1");
  17270. const maxValue = stringFromIdentityProperty((_f = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _f.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : "9223372036854775807");
  17271. const startWith = stringFromIdentityProperty((_g = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _g.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
  17272. const cache3 = stringFromIdentityProperty((_h = sequence == null ? void 0 : sequence.seqOptions) == null ? void 0 : _h.cache) ?? "1";
  17273. sequencesToReturn[`${sequence.schema ?? "public"}.${name}`] = {
  17274. name,
  17275. schema: sequence.schema ?? "public",
  17276. increment,
  17277. startWith,
  17278. minValue,
  17279. maxValue,
  17280. cache: cache3,
  17281. cycle: ((_i = sequence.seqOptions) == null ? void 0 : _i.cycle) ?? false
  17282. };
  17283. } else {
  17284. }
  17285. }
  17286. for (const role of roles) {
  17287. if (!role._existing) {
  17288. rolesToReturn[role.name] = {
  17289. name: role.name,
  17290. createDb: role.createDb === void 0 ? false : role.createDb,
  17291. createRole: role.createRole === void 0 ? false : role.createRole,
  17292. inherit: role.inherit === void 0 ? true : role.inherit
  17293. };
  17294. }
  17295. }
  17296. const combinedViews = [...views, ...matViews];
  17297. for (const view5 of combinedViews) {
  17298. let viewName;
  17299. let schema6;
  17300. let query;
  17301. let selectedFields;
  17302. let isExisting;
  17303. let withOption;
  17304. let tablespace;
  17305. let using;
  17306. let withNoData;
  17307. let materialized = false;
  17308. if ((0, import_drizzle_orm4.is)(view5, import_pg_core2.PgView)) {
  17309. ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption } = (0, import_pg_core2.getViewConfig)(view5));
  17310. } else {
  17311. ({ name: viewName, schema: schema6, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = (0, import_pg_core2.getMaterializedViewConfig)(view5));
  17312. materialized = true;
  17313. }
  17314. const viewSchema = schema6 ?? "public";
  17315. const viewKey = `${viewSchema}.${viewName}`;
  17316. const columnsObject = {};
  17317. const uniqueConstraintObject = {};
  17318. const existingView = resultViews[viewKey];
  17319. if (typeof existingView !== "undefined") {
  17320. console.log(
  17321. `
  17322. ${withStyle.errorWarning(
  17323. `We've found duplicated view name across ${source_default.underline.blue(schema6 ?? "public")} schema. Please rename your view`
  17324. )}`
  17325. );
  17326. process.exit(1);
  17327. }
  17328. for (const key in selectedFields) {
  17329. if ((0, import_drizzle_orm4.is)(selectedFields[key], import_pg_core2.PgColumn)) {
  17330. const column11 = selectedFields[key];
  17331. const notNull = column11.notNull;
  17332. const primaryKey = column11.primary;
  17333. const sqlTypeLowered = column11.getSQLType().toLowerCase();
  17334. const typeSchema = (0, import_drizzle_orm4.is)(column11, import_pg_core2.PgEnumColumn) ? column11.enum.schema || "public" : void 0;
  17335. const generated = column11.generated;
  17336. const identity = column11.generatedIdentity;
  17337. const increment = stringFromIdentityProperty((_j = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _j.increment) ?? "1";
  17338. const minValue = stringFromIdentityProperty((_k = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _k.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column11.columnType) : "1");
  17339. const maxValue = stringFromIdentityProperty((_l = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _l.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column11.getSQLType()));
  17340. const startWith = stringFromIdentityProperty((_m2 = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _m2.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
  17341. const cache3 = stringFromIdentityProperty((_n = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _n.cache) ?? "1";
  17342. const columnToSet = {
  17343. name: column11.name,
  17344. type: column11.getSQLType(),
  17345. typeSchema,
  17346. primaryKey,
  17347. notNull,
  17348. generated: generated ? {
  17349. as: (0, import_drizzle_orm4.is)(generated.as, import_drizzle_orm4.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
  17350. type: "stored"
  17351. } : void 0,
  17352. identity: identity ? {
  17353. type: identity.type,
  17354. name: identity.sequenceName ?? `${viewName}_${column11.name}_seq`,
  17355. schema: schema6 ?? "public",
  17356. increment,
  17357. startWith,
  17358. minValue,
  17359. maxValue,
  17360. cache: cache3,
  17361. cycle: ((_o = identity == null ? void 0 : identity.sequenceOptions) == null ? void 0 : _o.cycle) ?? false
  17362. } : void 0
  17363. };
  17364. if (column11.isUnique) {
  17365. const existingUnique = uniqueConstraintObject[column11.uniqueName];
  17366. if (typeof existingUnique !== "undefined") {
  17367. console.log(
  17368. `
  17369. ${withStyle.errorWarning(
  17370. `We've found duplicated unique constraint names in ${source_default.underline.blue(viewName)} table.
  17371. The unique constraint ${source_default.underline.blue(column11.uniqueName)} on the ${source_default.underline.blue(
  17372. column11.name
  17373. )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
  17374. `
  17375. )}`
  17376. );
  17377. process.exit(1);
  17378. }
  17379. uniqueConstraintObject[column11.uniqueName] = {
  17380. name: column11.uniqueName,
  17381. nullsNotDistinct: column11.uniqueType === "not distinct",
  17382. columns: [columnToSet.name]
  17383. };
  17384. }
  17385. if (column11.default !== void 0) {
  17386. if ((0, import_drizzle_orm4.is)(column11.default, import_drizzle_orm4.SQL)) {
  17387. columnToSet.default = sqlToStr(column11.default, casing2);
  17388. } else {
  17389. if (typeof column11.default === "string") {
  17390. columnToSet.default = `'${column11.default}'`;
  17391. } else {
  17392. if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
  17393. columnToSet.default = `'${JSON.stringify(column11.default)}'::${sqlTypeLowered}`;
  17394. } else if (column11.default instanceof Date) {
  17395. if (sqlTypeLowered === "date") {
  17396. columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`;
  17397. } else if (sqlTypeLowered === "timestamp") {
  17398. columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`;
  17399. } else {
  17400. columnToSet.default = `'${column11.default.toISOString()}'`;
  17401. }
  17402. } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column11.default)) {
  17403. columnToSet.default = `'${buildArrayString(column11.default, sqlTypeLowered)}'`;
  17404. } else {
  17405. columnToSet.default = column11.default;
  17406. }
  17407. }
  17408. }
  17409. }
  17410. columnsObject[column11.name] = columnToSet;
  17411. }
  17412. }
  17413. resultViews[viewKey] = {
  17414. columns: columnsObject,
  17415. definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql,
  17416. name: viewName,
  17417. schema: viewSchema,
  17418. isExisting,
  17419. with: withOption,
  17420. withNoData,
  17421. materialized,
  17422. tablespace,
  17423. using
  17424. };
  17425. }
  17426. const enumsToReturn = enums.reduce((map2, obj) => {
  17427. const enumSchema4 = obj.schema || "public";
  17428. const key = `${enumSchema4}.${obj.enumName}`;
  17429. map2[key] = {
  17430. name: obj.enumName,
  17431. schema: enumSchema4,
  17432. values: obj.enumValues
  17433. };
  17434. return map2;
  17435. }, {});
  17436. const schemasObject = Object.fromEntries(
  17437. schemas.filter((it) => {
  17438. if (schemaFilter) {
  17439. return schemaFilter.includes(it.schemaName) && it.schemaName !== "public";
  17440. } else {
  17441. return it.schemaName !== "public";
  17442. }
  17443. }).map((it) => [it.schemaName, it.schemaName])
  17444. );
  17445. return {
  17446. version: "7",
  17447. dialect: "postgresql",
  17448. tables: result,
  17449. enums: enumsToReturn,
  17450. schemas: schemasObject,
  17451. sequences: sequencesToReturn,
  17452. roles: rolesToReturn,
  17453. policies: policiesToReturn,
  17454. views: resultViews,
  17455. _meta: {
  17456. schemas: {},
  17457. tables: {},
  17458. columns: {}
  17459. }
  17460. };
  17461. };
  17462. trimChar = (str, char) => {
  17463. let start = 0;
  17464. let end = str.length;
  17465. while (start < end && str[start] === char) ++start;
  17466. while (end > start && str[end - 1] === char) --end;
  17467. return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
  17468. };
  17469. fromDatabase2 = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback, tsSchema) => {
  17470. const result = {};
  17471. const views = {};
  17472. const policies = {};
  17473. const internals = { tables: {} };
  17474. const where = schemaFilters.map((t4) => `n.nspname = '${t4}'`).join(" or ");
  17475. const allTables = await db.query(
  17476. `SELECT
  17477. n.nspname AS table_schema,
  17478. c.relname AS table_name,
  17479. CASE
  17480. WHEN c.relkind = 'r' THEN 'table'
  17481. WHEN c.relkind = 'v' THEN 'view'
  17482. WHEN c.relkind = 'm' THEN 'materialized_view'
  17483. END AS type,
  17484. c.relrowsecurity AS rls_enabled
  17485. FROM
  17486. pg_catalog.pg_class c
  17487. JOIN
  17488. pg_catalog.pg_namespace n ON n.oid = c.relnamespace
  17489. WHERE
  17490. c.relkind IN ('r', 'v', 'm')
  17491. ${where === "" ? "" : ` AND ${where}`};`
  17492. );
  17493. const schemas = new Set(allTables.map((it) => it.table_schema));
  17494. schemas.delete("public");
  17495. const allSchemas = await db.query(`select s.nspname as table_schema
  17496. from pg_catalog.pg_namespace s
  17497. join pg_catalog.pg_user u on u.usesysid = s.nspowner
  17498. where nspname not in ('information_schema', 'pg_catalog', 'public')
  17499. and nspname not like 'pg_toast%'
  17500. and nspname not like 'pg_temp_%'
  17501. order by table_schema;`);
  17502. allSchemas.forEach((item) => {
  17503. if (schemaFilters.includes(item.table_schema)) {
  17504. schemas.add(item.table_schema);
  17505. }
  17506. });
  17507. let columnsCount = 0;
  17508. let indexesCount = 0;
  17509. let foreignKeysCount = 0;
  17510. let tableCount = 0;
  17511. let checksCount = 0;
  17512. let viewsCount = 0;
  17513. const sequencesToReturn = {};
  17514. const seqWhere = schemaFilters.map((t4) => `schemaname = '${t4}'`).join(" or ");
  17515. const allSequences = await db.query(
  17516. `select schemaname, sequencename, start_value, min_value, max_value, increment_by, cycle, cache_size from pg_sequences as seq${seqWhere === "" ? "" : ` WHERE ${seqWhere}`};`
  17517. );
  17518. for (const dbSeq of allSequences) {
  17519. const schemaName = dbSeq.schemaname;
  17520. const sequenceName = dbSeq.sequencename;
  17521. const startValue = stringFromDatabaseIdentityProperty(dbSeq.start_value);
  17522. const minValue = stringFromDatabaseIdentityProperty(dbSeq.min_value);
  17523. const maxValue = stringFromDatabaseIdentityProperty(dbSeq.max_value);
  17524. const incrementBy = stringFromDatabaseIdentityProperty(dbSeq.increment_by);
  17525. const cycle = dbSeq.cycle;
  17526. const cacheSize = stringFromDatabaseIdentityProperty(dbSeq.cache_size);
  17527. const key = `${schemaName}.${sequenceName}`;
  17528. sequencesToReturn[key] = {
  17529. name: sequenceName,
  17530. schema: schemaName,
  17531. startWith: startValue,
  17532. minValue,
  17533. maxValue,
  17534. increment: incrementBy,
  17535. cycle,
  17536. cache: cacheSize
  17537. };
  17538. }
  17539. const whereEnums = schemaFilters.map((t4) => `n.nspname = '${t4}'`).join(" or ");
  17540. const allEnums = await db.query(
  17541. `select n.nspname as enum_schema,
  17542. t.typname as enum_name,
  17543. e.enumlabel as enum_value,
  17544. e.enumsortorder as sort_order
  17545. from pg_type t
  17546. join pg_enum e on t.oid = e.enumtypid
  17547. join pg_catalog.pg_namespace n ON n.oid = t.typnamespace
  17548. ${whereEnums === "" ? "" : ` WHERE ${whereEnums}`}
  17549. order by enum_schema, enum_name, sort_order;`
  17550. );
  17551. const enumsToReturn = {};
  17552. for (const dbEnum of allEnums) {
  17553. const enumName = dbEnum.enum_name;
  17554. const enumValue = dbEnum.enum_value;
  17555. const enumSchema4 = dbEnum.enum_schema || "public";
  17556. const key = `${enumSchema4}.${enumName}`;
  17557. if (enumsToReturn[key] !== void 0 && enumsToReturn[key] !== null) {
  17558. enumsToReturn[key].values.push(enumValue);
  17559. } else {
  17560. enumsToReturn[key] = {
  17561. name: enumName,
  17562. values: [enumValue],
  17563. schema: enumSchema4
  17564. };
  17565. }
  17566. }
  17567. if (progressCallback) {
  17568. progressCallback("enums", Object.keys(enumsToReturn).length, "done");
  17569. }
  17570. const allRoles = await db.query(
  17571. `SELECT rolname, rolinherit, rolcreatedb, rolcreaterole FROM pg_roles;`
  17572. );
  17573. const rolesToReturn = {};
  17574. const preparedRoles = prepareRoles(entities);
  17575. if (preparedRoles.useRoles || !(preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)) {
  17576. for (const dbRole of allRoles) {
  17577. if (preparedRoles.useRoles) {
  17578. rolesToReturn[dbRole.rolname] = {
  17579. createDb: dbRole.rolcreatedb,
  17580. createRole: dbRole.rolcreatedb,
  17581. inherit: dbRole.rolinherit,
  17582. name: dbRole.rolname
  17583. };
  17584. } else {
  17585. if (preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0) continue;
  17586. if (preparedRoles.includeRoles.includes(dbRole.rolname) && preparedRoles.excludeRoles.includes(dbRole.rolname)) continue;
  17587. if (preparedRoles.excludeRoles.includes(dbRole.rolname)) continue;
  17588. if (!preparedRoles.includeRoles.includes(dbRole.rolname)) continue;
  17589. rolesToReturn[dbRole.rolname] = {
  17590. createDb: dbRole.rolcreatedb,
  17591. createRole: dbRole.rolcreaterole,
  17592. inherit: dbRole.rolinherit,
  17593. name: dbRole.rolname
  17594. };
  17595. }
  17596. }
  17597. }
  17598. const schemasForLinkedPoliciesInSchema = Object.values((tsSchema == null ? void 0 : tsSchema.policies) ?? {}).map((it) => it.schema);
  17599. const wherePolicies = [...schemaFilters, ...schemasForLinkedPoliciesInSchema].map((t4) => `schemaname = '${t4}'`).join(" or ");
  17600. const policiesByTable = {};
  17601. const allPolicies = await db.query(`SELECT schemaname, tablename, policyname as name, permissive as "as", roles as to, cmd as for, qual as using, with_check as "withCheck" FROM pg_policies${wherePolicies === "" ? "" : ` WHERE ${wherePolicies}`};`);
  17602. for (const dbPolicy of allPolicies) {
  17603. const { tablename, schemaname, to, withCheck, using, ...rest } = dbPolicy;
  17604. const tableForPolicy = policiesByTable[`${schemaname}.${tablename}`];
  17605. const parsedTo = typeof to === "string" ? to.slice(1, -1).split(",") : to;
  17606. const parsedWithCheck = withCheck === null ? void 0 : withCheck;
  17607. const parsedUsing = using === null ? void 0 : using;
  17608. if (tableForPolicy) {
  17609. tableForPolicy[dbPolicy.name] = { ...rest, to: parsedTo };
  17610. } else {
  17611. policiesByTable[`${schemaname}.${tablename}`] = {
  17612. [dbPolicy.name]: { ...rest, to: parsedTo, withCheck: parsedWithCheck, using: parsedUsing }
  17613. };
  17614. }
  17615. if (tsSchema == null ? void 0 : tsSchema.policies[dbPolicy.name]) {
  17616. policies[dbPolicy.name] = {
  17617. ...rest,
  17618. to: parsedTo,
  17619. withCheck: parsedWithCheck,
  17620. using: parsedUsing,
  17621. on: tsSchema == null ? void 0 : tsSchema.policies[dbPolicy.name].on
  17622. };
  17623. }
  17624. }
  17625. if (progressCallback) {
  17626. progressCallback(
  17627. "policies",
  17628. Object.values(policiesByTable).reduce((total, innerRecord) => {
  17629. return total + Object.keys(innerRecord).length;
  17630. }, 0),
  17631. "done"
  17632. );
  17633. }
  17634. const sequencesInColumns = [];
  17635. const all = allTables.filter((it) => it.type === "table").map((row) => {
  17636. return new Promise(async (res, rej) => {
  17637. var _a2, _b, _c, _d, _e, _f;
  17638. const tableName = row.table_name;
  17639. if (!tablesFilter(tableName)) return res("");
  17640. tableCount += 1;
  17641. const tableSchema = row.table_schema;
  17642. try {
  17643. const columnToReturn = {};
  17644. const indexToReturn = {};
  17645. const foreignKeysToReturn = {};
  17646. const primaryKeys = {};
  17647. const uniqueConstrains = {};
  17648. const checkConstraints = {};
  17649. const tableResponse = await getColumnsInfoQuery({ schema: tableSchema, table: tableName, db });
  17650. const tableConstraints = await db.query(
  17651. `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
  17652. FROM information_schema.table_constraints tc
  17653. JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
  17654. JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
  17655. AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
  17656. WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
  17657. );
  17658. const tableChecks = await db.query(`SELECT
  17659. tc.constraint_name,
  17660. tc.constraint_type,
  17661. pg_get_constraintdef(con.oid) AS constraint_definition
  17662. FROM
  17663. information_schema.table_constraints AS tc
  17664. JOIN pg_constraint AS con
  17665. ON tc.constraint_name = con.conname
  17666. AND con.conrelid = (
  17667. SELECT oid
  17668. FROM pg_class
  17669. WHERE relname = tc.table_name
  17670. AND relnamespace = (
  17671. SELECT oid
  17672. FROM pg_namespace
  17673. WHERE nspname = tc.constraint_schema
  17674. )
  17675. )
  17676. WHERE
  17677. tc.table_name = '${tableName}'
  17678. AND tc.constraint_schema = '${tableSchema}'
  17679. AND tc.constraint_type = 'CHECK'
  17680. AND con.contype = 'c';`);
  17681. columnsCount += tableResponse.length;
  17682. if (progressCallback) {
  17683. progressCallback("columns", columnsCount, "fetching");
  17684. }
  17685. const tableForeignKeys = await db.query(
  17686. `SELECT
  17687. con.contype AS constraint_type,
  17688. nsp.nspname AS constraint_schema,
  17689. con.conname AS constraint_name,
  17690. rel.relname AS table_name,
  17691. att.attname AS column_name,
  17692. fnsp.nspname AS foreign_table_schema,
  17693. frel.relname AS foreign_table_name,
  17694. fatt.attname AS foreign_column_name,
  17695. CASE con.confupdtype
  17696. WHEN 'a' THEN 'NO ACTION'
  17697. WHEN 'r' THEN 'RESTRICT'
  17698. WHEN 'n' THEN 'SET NULL'
  17699. WHEN 'c' THEN 'CASCADE'
  17700. WHEN 'd' THEN 'SET DEFAULT'
  17701. END AS update_rule,
  17702. CASE con.confdeltype
  17703. WHEN 'a' THEN 'NO ACTION'
  17704. WHEN 'r' THEN 'RESTRICT'
  17705. WHEN 'n' THEN 'SET NULL'
  17706. WHEN 'c' THEN 'CASCADE'
  17707. WHEN 'd' THEN 'SET DEFAULT'
  17708. END AS delete_rule
  17709. FROM
  17710. pg_catalog.pg_constraint con
  17711. JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
  17712. JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
  17713. LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
  17714. AND att.attrelid = con.conrelid
  17715. LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
  17716. LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
  17717. LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
  17718. AND fatt.attrelid = con.confrelid
  17719. WHERE
  17720. nsp.nspname = '${tableSchema}'
  17721. AND rel.relname = '${tableName}'
  17722. AND con.contype IN ('f');`
  17723. );
  17724. foreignKeysCount += tableForeignKeys.length;
  17725. if (progressCallback) {
  17726. progressCallback("fks", foreignKeysCount, "fetching");
  17727. }
  17728. for (const fk5 of tableForeignKeys) {
  17729. const columnFrom = fk5.column_name;
  17730. const tableTo = fk5.foreign_table_name;
  17731. const columnTo = fk5.foreign_column_name;
  17732. const schemaTo = fk5.foreign_table_schema;
  17733. const foreignKeyName = fk5.constraint_name;
  17734. const onUpdate = (_a2 = fk5.update_rule) == null ? void 0 : _a2.toLowerCase();
  17735. const onDelete = (_b = fk5.delete_rule) == null ? void 0 : _b.toLowerCase();
  17736. if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
  17737. foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
  17738. foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
  17739. } else {
  17740. foreignKeysToReturn[foreignKeyName] = {
  17741. name: foreignKeyName,
  17742. tableFrom: tableName,
  17743. tableTo,
  17744. schemaTo,
  17745. columnsFrom: [columnFrom],
  17746. columnsTo: [columnTo],
  17747. onDelete,
  17748. onUpdate
  17749. };
  17750. }
  17751. foreignKeysToReturn[foreignKeyName].columnsFrom = [
  17752. ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
  17753. ];
  17754. foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
  17755. }
  17756. const uniqueConstrainsRows = tableConstraints.filter((mapRow) => mapRow.constraint_type === "UNIQUE");
  17757. for (const unqs of uniqueConstrainsRows) {
  17758. const columnName = unqs.column_name;
  17759. const constraintName = unqs.constraint_name;
  17760. if (typeof uniqueConstrains[constraintName] !== "undefined") {
  17761. uniqueConstrains[constraintName].columns.push(columnName);
  17762. } else {
  17763. uniqueConstrains[constraintName] = {
  17764. columns: [columnName],
  17765. nullsNotDistinct: false,
  17766. name: constraintName
  17767. };
  17768. }
  17769. }
  17770. checksCount += tableChecks.length;
  17771. if (progressCallback) {
  17772. progressCallback("checks", checksCount, "fetching");
  17773. }
  17774. for (const checks of tableChecks) {
  17775. let checkValue = checks.constraint_definition;
  17776. const constraintName = checks.constraint_name;
  17777. checkValue = checkValue.replace(/^CHECK\s*\(\(/, "").replace(/\)\)\s*$/, "");
  17778. checkConstraints[constraintName] = {
  17779. name: constraintName,
  17780. value: checkValue
  17781. };
  17782. }
  17783. for (const columnResponse of tableResponse) {
  17784. const columnName = columnResponse.column_name;
  17785. const columnAdditionalDT = columnResponse.additional_dt;
  17786. const columnDimensions = columnResponse.array_dimensions;
  17787. const enumType2 = columnResponse.enum_name;
  17788. let columnType = columnResponse.data_type;
  17789. const typeSchema = columnResponse.type_schema;
  17790. const defaultValueRes = columnResponse.column_default;
  17791. const isGenerated = columnResponse.is_generated === "ALWAYS";
  17792. const generationExpression = columnResponse.generation_expression;
  17793. const isIdentity = columnResponse.is_identity === "YES";
  17794. const identityGeneration = columnResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
  17795. const identityStart = columnResponse.identity_start;
  17796. const identityIncrement = columnResponse.identity_increment;
  17797. const identityMaximum = columnResponse.identity_maximum;
  17798. const identityMinimum = columnResponse.identity_minimum;
  17799. const identityCycle = columnResponse.identity_cycle === "YES";
  17800. const identityName = columnResponse.seq_name;
  17801. const primaryKey = tableConstraints.filter(
  17802. (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
  17803. );
  17804. const cprimaryKey = tableConstraints.filter((mapRow) => mapRow.constraint_type === "PRIMARY KEY");
  17805. if (cprimaryKey.length > 1) {
  17806. const tableCompositePkName = await db.query(
  17807. `SELECT conname AS primary_key
  17808. FROM pg_constraint join pg_class on (pg_class.oid = conrelid)
  17809. WHERE contype = 'p'
  17810. AND connamespace = $1::regnamespace
  17811. AND pg_class.relname = $2;`,
  17812. [tableSchema, tableName]
  17813. );
  17814. primaryKeys[tableCompositePkName[0].primary_key] = {
  17815. name: tableCompositePkName[0].primary_key,
  17816. columns: cprimaryKey.map((c3) => c3.column_name)
  17817. };
  17818. }
  17819. let columnTypeMapped = columnType;
  17820. if (columnAdditionalDT === "ARRAY") {
  17821. if (typeof internals.tables[tableName] === "undefined") {
  17822. internals.tables[tableName] = {
  17823. columns: {
  17824. [columnName]: {
  17825. isArray: true,
  17826. dimensions: columnDimensions,
  17827. rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
  17828. }
  17829. }
  17830. };
  17831. } else {
  17832. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  17833. internals.tables[tableName].columns[columnName] = {
  17834. isArray: true,
  17835. dimensions: columnDimensions,
  17836. rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
  17837. };
  17838. }
  17839. }
  17840. }
  17841. const defaultValue = defaultForColumn(columnResponse, internals, tableName);
  17842. if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
  17843. if (typeof internals.tables[tableName] === "undefined") {
  17844. internals.tables[tableName] = {
  17845. columns: {
  17846. [columnName]: {
  17847. isDefaultAnExpression: true
  17848. }
  17849. }
  17850. };
  17851. } else {
  17852. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  17853. internals.tables[tableName].columns[columnName] = {
  17854. isDefaultAnExpression: true
  17855. };
  17856. } else {
  17857. internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
  17858. }
  17859. }
  17860. }
  17861. const isSerial = columnType === "serial";
  17862. if (columnTypeMapped.startsWith("numeric(")) {
  17863. columnTypeMapped = columnTypeMapped.replace(",", ", ");
  17864. }
  17865. if (columnAdditionalDT === "ARRAY") {
  17866. for (let i4 = 1; i4 < Number(columnDimensions); i4++) {
  17867. columnTypeMapped += "[]";
  17868. }
  17869. }
  17870. columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
  17871. columnTypeMapped = trimChar(columnTypeMapped, '"');
  17872. columnToReturn[columnName] = {
  17873. name: columnName,
  17874. type: (
  17875. // filter vectors, but in future we should filter any extension that was installed by user
  17876. columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped
  17877. ),
  17878. typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
  17879. primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
  17880. // default: isSerial ? undefined : defaultValue,
  17881. notNull: columnResponse.is_nullable === "NO",
  17882. generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
  17883. identity: isIdentity ? {
  17884. type: identityGeneration,
  17885. name: identityName,
  17886. increment: stringFromDatabaseIdentityProperty(identityIncrement),
  17887. minValue: stringFromDatabaseIdentityProperty(identityMinimum),
  17888. maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
  17889. startWith: stringFromDatabaseIdentityProperty(identityStart),
  17890. cache: ((_c = sequencesToReturn[identityName]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[identityName]) == null ? void 0 : _d.cache : ((_e = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _e.cache) ? (_f = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _f.cache : void 0,
  17891. cycle: identityCycle,
  17892. schema: tableSchema
  17893. } : void 0
  17894. };
  17895. if (identityName && typeof identityName === "string") {
  17896. delete sequencesToReturn[`${tableSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
  17897. delete sequencesToReturn[identityName];
  17898. }
  17899. if (!isSerial && typeof defaultValue !== "undefined") {
  17900. columnToReturn[columnName].default = defaultValue;
  17901. }
  17902. }
  17903. const dbIndexes = await db.query(
  17904. `SELECT DISTINCT ON (t.relname, ic.relname, k.i) t.relname as table_name, ic.relname AS indexname,
  17905. k.i AS index_order,
  17906. i.indisunique as is_unique,
  17907. am.amname as method,
  17908. ic.reloptions as with,
  17909. coalesce(a.attname, pg_get_indexdef(i.indexrelid, k.i, false)) AS column_name,
  17910. CASE
  17911. WHEN pg_get_expr(i.indexprs, i.indrelid) IS NOT NULL THEN 1
  17912. ELSE 0
  17913. END AS is_expression,
  17914. i.indoption[k.i-1] & 1 = 1 AS descending,
  17915. i.indoption[k.i-1] & 2 = 2 AS nulls_first,
  17916. pg_get_expr(
  17917. i.indpred,
  17918. i.indrelid
  17919. ) as where,
  17920. opc.opcname
  17921. FROM pg_class t
  17922. LEFT JOIN pg_index i ON t.oid = i.indrelid
  17923. LEFT JOIN pg_class ic ON ic.oid = i.indexrelid
  17924. CROSS JOIN LATERAL (SELECT unnest(i.indkey), generate_subscripts(i.indkey, 1) + 1) AS k(attnum, i)
  17925. LEFT JOIN pg_attribute AS a
  17926. ON i.indrelid = a.attrelid AND k.attnum = a.attnum
  17927. JOIN pg_namespace c on c.oid = t.relnamespace
  17928. LEFT JOIN pg_am AS am ON ic.relam = am.oid
  17929. JOIN pg_opclass opc ON opc.oid = ANY(i.indclass)
  17930. WHERE
  17931. c.nspname = '${tableSchema}' AND
  17932. t.relname = '${tableName}';`
  17933. );
  17934. const dbIndexFromConstraint = await db.query(
  17935. `SELECT
  17936. idx.indexrelname AS index_name,
  17937. idx.relname AS table_name,
  17938. schemaname,
  17939. CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
  17940. FROM
  17941. pg_stat_user_indexes idx
  17942. LEFT JOIN
  17943. pg_constraint con ON con.conindid = idx.indexrelid
  17944. WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
  17945. group by index_name, table_name,schemaname, generated_by_constraint;`
  17946. );
  17947. const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
  17948. (it) => it.index_name
  17949. );
  17950. for (const dbIndex of dbIndexes) {
  17951. const indexName6 = dbIndex.indexname;
  17952. const indexColumnName = dbIndex.column_name;
  17953. const indexIsUnique = dbIndex.is_unique;
  17954. const indexMethod = dbIndex.method;
  17955. const indexWith = dbIndex.with;
  17956. const indexWhere = dbIndex.where;
  17957. const opclass = dbIndex.opcname;
  17958. const isExpression = dbIndex.is_expression === 1;
  17959. const desc = dbIndex.descending;
  17960. const nullsFirst = dbIndex.nulls_first;
  17961. const mappedWith = {};
  17962. if (indexWith !== null) {
  17963. indexWith.forEach((it) => {
  17964. const splitted = it.split("=");
  17965. mappedWith[splitted[0]] = splitted[1];
  17966. });
  17967. }
  17968. if (idxsInConsteraint.includes(indexName6)) continue;
  17969. if (typeof indexToReturn[indexName6] !== "undefined") {
  17970. indexToReturn[indexName6].columns.push({
  17971. expression: indexColumnName,
  17972. asc: !desc,
  17973. nulls: nullsFirst ? "first" : "last",
  17974. opclass,
  17975. isExpression
  17976. });
  17977. } else {
  17978. indexToReturn[indexName6] = {
  17979. name: indexName6,
  17980. columns: [
  17981. {
  17982. expression: indexColumnName,
  17983. asc: !desc,
  17984. nulls: nullsFirst ? "first" : "last",
  17985. opclass,
  17986. isExpression
  17987. }
  17988. ],
  17989. isUnique: indexIsUnique,
  17990. // should not be a part of diff detects
  17991. concurrently: false,
  17992. method: indexMethod,
  17993. where: indexWhere === null ? void 0 : indexWhere,
  17994. with: mappedWith
  17995. };
  17996. }
  17997. }
  17998. indexesCount += Object.keys(indexToReturn).length;
  17999. if (progressCallback) {
  18000. progressCallback("indexes", indexesCount, "fetching");
  18001. }
  18002. result[`${tableSchema}.${tableName}`] = {
  18003. name: tableName,
  18004. schema: tableSchema !== "public" ? tableSchema : "",
  18005. columns: columnToReturn,
  18006. indexes: indexToReturn,
  18007. foreignKeys: foreignKeysToReturn,
  18008. compositePrimaryKeys: primaryKeys,
  18009. uniqueConstraints: uniqueConstrains,
  18010. checkConstraints,
  18011. policies: policiesByTable[`${tableSchema}.${tableName}`] ?? {},
  18012. isRLSEnabled: row.rls_enabled
  18013. };
  18014. } catch (e4) {
  18015. rej(e4);
  18016. return;
  18017. }
  18018. res("");
  18019. });
  18020. });
  18021. if (progressCallback) {
  18022. progressCallback("tables", tableCount, "done");
  18023. }
  18024. for await (const _3 of all) {
  18025. }
  18026. const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
  18027. return new Promise(async (res, rej) => {
  18028. var _a2, _b, _c, _d;
  18029. const viewName = row.table_name;
  18030. if (!tablesFilter(viewName)) return res("");
  18031. tableCount += 1;
  18032. const viewSchema = row.table_schema;
  18033. try {
  18034. const columnToReturn = {};
  18035. const viewResponses = await getColumnsInfoQuery({ schema: viewSchema, table: viewName, db });
  18036. for (const viewResponse of viewResponses) {
  18037. const columnName = viewResponse.column_name;
  18038. const columnAdditionalDT = viewResponse.additional_dt;
  18039. const columnDimensions = viewResponse.array_dimensions;
  18040. const enumType2 = viewResponse.enum_name;
  18041. let columnType = viewResponse.data_type;
  18042. const typeSchema = viewResponse.type_schema;
  18043. const isGenerated = viewResponse.is_generated === "ALWAYS";
  18044. const generationExpression = viewResponse.generation_expression;
  18045. const isIdentity = viewResponse.is_identity === "YES";
  18046. const identityGeneration = viewResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
  18047. const identityStart = viewResponse.identity_start;
  18048. const identityIncrement = viewResponse.identity_increment;
  18049. const identityMaximum = viewResponse.identity_maximum;
  18050. const identityMinimum = viewResponse.identity_minimum;
  18051. const identityCycle = viewResponse.identity_cycle === "YES";
  18052. const identityName = viewResponse.seq_name;
  18053. const defaultValueRes = viewResponse.column_default;
  18054. const primaryKey = viewResponse.constraint_type === "PRIMARY KEY";
  18055. let columnTypeMapped = columnType;
  18056. if (columnAdditionalDT === "ARRAY") {
  18057. if (typeof internals.tables[viewName] === "undefined") {
  18058. internals.tables[viewName] = {
  18059. columns: {
  18060. [columnName]: {
  18061. isArray: true,
  18062. dimensions: columnDimensions,
  18063. rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
  18064. }
  18065. }
  18066. };
  18067. } else {
  18068. if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
  18069. internals.tables[viewName].columns[columnName] = {
  18070. isArray: true,
  18071. dimensions: columnDimensions,
  18072. rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
  18073. };
  18074. }
  18075. }
  18076. }
  18077. const defaultValue = defaultForColumn(viewResponse, internals, viewName);
  18078. if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
  18079. if (typeof internals.tables[viewName] === "undefined") {
  18080. internals.tables[viewName] = {
  18081. columns: {
  18082. [columnName]: {
  18083. isDefaultAnExpression: true
  18084. }
  18085. }
  18086. };
  18087. } else {
  18088. if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
  18089. internals.tables[viewName].columns[columnName] = {
  18090. isDefaultAnExpression: true
  18091. };
  18092. } else {
  18093. internals.tables[viewName].columns[columnName].isDefaultAnExpression = true;
  18094. }
  18095. }
  18096. }
  18097. const isSerial = columnType === "serial";
  18098. if (columnTypeMapped.startsWith("numeric(")) {
  18099. columnTypeMapped = columnTypeMapped.replace(",", ", ");
  18100. }
  18101. if (columnAdditionalDT === "ARRAY") {
  18102. for (let i4 = 1; i4 < Number(columnDimensions); i4++) {
  18103. columnTypeMapped += "[]";
  18104. }
  18105. }
  18106. columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
  18107. columnTypeMapped = trimChar(columnTypeMapped, '"');
  18108. columnToReturn[columnName] = {
  18109. name: columnName,
  18110. type: (
  18111. // filter vectors, but in future we should filter any extension that was installed by user
  18112. columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped
  18113. ),
  18114. typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
  18115. primaryKey,
  18116. notNull: viewResponse.is_nullable === "NO",
  18117. generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
  18118. identity: isIdentity ? {
  18119. type: identityGeneration,
  18120. name: identityName,
  18121. increment: stringFromDatabaseIdentityProperty(identityIncrement),
  18122. minValue: stringFromDatabaseIdentityProperty(identityMinimum),
  18123. maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
  18124. startWith: stringFromDatabaseIdentityProperty(identityStart),
  18125. cache: ((_a2 = sequencesToReturn[identityName]) == null ? void 0 : _a2.cache) ? (_b = sequencesToReturn[identityName]) == null ? void 0 : _b.cache : ((_c = sequencesToReturn[`${viewSchema}.${identityName}`]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[`${viewSchema}.${identityName}`]) == null ? void 0 : _d.cache : void 0,
  18126. cycle: identityCycle,
  18127. schema: viewSchema
  18128. } : void 0
  18129. };
  18130. if (identityName) {
  18131. delete sequencesToReturn[`${viewSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
  18132. delete sequencesToReturn[identityName];
  18133. }
  18134. if (!isSerial && typeof defaultValue !== "undefined") {
  18135. columnToReturn[columnName].default = defaultValue;
  18136. }
  18137. }
  18138. const [viewInfo] = await db.query(`
  18139. SELECT
  18140. c.relname AS view_name,
  18141. n.nspname AS schema_name,
  18142. pg_get_viewdef(c.oid, true) AS definition,
  18143. ts.spcname AS tablespace_name,
  18144. c.reloptions AS options,
  18145. pg_tablespace_location(ts.oid) AS location
  18146. FROM
  18147. pg_class c
  18148. JOIN
  18149. pg_namespace n ON c.relnamespace = n.oid
  18150. LEFT JOIN
  18151. pg_tablespace ts ON c.reltablespace = ts.oid
  18152. WHERE
  18153. (c.relkind = 'm' OR c.relkind = 'v')
  18154. AND n.nspname = '${viewSchema}'
  18155. AND c.relname = '${viewName}';`);
  18156. const resultWith = {};
  18157. if (viewInfo.options) {
  18158. viewInfo.options.forEach((pair) => {
  18159. const splitted = pair.split("=");
  18160. const key = splitted[0];
  18161. const value = splitted[1];
  18162. if (value === "true") {
  18163. resultWith[key] = true;
  18164. } else if (value === "false") {
  18165. resultWith[key] = false;
  18166. } else if (!isNaN(Number(value))) {
  18167. resultWith[key] = Number(value);
  18168. } else {
  18169. resultWith[key] = value;
  18170. }
  18171. });
  18172. }
  18173. const definition = viewInfo.definition.replace(/\s+/g, " ").replace(";", "").trim();
  18174. const withOption = Object.values(resultWith).length ? Object.fromEntries(Object.entries(resultWith).map(([key, value]) => [key.camelCase(), value])) : void 0;
  18175. const materialized = row.type === "materialized_view";
  18176. views[`${viewSchema}.${viewName}`] = {
  18177. name: viewName,
  18178. schema: viewSchema,
  18179. columns: columnToReturn,
  18180. isExisting: false,
  18181. definition,
  18182. materialized,
  18183. with: withOption,
  18184. tablespace: viewInfo.tablespace_name ?? void 0
  18185. };
  18186. } catch (e4) {
  18187. rej(e4);
  18188. return;
  18189. }
  18190. res("");
  18191. });
  18192. });
  18193. viewsCount = allViews.length;
  18194. for await (const _3 of allViews) {
  18195. }
  18196. if (progressCallback) {
  18197. progressCallback("columns", columnsCount, "done");
  18198. progressCallback("indexes", indexesCount, "done");
  18199. progressCallback("fks", foreignKeysCount, "done");
  18200. progressCallback("checks", checksCount, "done");
  18201. progressCallback("views", viewsCount, "done");
  18202. }
  18203. const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
  18204. return {
  18205. version: "7",
  18206. dialect: "postgresql",
  18207. tables: result,
  18208. enums: enumsToReturn,
  18209. schemas: schemasObject,
  18210. sequences: sequencesToReturn,
  18211. roles: rolesToReturn,
  18212. policies,
  18213. views,
  18214. _meta: {
  18215. schemas: {},
  18216. tables: {},
  18217. columns: {}
  18218. },
  18219. internal: internals
  18220. };
  18221. };
  18222. defaultForColumn = (column11, internals, tableName) => {
  18223. var _a2, _b;
  18224. const columnName = column11.column_name;
  18225. const isArray = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[columnName]) == null ? void 0 : _b.isArray) ?? false;
  18226. if (column11.column_default === null || column11.column_default === void 0 || column11.data_type === "serial" || column11.data_type === "smallserial" || column11.data_type === "bigserial") {
  18227. return void 0;
  18228. }
  18229. if (column11.column_default.endsWith("[]")) {
  18230. column11.column_default = column11.column_default.slice(0, -2);
  18231. }
  18232. column11.column_default = column11.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
  18233. const columnDefaultAsString = column11.column_default.toString();
  18234. if (isArray) {
  18235. return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => {
  18236. if (["integer", "smallint", "bigint", "double precision", "real"].includes(column11.data_type.slice(0, -2))) {
  18237. return value;
  18238. } else if (column11.data_type.startsWith("timestamp")) {
  18239. return `${value}`;
  18240. } else if (column11.data_type.slice(0, -2) === "interval") {
  18241. return value.replaceAll('"', `"`);
  18242. } else if (column11.data_type.slice(0, -2) === "boolean") {
  18243. return value === "t" ? "true" : "false";
  18244. } else if (["json", "jsonb"].includes(column11.data_type.slice(0, -2))) {
  18245. return JSON.stringify(JSON.stringify(JSON.parse(JSON.parse(value)), null, 0));
  18246. } else {
  18247. return `"${value}"`;
  18248. }
  18249. }).join(",")}}'`;
  18250. }
  18251. if (["integer", "smallint", "bigint", "double precision", "real"].includes(column11.data_type)) {
  18252. if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString)) {
  18253. return Number(columnDefaultAsString);
  18254. } else {
  18255. if (typeof internals.tables[tableName] === "undefined") {
  18256. internals.tables[tableName] = {
  18257. columns: {
  18258. [columnName]: {
  18259. isDefaultAnExpression: true
  18260. }
  18261. }
  18262. };
  18263. } else {
  18264. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  18265. internals.tables[tableName].columns[columnName] = {
  18266. isDefaultAnExpression: true
  18267. };
  18268. } else {
  18269. internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
  18270. }
  18271. }
  18272. return columnDefaultAsString;
  18273. }
  18274. } else if (column11.data_type.includes("numeric")) {
  18275. return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
  18276. } else if (column11.data_type === "json" || column11.data_type === "jsonb") {
  18277. const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
  18278. return `'${jsonWithoutSpaces}'::${column11.data_type}`;
  18279. } else if (column11.data_type === "boolean") {
  18280. return column11.column_default === "true";
  18281. } else if (columnDefaultAsString === "NULL") {
  18282. return `NULL`;
  18283. } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) {
  18284. return columnDefaultAsString;
  18285. } else {
  18286. return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
  18287. }
  18288. };
  18289. getColumnsInfoQuery = ({ schema: schema6, table: table6, db }) => {
  18290. return db.query(
  18291. `SELECT
  18292. a.attrelid::regclass::text AS table_name, -- Table, view, or materialized view name
  18293. a.attname AS column_name, -- Column name
  18294. CASE
  18295. WHEN NOT a.attisdropped THEN
  18296. CASE
  18297. WHEN a.attnotnull THEN 'NO'
  18298. ELSE 'YES'
  18299. END
  18300. ELSE NULL
  18301. END AS is_nullable, -- NULL or NOT NULL constraint
  18302. a.attndims AS array_dimensions, -- Array dimensions
  18303. CASE
  18304. WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
  18305. AND EXISTS (
  18306. SELECT FROM pg_attrdef ad
  18307. WHERE ad.adrelid = a.attrelid
  18308. AND ad.adnum = a.attnum
  18309. AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval('''
  18310. || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
  18311. )
  18312. THEN CASE a.atttypid
  18313. WHEN 'int'::regtype THEN 'serial'
  18314. WHEN 'int8'::regtype THEN 'bigserial'
  18315. WHEN 'int2'::regtype THEN 'smallserial'
  18316. END
  18317. ELSE format_type(a.atttypid, a.atttypmod)
  18318. END AS data_type, -- Column data type
  18319. -- ns.nspname AS type_schema, -- Schema name
  18320. pg_get_serial_sequence('"${schema6}"."${table6}"', a.attname)::regclass AS seq_name, -- Serial sequence (if any)
  18321. c.column_default, -- Column default value
  18322. c.data_type AS additional_dt, -- Data type from information_schema
  18323. c.udt_name AS enum_name, -- Enum type (if applicable)
  18324. c.is_generated, -- Is it a generated column?
  18325. c.generation_expression, -- Generation expression (if generated)
  18326. c.is_identity, -- Is it an identity column?
  18327. c.identity_generation, -- Identity generation strategy (ALWAYS or BY DEFAULT)
  18328. c.identity_start, -- Start value of identity column
  18329. c.identity_increment, -- Increment for identity column
  18330. c.identity_maximum, -- Maximum value for identity column
  18331. c.identity_minimum, -- Minimum value for identity column
  18332. c.identity_cycle, -- Does the identity column cycle?
  18333. enum_ns.nspname AS type_schema -- Schema of the enum type
  18334. FROM
  18335. pg_attribute a
  18336. JOIN
  18337. pg_class cls ON cls.oid = a.attrelid -- Join pg_class to get table/view/materialized view info
  18338. JOIN
  18339. pg_namespace ns ON ns.oid = cls.relnamespace -- Join namespace to get schema info
  18340. LEFT JOIN
  18341. information_schema.columns c ON c.column_name = a.attname
  18342. AND c.table_schema = ns.nspname
  18343. AND c.table_name = cls.relname -- Match schema and table/view name
  18344. LEFT JOIN
  18345. pg_type enum_t ON enum_t.oid = a.atttypid -- Join to get the type info
  18346. LEFT JOIN
  18347. pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace -- Join to get the enum schema
  18348. WHERE
  18349. a.attnum > 0 -- Valid column numbers only
  18350. AND NOT a.attisdropped -- Skip dropped columns
  18351. AND cls.relkind IN ('r', 'v', 'm') -- Include regular tables ('r'), views ('v'), and materialized views ('m')
  18352. AND ns.nspname = '${schema6}' -- Filter by schema
  18353. AND cls.relname = '${table6}' -- Filter by table name
  18354. ORDER BY
  18355. a.attnum; -- Order by column number`
  18356. );
  18357. };
  18358. }
  18359. });
  18360. // src/serializer/sqliteImports.ts
  18361. var sqliteImports_exports = {};
  18362. __export(sqliteImports_exports, {
  18363. prepareFromExports: () => prepareFromExports3,
  18364. prepareFromSqliteImports: () => prepareFromSqliteImports
  18365. });
  18366. var import_drizzle_orm5, import_sqlite_core, prepareFromExports3, prepareFromSqliteImports;
  18367. var init_sqliteImports = __esm({
  18368. "src/serializer/sqliteImports.ts"() {
  18369. "use strict";
  18370. import_drizzle_orm5 = require("drizzle-orm");
  18371. import_sqlite_core = require("drizzle-orm/sqlite-core");
  18372. init_utils3();
  18373. prepareFromExports3 = (exports2) => {
  18374. const tables = [];
  18375. const views = [];
  18376. const i0values = Object.values(exports2);
  18377. i0values.forEach((t4) => {
  18378. if ((0, import_drizzle_orm5.is)(t4, import_sqlite_core.SQLiteTable)) {
  18379. tables.push(t4);
  18380. }
  18381. if ((0, import_drizzle_orm5.is)(t4, import_sqlite_core.SQLiteView)) {
  18382. views.push(t4);
  18383. }
  18384. });
  18385. return { tables, views };
  18386. };
  18387. prepareFromSqliteImports = async (imports) => {
  18388. const tables = [];
  18389. const views = [];
  18390. await safeRegister(async () => {
  18391. for (let i4 = 0; i4 < imports.length; i4++) {
  18392. const it = imports[i4];
  18393. const i0 = require(`${it}`);
  18394. const prepared = prepareFromExports3(i0);
  18395. tables.push(...prepared.tables);
  18396. views.push(...prepared.views);
  18397. }
  18398. });
  18399. return { tables: Array.from(new Set(tables)), views };
  18400. };
  18401. }
  18402. });
  18403. // src/serializer/sqliteSerializer.ts
  18404. var sqliteSerializer_exports = {};
  18405. __export(sqliteSerializer_exports, {
  18406. fromDatabase: () => fromDatabase3,
  18407. generateSqliteSnapshot: () => generateSqliteSnapshot
  18408. });
  18409. function mapSqlToSqliteType(sqlType) {
  18410. const lowered = sqlType.toLowerCase();
  18411. if ([
  18412. "int",
  18413. "integer",
  18414. "integer auto_increment",
  18415. "tinyint",
  18416. "smallint",
  18417. "mediumint",
  18418. "bigint",
  18419. "unsigned big int",
  18420. "int2",
  18421. "int8"
  18422. ].some((it) => lowered.startsWith(it))) {
  18423. return "integer";
  18424. } else if ([
  18425. "character",
  18426. "varchar",
  18427. "varying character",
  18428. "national varying character",
  18429. "nchar",
  18430. "native character",
  18431. "nvarchar",
  18432. "text",
  18433. "clob"
  18434. ].some((it) => lowered.startsWith(it))) {
  18435. const match2 = lowered.match(/\d+/);
  18436. if (match2) {
  18437. return `text(${match2[0]})`;
  18438. }
  18439. return "text";
  18440. } else if (lowered.startsWith("blob")) {
  18441. return "blob";
  18442. } else if (["real", "double", "double precision", "float"].some((it) => lowered.startsWith(it))) {
  18443. return "real";
  18444. } else {
  18445. return "numeric";
  18446. }
  18447. }
  18448. function extractGeneratedColumns(input) {
  18449. const columns = {};
  18450. const lines = input.split(/,\s*(?![^()]*\))/);
  18451. for (const line of lines) {
  18452. if (line.includes("GENERATED ALWAYS AS")) {
  18453. const parts = line.trim().split(/\s+/);
  18454. const columnName = parts[0].replace(/[`'"]/g, "");
  18455. const expression = line.substring(line.indexOf("("), line.indexOf(")") + 1).trim();
  18456. const typeIndex = parts.findIndex((part) => part.match(/(stored|virtual)/i));
  18457. let type = "virtual";
  18458. if (typeIndex !== -1) {
  18459. type = parts[typeIndex].replace(/[^a-z]/gi, "").toLowerCase();
  18460. }
  18461. columns[columnName] = {
  18462. columnName,
  18463. expression,
  18464. type
  18465. };
  18466. }
  18467. }
  18468. return columns;
  18469. }
  18470. function filterIgnoredTablesByField(fieldName) {
  18471. return `${fieldName} != '__drizzle_migrations'
  18472. AND ${fieldName} NOT LIKE '\\_cf\\_%' ESCAPE '\\'
  18473. AND ${fieldName} NOT LIKE '\\_litestream\\_%' ESCAPE '\\'
  18474. AND ${fieldName} NOT LIKE 'libsql\\_%' ESCAPE '\\'
  18475. AND ${fieldName} NOT LIKE 'sqlite\\_%' ESCAPE '\\'`;
  18476. }
  18477. var import_drizzle_orm6, import_sqlite_core2, generateSqliteSnapshot, fromDatabase3;
  18478. var init_sqliteSerializer = __esm({
  18479. "src/serializer/sqliteSerializer.ts"() {
  18480. "use strict";
  18481. init_source();
  18482. import_drizzle_orm6 = require("drizzle-orm");
  18483. import_sqlite_core2 = require("drizzle-orm/sqlite-core");
  18484. init_outputs();
  18485. init_utils2();
  18486. init_utils4();
  18487. generateSqliteSnapshot = (tables, views, casing2) => {
  18488. const dialect6 = new import_sqlite_core2.SQLiteSyncDialect({ casing: casing2 });
  18489. const result = {};
  18490. const resultViews = {};
  18491. const internal = { indexes: {} };
  18492. for (const table6 of tables) {
  18493. const columnsObject = {};
  18494. const indexesObject = {};
  18495. const foreignKeysObject = {};
  18496. const primaryKeysObject = {};
  18497. const uniqueConstraintObject = {};
  18498. const checkConstraintObject = {};
  18499. const checksInTable = {};
  18500. const {
  18501. name: tableName,
  18502. columns,
  18503. indexes,
  18504. checks,
  18505. foreignKeys: tableForeignKeys,
  18506. primaryKeys,
  18507. uniqueConstraints
  18508. } = (0, import_sqlite_core2.getTableConfig)(table6);
  18509. columns.forEach((column11) => {
  18510. const name = getColumnCasing(column11, casing2);
  18511. const notNull = column11.notNull;
  18512. const primaryKey = column11.primary;
  18513. const generated = column11.generated;
  18514. const columnToSet = {
  18515. name,
  18516. type: column11.getSQLType(),
  18517. primaryKey,
  18518. notNull,
  18519. autoincrement: (0, import_drizzle_orm6.is)(column11, import_sqlite_core2.SQLiteBaseInteger) ? column11.autoIncrement : false,
  18520. generated: generated ? {
  18521. as: (0, import_drizzle_orm6.is)(generated.as, import_drizzle_orm6.SQL) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
  18522. type: generated.mode ?? "virtual"
  18523. } : void 0
  18524. };
  18525. if (column11.default !== void 0) {
  18526. if ((0, import_drizzle_orm6.is)(column11.default, import_drizzle_orm6.SQL)) {
  18527. columnToSet.default = sqlToStr(column11.default, casing2);
  18528. } else {
  18529. columnToSet.default = typeof column11.default === "string" ? `'${escapeSingleQuotes(column11.default)}'` : typeof column11.default === "object" || Array.isArray(column11.default) ? `'${JSON.stringify(column11.default)}'` : column11.default;
  18530. }
  18531. }
  18532. columnsObject[name] = columnToSet;
  18533. if (column11.isUnique) {
  18534. const existingUnique = indexesObject[column11.uniqueName];
  18535. if (typeof existingUnique !== "undefined") {
  18536. console.log(
  18537. `
  18538. ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
  18539. tableName
  18540. )} table.
  18541. The unique constraint ${source_default.underline.blue(
  18542. column11.uniqueName
  18543. )} on the ${source_default.underline.blue(
  18544. name
  18545. )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  18546. existingUnique.columns.join(",")
  18547. )} columns
  18548. `)}`
  18549. );
  18550. process.exit(1);
  18551. }
  18552. indexesObject[column11.uniqueName] = {
  18553. name: column11.uniqueName,
  18554. columns: [columnToSet.name],
  18555. isUnique: true
  18556. };
  18557. }
  18558. });
  18559. const foreignKeys = tableForeignKeys.map((fk5) => {
  18560. const tableFrom = tableName;
  18561. const onDelete = fk5.onDelete ?? "no action";
  18562. const onUpdate = fk5.onUpdate ?? "no action";
  18563. const reference = fk5.reference();
  18564. const referenceFT = reference.foreignTable;
  18565. const tableTo = (0, import_drizzle_orm6.getTableName)(referenceFT);
  18566. const originalColumnsFrom = reference.columns.map((it) => it.name);
  18567. const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
  18568. const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
  18569. const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
  18570. let name = fk5.getName();
  18571. if (casing2 !== void 0) {
  18572. for (let i4 = 0; i4 < originalColumnsFrom.length; i4++) {
  18573. name = name.replace(originalColumnsFrom[i4], columnsFrom[i4]);
  18574. }
  18575. for (let i4 = 0; i4 < originalColumnsTo.length; i4++) {
  18576. name = name.replace(originalColumnsTo[i4], columnsTo[i4]);
  18577. }
  18578. }
  18579. return {
  18580. name,
  18581. tableFrom,
  18582. tableTo,
  18583. columnsFrom,
  18584. columnsTo,
  18585. onDelete,
  18586. onUpdate
  18587. };
  18588. });
  18589. foreignKeys.forEach((it) => {
  18590. foreignKeysObject[it.name] = it;
  18591. });
  18592. indexes.forEach((value) => {
  18593. const columns2 = value.config.columns;
  18594. const name = value.config.name;
  18595. let indexColumns = columns2.map((it) => {
  18596. var _a2;
  18597. if ((0, import_drizzle_orm6.is)(it, import_drizzle_orm6.SQL)) {
  18598. const sql = dialect6.sqlToQuery(it, "indexes").sql;
  18599. if (typeof internal.indexes[name] === "undefined") {
  18600. internal.indexes[name] = {
  18601. columns: {
  18602. [sql]: {
  18603. isExpression: true
  18604. }
  18605. }
  18606. };
  18607. } else {
  18608. if (typeof ((_a2 = internal.indexes[name]) == null ? void 0 : _a2.columns[sql]) === "undefined") {
  18609. internal.indexes[name].columns[sql] = {
  18610. isExpression: true
  18611. };
  18612. } else {
  18613. internal.indexes[name].columns[sql].isExpression = true;
  18614. }
  18615. }
  18616. return sql;
  18617. } else {
  18618. return getColumnCasing(it, casing2);
  18619. }
  18620. });
  18621. let where = void 0;
  18622. if (value.config.where !== void 0) {
  18623. if ((0, import_drizzle_orm6.is)(value.config.where, import_drizzle_orm6.SQL)) {
  18624. where = dialect6.sqlToQuery(value.config.where).sql;
  18625. }
  18626. }
  18627. indexesObject[name] = {
  18628. name,
  18629. columns: indexColumns,
  18630. isUnique: value.config.unique ?? false,
  18631. where
  18632. };
  18633. });
  18634. uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
  18635. const columnNames = unq.columns.map((c3) => getColumnCasing(c3, casing2));
  18636. const name = unq.name ?? (0, import_sqlite_core2.uniqueKeyName)(table6, columnNames);
  18637. const existingUnique = indexesObject[name];
  18638. if (typeof existingUnique !== "undefined") {
  18639. console.log(
  18640. `
  18641. ${withStyle.errorWarning(
  18642. `We've found duplicated unique constraint names in ${source_default.underline.blue(
  18643. tableName
  18644. )} table.
  18645. The unique constraint ${source_default.underline.blue(
  18646. name
  18647. )} on the ${source_default.underline.blue(
  18648. columnNames.join(",")
  18649. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  18650. existingUnique.columns.join(",")
  18651. )} columns
  18652. `
  18653. )}`
  18654. );
  18655. process.exit(1);
  18656. }
  18657. indexesObject[name] = {
  18658. name: unq.name,
  18659. columns: columnNames,
  18660. isUnique: true
  18661. };
  18662. });
  18663. primaryKeys.forEach((it) => {
  18664. if (it.columns.length > 1) {
  18665. const originalColumnNames = it.columns.map((c3) => c3.name);
  18666. const columnNames = it.columns.map((c3) => getColumnCasing(c3, casing2));
  18667. let name = it.getName();
  18668. if (casing2 !== void 0) {
  18669. for (let i4 = 0; i4 < originalColumnNames.length; i4++) {
  18670. name = name.replace(originalColumnNames[i4], columnNames[i4]);
  18671. }
  18672. }
  18673. primaryKeysObject[name] = {
  18674. columns: columnNames,
  18675. name
  18676. };
  18677. } else {
  18678. columnsObject[getColumnCasing(it.columns[0], casing2)].primaryKey = true;
  18679. }
  18680. });
  18681. checks.forEach((check2) => {
  18682. const checkName = check2.name;
  18683. if (typeof checksInTable[tableName] !== "undefined") {
  18684. if (checksInTable[tableName].includes(check2.name)) {
  18685. console.log(
  18686. `
  18687. ${withStyle.errorWarning(
  18688. `We've found duplicated check constraint name in ${source_default.underline.blue(
  18689. tableName
  18690. )}. Please rename your check constraint in the ${source_default.underline.blue(
  18691. tableName
  18692. )} table`
  18693. )}`
  18694. );
  18695. process.exit(1);
  18696. }
  18697. checksInTable[tableName].push(checkName);
  18698. } else {
  18699. checksInTable[tableName] = [check2.name];
  18700. }
  18701. checkConstraintObject[checkName] = {
  18702. name: checkName,
  18703. value: dialect6.sqlToQuery(check2.value).sql
  18704. };
  18705. });
  18706. result[tableName] = {
  18707. name: tableName,
  18708. columns: columnsObject,
  18709. indexes: indexesObject,
  18710. foreignKeys: foreignKeysObject,
  18711. compositePrimaryKeys: primaryKeysObject,
  18712. uniqueConstraints: uniqueConstraintObject,
  18713. checkConstraints: checkConstraintObject
  18714. };
  18715. }
  18716. for (const view5 of views) {
  18717. const { name, isExisting, selectedFields, query, schema: schema6 } = (0, import_sqlite_core2.getViewConfig)(view5);
  18718. const columnsObject = {};
  18719. const existingView = resultViews[name];
  18720. if (typeof existingView !== "undefined") {
  18721. console.log(
  18722. `
  18723. ${withStyle.errorWarning(
  18724. `We've found duplicated view name across ${source_default.underline.blue(
  18725. schema6 ?? "public"
  18726. )} schema. Please rename your view`
  18727. )}`
  18728. );
  18729. process.exit(1);
  18730. }
  18731. for (const key in selectedFields) {
  18732. if ((0, import_drizzle_orm6.is)(selectedFields[key], import_sqlite_core2.SQLiteColumn)) {
  18733. const column11 = selectedFields[key];
  18734. const notNull = column11.notNull;
  18735. const primaryKey = column11.primary;
  18736. const generated = column11.generated;
  18737. const columnToSet = {
  18738. name: column11.name,
  18739. type: column11.getSQLType(),
  18740. primaryKey,
  18741. notNull,
  18742. autoincrement: (0, import_drizzle_orm6.is)(column11, import_sqlite_core2.SQLiteBaseInteger) ? column11.autoIncrement : false,
  18743. generated: generated ? {
  18744. as: (0, import_drizzle_orm6.is)(generated.as, import_drizzle_orm6.SQL) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
  18745. type: generated.mode ?? "virtual"
  18746. } : void 0
  18747. };
  18748. if (column11.default !== void 0) {
  18749. if ((0, import_drizzle_orm6.is)(column11.default, import_drizzle_orm6.SQL)) {
  18750. columnToSet.default = sqlToStr(column11.default, casing2);
  18751. } else {
  18752. columnToSet.default = typeof column11.default === "string" ? `'${column11.default}'` : typeof column11.default === "object" || Array.isArray(column11.default) ? `'${JSON.stringify(column11.default)}'` : column11.default;
  18753. }
  18754. }
  18755. columnsObject[column11.name] = columnToSet;
  18756. }
  18757. }
  18758. resultViews[name] = {
  18759. columns: columnsObject,
  18760. name,
  18761. isExisting,
  18762. definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql
  18763. };
  18764. }
  18765. return {
  18766. version: "6",
  18767. dialect: "sqlite",
  18768. tables: result,
  18769. views: resultViews,
  18770. enums: {},
  18771. _meta: {
  18772. tables: {},
  18773. columns: {}
  18774. },
  18775. internal
  18776. };
  18777. };
  18778. fromDatabase3 = async (db, tablesFilter = (table6) => true, progressCallback) => {
  18779. const result = {};
  18780. const resultViews = {};
  18781. const columns = await db.query(`SELECT
  18782. m.name as "tableName",
  18783. p.name as "columnName",
  18784. p.type as "columnType",
  18785. p."notnull" as "notNull",
  18786. p.dflt_value as "defaultValue",
  18787. p.pk as pk,
  18788. p.hidden as hidden,
  18789. m.sql,
  18790. m.type as type
  18791. FROM sqlite_master AS m
  18792. JOIN pragma_table_xinfo(m.name) AS p
  18793. WHERE (m.type = 'table' OR m.type = 'view')
  18794. AND ${filterIgnoredTablesByField("m.tbl_name")};`);
  18795. const tablesWithSeq = [];
  18796. const seq = await db.query(`SELECT
  18797. *
  18798. FROM sqlite_master
  18799. WHERE sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*'
  18800. AND ${filterIgnoredTablesByField("tbl_name")};`);
  18801. for (const s4 of seq) {
  18802. tablesWithSeq.push(s4.name);
  18803. }
  18804. let columnsCount = 0;
  18805. let tablesCount = /* @__PURE__ */ new Set();
  18806. let indexesCount = 0;
  18807. let foreignKeysCount = 0;
  18808. let checksCount = 0;
  18809. let viewsCount = 0;
  18810. const tableToPk = {};
  18811. let tableToGeneratedColumnsInfo = {};
  18812. for (const column11 of columns) {
  18813. if (!tablesFilter(column11.tableName)) continue;
  18814. if (column11.type !== "view") {
  18815. columnsCount += 1;
  18816. }
  18817. if (progressCallback) {
  18818. progressCallback("columns", columnsCount, "fetching");
  18819. }
  18820. const tableName = column11.tableName;
  18821. tablesCount.add(tableName);
  18822. if (progressCallback) {
  18823. progressCallback("tables", tablesCount.size, "fetching");
  18824. }
  18825. const columnName = column11.columnName;
  18826. const isNotNull = column11.notNull === 1;
  18827. const columnType = column11.columnType;
  18828. const isPrimary = column11.pk !== 0;
  18829. const columnDefault = column11.defaultValue;
  18830. const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
  18831. if (isPrimary) {
  18832. if (typeof tableToPk[tableName] === "undefined") {
  18833. tableToPk[tableName] = [columnName];
  18834. } else {
  18835. tableToPk[tableName].push(columnName);
  18836. }
  18837. }
  18838. const table6 = result[tableName];
  18839. if (column11.hidden === 2 || column11.hidden === 3) {
  18840. if (typeof tableToGeneratedColumnsInfo[column11.tableName] === "undefined") {
  18841. tableToGeneratedColumnsInfo[column11.tableName] = extractGeneratedColumns(
  18842. column11.sql
  18843. );
  18844. }
  18845. }
  18846. const newColumn = {
  18847. default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
  18848. columnDefault
  18849. ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : `(${columnDefault})`,
  18850. autoincrement: isAutoincrement,
  18851. name: columnName,
  18852. type: mapSqlToSqliteType(columnType),
  18853. primaryKey: false,
  18854. notNull: isNotNull,
  18855. generated: tableToGeneratedColumnsInfo[tableName] && tableToGeneratedColumnsInfo[tableName][columnName] ? {
  18856. type: tableToGeneratedColumnsInfo[tableName][columnName].type,
  18857. as: tableToGeneratedColumnsInfo[tableName][columnName].expression
  18858. } : void 0
  18859. };
  18860. if (!table6) {
  18861. result[tableName] = {
  18862. name: tableName,
  18863. columns: {
  18864. [columnName]: newColumn
  18865. },
  18866. compositePrimaryKeys: {},
  18867. indexes: {},
  18868. foreignKeys: {},
  18869. uniqueConstraints: {},
  18870. checkConstraints: {}
  18871. };
  18872. } else {
  18873. result[tableName].columns[columnName] = newColumn;
  18874. }
  18875. }
  18876. for (const [key, value] of Object.entries(tableToPk)) {
  18877. if (value.length > 1) {
  18878. result[key].compositePrimaryKeys = {
  18879. [`${key}_${value.join("_")}_pk`]: {
  18880. columns: value,
  18881. name: `${key}_${value.join("_")}_pk`
  18882. }
  18883. };
  18884. } else if (value.length === 1) {
  18885. result[key].columns[value[0]].primaryKey = true;
  18886. } else {
  18887. }
  18888. }
  18889. if (progressCallback) {
  18890. progressCallback("columns", columnsCount, "done");
  18891. progressCallback("tables", tablesCount.size, "done");
  18892. }
  18893. try {
  18894. const fks = await db.query(`SELECT
  18895. m.name as "tableFrom",
  18896. f.id as "id",
  18897. f."table" as "tableTo",
  18898. f."from",
  18899. f."to",
  18900. f."on_update" as "onUpdate",
  18901. f."on_delete" as "onDelete",
  18902. f.seq as "seq"
  18903. FROM
  18904. sqlite_master m,
  18905. pragma_foreign_key_list(m.name) as f
  18906. WHERE ${filterIgnoredTablesByField("m.tbl_name")};`);
  18907. const fkByTableName = {};
  18908. for (const fkRow of fks) {
  18909. foreignKeysCount += 1;
  18910. if (progressCallback) {
  18911. progressCallback("fks", foreignKeysCount, "fetching");
  18912. }
  18913. const tableName = fkRow.tableFrom;
  18914. const columnName = fkRow.from;
  18915. const refTableName = fkRow.tableTo;
  18916. const refColumnName = fkRow.to;
  18917. const updateRule = fkRow.onUpdate;
  18918. const deleteRule = fkRow.onDelete;
  18919. const sequence = fkRow.seq;
  18920. const id = fkRow.id;
  18921. const tableInResult = result[tableName];
  18922. if (typeof tableInResult === "undefined") continue;
  18923. if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
  18924. fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
  18925. fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
  18926. } else {
  18927. fkByTableName[`${tableName}_${id}`] = {
  18928. name: "",
  18929. tableFrom: tableName,
  18930. tableTo: refTableName,
  18931. columnsFrom: [columnName],
  18932. columnsTo: [refColumnName],
  18933. onDelete: deleteRule == null ? void 0 : deleteRule.toLowerCase(),
  18934. onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
  18935. };
  18936. }
  18937. const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
  18938. const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
  18939. fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
  18940. "_"
  18941. )}_${refTableName}_${columnsTo.join("_")}_fk`;
  18942. }
  18943. for (const idx of Object.keys(fkByTableName)) {
  18944. const value = fkByTableName[idx];
  18945. result[value.tableFrom].foreignKeys[value.name] = value;
  18946. }
  18947. } catch (e4) {
  18948. }
  18949. if (progressCallback) {
  18950. progressCallback("fks", foreignKeysCount, "done");
  18951. }
  18952. const idxs = await db.query(`SELECT
  18953. m.tbl_name as tableName,
  18954. il.name as indexName,
  18955. ii.name as columnName,
  18956. il.[unique] as isUnique,
  18957. il.seq as seq
  18958. FROM
  18959. sqlite_master AS m,
  18960. pragma_index_list(m.name) AS il,
  18961. pragma_index_info(il.name) AS ii
  18962. WHERE
  18963. m.type = 'table'
  18964. AND il.name NOT LIKE 'sqlite\\_autoindex\\_%' ESCAPE '\\'
  18965. AND ${filterIgnoredTablesByField("m.tbl_name")};`);
  18966. for (const idxRow of idxs) {
  18967. const tableName = idxRow.tableName;
  18968. const constraintName = idxRow.indexName;
  18969. const columnName = idxRow.columnName;
  18970. const isUnique = idxRow.isUnique === 1;
  18971. const tableInResult = result[tableName];
  18972. if (typeof tableInResult === "undefined") continue;
  18973. indexesCount += 1;
  18974. if (progressCallback) {
  18975. progressCallback("indexes", indexesCount, "fetching");
  18976. }
  18977. if (typeof tableInResult.indexes[constraintName] !== "undefined" && columnName) {
  18978. tableInResult.indexes[constraintName].columns.push(columnName);
  18979. } else {
  18980. tableInResult.indexes[constraintName] = {
  18981. name: constraintName,
  18982. columns: columnName ? [columnName] : [],
  18983. isUnique
  18984. };
  18985. }
  18986. }
  18987. if (progressCallback) {
  18988. progressCallback("indexes", indexesCount, "done");
  18989. progressCallback("enums", 0, "done");
  18990. }
  18991. const views = await db.query(
  18992. `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';`
  18993. );
  18994. viewsCount = views.length;
  18995. if (progressCallback) {
  18996. progressCallback("views", viewsCount, "fetching");
  18997. }
  18998. for (const view5 of views) {
  18999. const viewName = view5["view_name"];
  19000. const sql = view5["sql"];
  19001. const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i");
  19002. const match2 = sql.match(regex);
  19003. if (!match2) {
  19004. console.log("Could not process view");
  19005. process.exit(1);
  19006. }
  19007. const viewDefinition = match2[1];
  19008. const columns2 = result[viewName].columns;
  19009. delete result[viewName];
  19010. resultViews[viewName] = {
  19011. columns: columns2,
  19012. isExisting: false,
  19013. name: viewName,
  19014. definition: viewDefinition
  19015. };
  19016. }
  19017. if (progressCallback) {
  19018. progressCallback("views", viewsCount, "done");
  19019. }
  19020. const namedCheckPattern = /CONSTRAINT\s*["']?(\w+)["']?\s*CHECK\s*\((.*?)\)/gi;
  19021. const unnamedCheckPattern = /CHECK\s*\((.*?)\)/gi;
  19022. let checkCounter = 0;
  19023. const checkConstraints = {};
  19024. const checks = await db.query(`SELECT
  19025. name as "tableName",
  19026. sql as "sql"
  19027. FROM sqlite_master
  19028. WHERE type = 'table'
  19029. AND ${filterIgnoredTablesByField("tbl_name")};`);
  19030. for (const check2 of checks) {
  19031. if (!tablesFilter(check2.tableName)) continue;
  19032. const { tableName, sql } = check2;
  19033. let namedChecks = [...sql.matchAll(namedCheckPattern)];
  19034. if (namedChecks.length > 0) {
  19035. namedChecks.forEach(([_3, checkName, checkValue]) => {
  19036. checkConstraints[checkName] = {
  19037. name: checkName,
  19038. value: checkValue.trim()
  19039. };
  19040. });
  19041. } else {
  19042. let unnamedChecks = [...sql.matchAll(unnamedCheckPattern)];
  19043. unnamedChecks.forEach(([_3, checkValue]) => {
  19044. let checkName = `${tableName}_check_${++checkCounter}`;
  19045. checkConstraints[checkName] = {
  19046. name: checkName,
  19047. value: checkValue.trim()
  19048. };
  19049. });
  19050. }
  19051. checksCount += Object.values(checkConstraints).length;
  19052. if (progressCallback) {
  19053. progressCallback("checks", checksCount, "fetching");
  19054. }
  19055. const table6 = result[tableName];
  19056. if (!table6) {
  19057. result[tableName] = {
  19058. name: tableName,
  19059. columns: {},
  19060. compositePrimaryKeys: {},
  19061. indexes: {},
  19062. foreignKeys: {},
  19063. uniqueConstraints: {},
  19064. checkConstraints
  19065. };
  19066. } else {
  19067. result[tableName].checkConstraints = checkConstraints;
  19068. }
  19069. }
  19070. if (progressCallback) {
  19071. progressCallback("checks", checksCount, "done");
  19072. }
  19073. return {
  19074. version: "6",
  19075. dialect: "sqlite",
  19076. tables: result,
  19077. views: resultViews,
  19078. enums: {},
  19079. _meta: {
  19080. tables: {},
  19081. columns: {}
  19082. }
  19083. };
  19084. };
  19085. }
  19086. });
  19087. // src/serializer/singlestoreImports.ts
  19088. var singlestoreImports_exports = {};
  19089. __export(singlestoreImports_exports, {
  19090. prepareFromExports: () => prepareFromExports4,
  19091. prepareFromSingleStoreImports: () => prepareFromSingleStoreImports
  19092. });
  19093. var import_drizzle_orm7, import_singlestore_core, prepareFromExports4, prepareFromSingleStoreImports;
  19094. var init_singlestoreImports = __esm({
  19095. "src/serializer/singlestoreImports.ts"() {
  19096. "use strict";
  19097. import_drizzle_orm7 = require("drizzle-orm");
  19098. import_singlestore_core = require("drizzle-orm/singlestore-core");
  19099. init_utils3();
  19100. prepareFromExports4 = (exports2) => {
  19101. const tables = [];
  19102. const i0values = Object.values(exports2);
  19103. i0values.forEach((t4) => {
  19104. if ((0, import_drizzle_orm7.is)(t4, import_singlestore_core.SingleStoreTable)) {
  19105. tables.push(t4);
  19106. }
  19107. });
  19108. return {
  19109. tables
  19110. /* views */
  19111. };
  19112. };
  19113. prepareFromSingleStoreImports = async (imports) => {
  19114. const tables = [];
  19115. await safeRegister(async () => {
  19116. for (let i4 = 0; i4 < imports.length; i4++) {
  19117. const it = imports[i4];
  19118. const i0 = require(`${it}`);
  19119. const prepared = prepareFromExports4(i0);
  19120. tables.push(...prepared.tables);
  19121. }
  19122. });
  19123. return {
  19124. tables: Array.from(new Set(tables))
  19125. /* , views */
  19126. };
  19127. };
  19128. }
  19129. });
  19130. // src/serializer/singlestoreSerializer.ts
  19131. var singlestoreSerializer_exports = {};
  19132. __export(singlestoreSerializer_exports, {
  19133. fromDatabase: () => fromDatabase4,
  19134. generateSingleStoreSnapshot: () => generateSingleStoreSnapshot,
  19135. indexName: () => indexName3
  19136. });
  19137. function clearDefaults2(defaultValue, collate) {
  19138. if (typeof collate === "undefined" || collate === null) {
  19139. collate = `utf8mb4`;
  19140. }
  19141. let resultDefault = defaultValue;
  19142. collate = `_${collate}`;
  19143. if (defaultValue.startsWith(collate)) {
  19144. resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
  19145. if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
  19146. return `('${resultDefault.substring(1, resultDefault.length - 1)}')`;
  19147. } else {
  19148. return `'${resultDefault}'`;
  19149. }
  19150. } else {
  19151. return `(${resultDefault})`;
  19152. }
  19153. }
  19154. var import_drizzle_orm8, import_singlestore_core2, dialect5, indexName3, generateSingleStoreSnapshot, fromDatabase4;
  19155. var init_singlestoreSerializer = __esm({
  19156. "src/serializer/singlestoreSerializer.ts"() {
  19157. "use strict";
  19158. init_source();
  19159. import_drizzle_orm8 = require("drizzle-orm");
  19160. import_singlestore_core2 = require("drizzle-orm/singlestore-core");
  19161. init_outputs();
  19162. init_utils4();
  19163. dialect5 = new import_singlestore_core2.SingleStoreDialect();
  19164. indexName3 = (tableName, columns) => {
  19165. return `${tableName}_${columns.join("_")}_index`;
  19166. };
  19167. generateSingleStoreSnapshot = (tables, casing2) => {
  19168. const dialect6 = new import_singlestore_core2.SingleStoreDialect({ casing: casing2 });
  19169. const result = {};
  19170. const internal = { tables: {}, indexes: {} };
  19171. for (const table6 of tables) {
  19172. const {
  19173. name: tableName,
  19174. columns,
  19175. indexes,
  19176. schema: schema6,
  19177. primaryKeys,
  19178. uniqueConstraints
  19179. } = (0, import_singlestore_core2.getTableConfig)(table6);
  19180. const columnsObject = {};
  19181. const indexesObject = {};
  19182. const primaryKeysObject = {};
  19183. const uniqueConstraintObject = {};
  19184. columns.forEach((column11) => {
  19185. const notNull = column11.notNull;
  19186. const sqlTypeLowered = column11.getSQLType().toLowerCase();
  19187. const autoIncrement = typeof column11.autoIncrement === "undefined" ? false : column11.autoIncrement;
  19188. const generated = column11.generated;
  19189. const columnToSet = {
  19190. name: column11.name,
  19191. type: column11.getSQLType(),
  19192. primaryKey: false,
  19193. // If field is autoincrement it's notNull by default
  19194. // notNull: autoIncrement ? true : notNull,
  19195. notNull,
  19196. autoincrement: autoIncrement,
  19197. onUpdate: column11.hasOnUpdateNow,
  19198. generated: generated ? {
  19199. as: (0, import_drizzle_orm8.is)(generated.as, import_drizzle_orm8.SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
  19200. type: generated.mode ?? "stored"
  19201. } : void 0
  19202. };
  19203. if (column11.primary) {
  19204. primaryKeysObject[`${tableName}_${column11.name}`] = {
  19205. name: `${tableName}_${column11.name}`,
  19206. columns: [column11.name]
  19207. };
  19208. }
  19209. if (column11.isUnique) {
  19210. const existingUnique = uniqueConstraintObject[column11.uniqueName];
  19211. if (typeof existingUnique !== "undefined") {
  19212. console.log(
  19213. `
  19214. ${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
  19215. tableName
  19216. )} table.
  19217. The unique constraint ${source_default.underline.blue(
  19218. column11.uniqueName
  19219. )} on the ${source_default.underline.blue(
  19220. column11.name
  19221. )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  19222. existingUnique.columns.join(",")
  19223. )} columns
  19224. `)}`
  19225. );
  19226. process.exit(1);
  19227. }
  19228. uniqueConstraintObject[column11.uniqueName] = {
  19229. name: column11.uniqueName,
  19230. columns: [columnToSet.name]
  19231. };
  19232. }
  19233. if (column11.default !== void 0) {
  19234. if ((0, import_drizzle_orm8.is)(column11.default, import_drizzle_orm8.SQL)) {
  19235. columnToSet.default = sqlToStr(column11.default, casing2);
  19236. } else {
  19237. if (typeof column11.default === "string") {
  19238. columnToSet.default = `'${column11.default}'`;
  19239. } else {
  19240. if (sqlTypeLowered === "json" || Array.isArray(column11.default)) {
  19241. columnToSet.default = `'${JSON.stringify(column11.default)}'`;
  19242. } else if (column11.default instanceof Date) {
  19243. if (sqlTypeLowered === "date") {
  19244. columnToSet.default = `'${column11.default.toISOString().split("T")[0]}'`;
  19245. } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
  19246. columnToSet.default = `'${column11.default.toISOString().replace("T", " ").slice(0, 23)}'`;
  19247. }
  19248. } else {
  19249. columnToSet.default = column11.default;
  19250. }
  19251. }
  19252. }
  19253. }
  19254. columnsObject[column11.name] = columnToSet;
  19255. });
  19256. primaryKeys.map((pk) => {
  19257. const columnNames = pk.columns.map((c3) => c3.name);
  19258. primaryKeysObject[pk.getName()] = {
  19259. name: pk.getName(),
  19260. columns: columnNames
  19261. };
  19262. for (const column11 of pk.columns) {
  19263. columnsObject[column11.name].notNull = true;
  19264. }
  19265. });
  19266. uniqueConstraints == null ? void 0 : uniqueConstraints.map((unq) => {
  19267. const columnNames = unq.columns.map((c3) => c3.name);
  19268. const name = unq.name ?? (0, import_singlestore_core2.uniqueKeyName)(table6, columnNames);
  19269. const existingUnique = uniqueConstraintObject[name];
  19270. if (typeof existingUnique !== "undefined") {
  19271. console.log(
  19272. `
  19273. ${withStyle.errorWarning(
  19274. `We've found duplicated unique constraint names in ${source_default.underline.blue(
  19275. tableName
  19276. )} table.
  19277. The unique constraint ${source_default.underline.blue(
  19278. name
  19279. )} on the ${source_default.underline.blue(
  19280. columnNames.join(",")
  19281. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  19282. existingUnique.columns.join(",")
  19283. )} columns
  19284. `
  19285. )}`
  19286. );
  19287. process.exit(1);
  19288. }
  19289. uniqueConstraintObject[name] = {
  19290. name: unq.name,
  19291. columns: columnNames
  19292. };
  19293. });
  19294. indexes.forEach((value) => {
  19295. const columns2 = value.config.columns;
  19296. const name = value.config.name;
  19297. let indexColumns = columns2.map((it) => {
  19298. var _a2;
  19299. if ((0, import_drizzle_orm8.is)(it, import_drizzle_orm8.SQL)) {
  19300. const sql = dialect6.sqlToQuery(it, "indexes").sql;
  19301. if (typeof internal.indexes[name] === "undefined") {
  19302. internal.indexes[name] = {
  19303. columns: {
  19304. [sql]: {
  19305. isExpression: true
  19306. }
  19307. }
  19308. };
  19309. } else {
  19310. if (typeof ((_a2 = internal.indexes[name]) == null ? void 0 : _a2.columns[sql]) === "undefined") {
  19311. internal.indexes[name].columns[sql] = {
  19312. isExpression: true
  19313. };
  19314. } else {
  19315. internal.indexes[name].columns[sql].isExpression = true;
  19316. }
  19317. }
  19318. return sql;
  19319. } else {
  19320. return `${it.name}`;
  19321. }
  19322. });
  19323. if (value.config.unique) {
  19324. if (typeof uniqueConstraintObject[name] !== "undefined") {
  19325. console.log(
  19326. `
  19327. ${withStyle.errorWarning(
  19328. `We've found duplicated unique constraint names in ${source_default.underline.blue(
  19329. tableName
  19330. )} table.
  19331. The unique index ${source_default.underline.blue(
  19332. name
  19333. )} on the ${source_default.underline.blue(
  19334. indexColumns.join(",")
  19335. )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
  19336. uniqueConstraintObject[name].columns.join(",")
  19337. )} columns
  19338. `
  19339. )}`
  19340. );
  19341. process.exit(1);
  19342. }
  19343. }
  19344. indexesObject[name] = {
  19345. name,
  19346. columns: indexColumns,
  19347. isUnique: value.config.unique ?? false,
  19348. using: value.config.using,
  19349. algorithm: value.config.algorithm,
  19350. lock: value.config.lock
  19351. };
  19352. });
  19353. if (!schema6) {
  19354. result[tableName] = {
  19355. name: tableName,
  19356. columns: columnsObject,
  19357. indexes: indexesObject,
  19358. compositePrimaryKeys: primaryKeysObject,
  19359. uniqueConstraints: uniqueConstraintObject
  19360. };
  19361. }
  19362. }
  19363. return {
  19364. version: "1",
  19365. dialect: "singlestore",
  19366. tables: result,
  19367. /* views: resultViews, */
  19368. _meta: {
  19369. tables: {},
  19370. columns: {}
  19371. },
  19372. internal
  19373. };
  19374. };
  19375. fromDatabase4 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => {
  19376. const result = {};
  19377. const internals = { tables: {}, indexes: {} };
  19378. const columns = await db.query(`select * from information_schema.columns
  19379. where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
  19380. order by table_name, ordinal_position;`);
  19381. const response = columns;
  19382. const schemas = [];
  19383. let columnsCount = 0;
  19384. let tablesCount = /* @__PURE__ */ new Set();
  19385. let indexesCount = 0;
  19386. const idxs = await db.query(
  19387. `select * from INFORMATION_SCHEMA.STATISTICS
  19388. WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
  19389. );
  19390. const idxRows = idxs;
  19391. for (const column11 of response) {
  19392. if (!tablesFilter(column11["TABLE_NAME"])) continue;
  19393. columnsCount += 1;
  19394. if (progressCallback) {
  19395. progressCallback("columns", columnsCount, "fetching");
  19396. }
  19397. const schema6 = column11["TABLE_SCHEMA"];
  19398. const tableName = column11["TABLE_NAME"];
  19399. tablesCount.add(`${schema6}.${tableName}`);
  19400. if (progressCallback) {
  19401. progressCallback("columns", tablesCount.size, "fetching");
  19402. }
  19403. const columnName = column11["COLUMN_NAME"];
  19404. const isNullable = column11["IS_NULLABLE"] === "YES";
  19405. const dataType = column11["DATA_TYPE"];
  19406. const columnType = column11["COLUMN_TYPE"];
  19407. const isPrimary = column11["COLUMN_KEY"] === "PRI";
  19408. let columnDefault = column11["COLUMN_DEFAULT"];
  19409. const collation = column11["CHARACTER_SET_NAME"];
  19410. const geenratedExpression = column11["GENERATION_EXPRESSION"];
  19411. let columnExtra = column11["EXTRA"];
  19412. let isAutoincrement = false;
  19413. let isDefaultAnExpression = false;
  19414. if (typeof column11["EXTRA"] !== "undefined") {
  19415. columnExtra = column11["EXTRA"];
  19416. isAutoincrement = column11["EXTRA"] === "auto_increment";
  19417. isDefaultAnExpression = column11["EXTRA"].includes("DEFAULT_GENERATED");
  19418. }
  19419. if (schema6 !== inputSchema) {
  19420. schemas.push(schema6);
  19421. }
  19422. const table6 = result[tableName];
  19423. let changedType = columnType;
  19424. if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) {
  19425. const uniqueIdx = idxRows.filter(
  19426. (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0
  19427. );
  19428. if (uniqueIdx && uniqueIdx.length === 1) {
  19429. changedType = columnType.replace("bigint unsigned", "serial");
  19430. }
  19431. }
  19432. if (columnType.startsWith("bigint(") || columnType.startsWith("tinyint(") || columnType.startsWith("date(") || columnType.startsWith("int(") || columnType.startsWith("mediumint(") || columnType.startsWith("smallint(") || columnType.startsWith("text(") || columnType.startsWith("time(") || columnType.startsWith("year(")) {
  19433. changedType = columnType.replace(/\(\s*[^)]*\)$/, "");
  19434. }
  19435. if (columnType.includes("decimal(10,0)")) {
  19436. changedType = columnType.replace("decimal(10,0)", "decimal");
  19437. }
  19438. if (columnDefault == null ? void 0 : columnDefault.endsWith(".")) {
  19439. columnDefault = columnDefault.slice(0, -1);
  19440. }
  19441. let onUpdate = void 0;
  19442. if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) {
  19443. onUpdate = true;
  19444. }
  19445. const newColumn = {
  19446. default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults2(columnDefault, collation) : columnDefault.startsWith("CURRENT_TIMESTAMP") ? "CURRENT_TIMESTAMP" : `'${columnDefault}'`,
  19447. autoincrement: isAutoincrement,
  19448. name: columnName,
  19449. type: changedType,
  19450. primaryKey: false,
  19451. notNull: !isNullable,
  19452. onUpdate,
  19453. generated: geenratedExpression ? {
  19454. as: geenratedExpression,
  19455. type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored"
  19456. } : void 0
  19457. };
  19458. if (isDefaultAnExpression) {
  19459. if (typeof internals.tables[tableName] === "undefined") {
  19460. internals.tables[tableName] = {
  19461. columns: {
  19462. [columnName]: {
  19463. isDefaultAnExpression: true
  19464. }
  19465. }
  19466. };
  19467. } else {
  19468. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  19469. internals.tables[tableName].columns[columnName] = {
  19470. isDefaultAnExpression: true
  19471. };
  19472. } else {
  19473. internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
  19474. }
  19475. }
  19476. }
  19477. if (!table6) {
  19478. result[tableName] = {
  19479. name: tableName,
  19480. columns: {
  19481. [columnName]: newColumn
  19482. },
  19483. compositePrimaryKeys: {},
  19484. indexes: {},
  19485. uniqueConstraints: {}
  19486. };
  19487. } else {
  19488. result[tableName].columns[columnName] = newColumn;
  19489. }
  19490. }
  19491. const tablePks = await db.query(
  19492. `SELECT table_name, column_name, ordinal_position
  19493. FROM information_schema.table_constraints t
  19494. LEFT JOIN information_schema.key_column_usage k
  19495. USING(constraint_name,table_schema,table_name)
  19496. WHERE t.constraint_type='UNIQUE'
  19497. and table_name != '__drizzle_migrations'
  19498. AND t.table_schema = '${inputSchema}'
  19499. ORDER BY ordinal_position`
  19500. );
  19501. const tableToPk = {};
  19502. const tableToPkRows = tablePks;
  19503. for (const tableToPkRow of tableToPkRows) {
  19504. const tableName = tableToPkRow["table_name"];
  19505. const columnName = tableToPkRow["column_name"];
  19506. const position = tableToPkRow["ordinal_position"];
  19507. if (typeof result[tableName] === "undefined") {
  19508. continue;
  19509. }
  19510. if (typeof tableToPk[tableName] === "undefined") {
  19511. tableToPk[tableName] = [columnName];
  19512. } else {
  19513. tableToPk[tableName].push(columnName);
  19514. }
  19515. }
  19516. for (const [key, value] of Object.entries(tableToPk)) {
  19517. result[key].compositePrimaryKeys = {
  19518. [`${key}_${value.join("_")}`]: {
  19519. name: `${key}_${value.join("_")}`,
  19520. columns: value
  19521. }
  19522. };
  19523. }
  19524. if (progressCallback) {
  19525. progressCallback("columns", columnsCount, "done");
  19526. progressCallback("tables", tablesCount.size, "done");
  19527. }
  19528. for (const idxRow of idxRows) {
  19529. const tableSchema = idxRow["TABLE_SCHEMA"];
  19530. const tableName = idxRow["TABLE_NAME"];
  19531. const constraintName = idxRow["INDEX_NAME"];
  19532. const columnName = idxRow["COLUMN_NAME"];
  19533. const isUnique = idxRow["NON_UNIQUE"] === 0;
  19534. const tableInResult = result[tableName];
  19535. if (typeof tableInResult === "undefined") continue;
  19536. indexesCount += 1;
  19537. if (progressCallback) {
  19538. progressCallback("indexes", indexesCount, "fetching");
  19539. }
  19540. if (isUnique) {
  19541. if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") {
  19542. tableInResult.uniqueConstraints[constraintName].columns.push(
  19543. columnName
  19544. );
  19545. } else {
  19546. tableInResult.uniqueConstraints[constraintName] = {
  19547. name: constraintName,
  19548. columns: [columnName]
  19549. };
  19550. }
  19551. }
  19552. }
  19553. if (progressCallback) {
  19554. progressCallback("indexes", indexesCount, "done");
  19555. progressCallback("enums", 0, "done");
  19556. }
  19557. return {
  19558. version: "1",
  19559. dialect: "singlestore",
  19560. tables: result,
  19561. /* views: resultViews, */
  19562. _meta: {
  19563. tables: {},
  19564. columns: {}
  19565. },
  19566. internal: internals
  19567. };
  19568. };
  19569. }
  19570. });
  19571. // src/serializer/index.ts
  19572. var import_fs4, glob, import_path4, serializeMySql, serializePg, serializeSQLite, serializeSingleStore, prepareFilenames;
  19573. var init_serializer = __esm({
  19574. "src/serializer/index.ts"() {
  19575. "use strict";
  19576. init_source();
  19577. import_fs4 = __toESM(require("fs"));
  19578. glob = __toESM(require_glob());
  19579. import_path4 = __toESM(require("path"));
  19580. init_views();
  19581. serializeMySql = async (path4, casing2) => {
  19582. const filenames = prepareFilenames(path4);
  19583. console.log(source_default.gray(`Reading schema files:
  19584. ${filenames.join("\n")}
  19585. `));
  19586. const { prepareFromMySqlImports: prepareFromMySqlImports2 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
  19587. const { generateMySqlSnapshot: generateMySqlSnapshot2 } = await Promise.resolve().then(() => (init_mysqlSerializer(), mysqlSerializer_exports));
  19588. const { tables, views } = await prepareFromMySqlImports2(filenames);
  19589. return generateMySqlSnapshot2(tables, views, casing2);
  19590. };
  19591. serializePg = async (path4, casing2, schemaFilter) => {
  19592. const filenames = prepareFilenames(path4);
  19593. const { prepareFromPgImports: prepareFromPgImports2 } = await Promise.resolve().then(() => (init_pgImports(), pgImports_exports));
  19594. const { generatePgSnapshot: generatePgSnapshot2 } = await Promise.resolve().then(() => (init_pgSerializer(), pgSerializer_exports));
  19595. const { tables, enums, schemas, sequences, views, matViews, roles, policies } = await prepareFromPgImports2(
  19596. filenames
  19597. );
  19598. return generatePgSnapshot2(tables, enums, schemas, sequences, roles, policies, views, matViews, casing2, schemaFilter);
  19599. };
  19600. serializeSQLite = async (path4, casing2) => {
  19601. const filenames = prepareFilenames(path4);
  19602. const { prepareFromSqliteImports: prepareFromSqliteImports2 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
  19603. const { generateSqliteSnapshot: generateSqliteSnapshot2 } = await Promise.resolve().then(() => (init_sqliteSerializer(), sqliteSerializer_exports));
  19604. const { tables, views } = await prepareFromSqliteImports2(filenames);
  19605. return generateSqliteSnapshot2(tables, views, casing2);
  19606. };
  19607. serializeSingleStore = async (path4, casing2) => {
  19608. const filenames = prepareFilenames(path4);
  19609. console.log(source_default.gray(`Reading schema files:
  19610. ${filenames.join("\n")}
  19611. `));
  19612. const { prepareFromSingleStoreImports: prepareFromSingleStoreImports2 } = await Promise.resolve().then(() => (init_singlestoreImports(), singlestoreImports_exports));
  19613. const { generateSingleStoreSnapshot: generateSingleStoreSnapshot2 } = await Promise.resolve().then(() => (init_singlestoreSerializer(), singlestoreSerializer_exports));
  19614. const {
  19615. tables
  19616. /* views */
  19617. } = await prepareFromSingleStoreImports2(filenames);
  19618. return generateSingleStoreSnapshot2(
  19619. tables,
  19620. /* views, */
  19621. casing2
  19622. );
  19623. };
  19624. prepareFilenames = (path4) => {
  19625. if (typeof path4 === "string") {
  19626. path4 = [path4];
  19627. }
  19628. const prefix2 = process.env.TEST_CONFIG_PATH_PREFIX || "";
  19629. const result = path4.reduce((result2, cur) => {
  19630. const globbed = glob.sync(`${prefix2}${cur}`);
  19631. globbed.forEach((it) => {
  19632. const fileName = import_fs4.default.lstatSync(it).isDirectory() ? null : import_path4.default.resolve(it);
  19633. const filenames = fileName ? [fileName] : import_fs4.default.readdirSync(it).map((file) => import_path4.default.join(import_path4.default.resolve(it), file));
  19634. filenames.filter((file) => !import_fs4.default.lstatSync(file).isDirectory()).forEach((file) => result2.add(file));
  19635. });
  19636. return result2;
  19637. }, /* @__PURE__ */ new Set());
  19638. const res = [...result];
  19639. const errors = res.filter((it) => {
  19640. return !(it.endsWith(".ts") || it.endsWith(".js") || it.endsWith(".cjs") || it.endsWith(".mjs") || it.endsWith(".mts") || it.endsWith(".cts"));
  19641. });
  19642. if (res.length === 0) {
  19643. console.log(
  19644. error(
  19645. `No schema files found for path config [${path4.map((it) => `'${it}'`).join(", ")}]`
  19646. )
  19647. );
  19648. console.log(
  19649. error(
  19650. `If path represents a file - please make sure to use .ts or other extension in the path`
  19651. )
  19652. );
  19653. process.exit(1);
  19654. }
  19655. return res;
  19656. };
  19657. }
  19658. });
  19659. // src/migrationPreparator.ts
  19660. var import_crypto, import_fs5, prepareMySqlDbPushSnapshot, prepareSingleStoreDbPushSnapshot, prepareSQLiteDbPushSnapshot, prepareMySqlMigrationSnapshot, prepareSingleStoreMigrationSnapshot, prepareSqliteMigrationSnapshot, preparePgMigrationSnapshot, preparePrevSnapshot;
  19661. var init_migrationPreparator = __esm({
  19662. "src/migrationPreparator.ts"() {
  19663. "use strict";
  19664. import_crypto = require("crypto");
  19665. import_fs5 = __toESM(require("fs"));
  19666. init_serializer();
  19667. init_mysqlSchema();
  19668. init_pgSchema();
  19669. init_singlestoreSchema();
  19670. init_sqliteSchema();
  19671. prepareMySqlDbPushSnapshot = async (prev, schemaPath, casing2) => {
  19672. const serialized = await serializeMySql(schemaPath, casing2);
  19673. const id = (0, import_crypto.randomUUID)();
  19674. const idPrev = prev.id;
  19675. const { version: version3, dialect: dialect6, ...rest } = serialized;
  19676. const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
  19677. return { prev, cur: result };
  19678. };
  19679. prepareSingleStoreDbPushSnapshot = async (prev, schemaPath, casing2) => {
  19680. const serialized = await serializeSingleStore(schemaPath, casing2);
  19681. const id = (0, import_crypto.randomUUID)();
  19682. const idPrev = prev.id;
  19683. const { version: version3, dialect: dialect6, ...rest } = serialized;
  19684. const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
  19685. return { prev, cur: result };
  19686. };
  19687. prepareSQLiteDbPushSnapshot = async (prev, schemaPath, casing2) => {
  19688. const serialized = await serializeSQLite(schemaPath, casing2);
  19689. const id = (0, import_crypto.randomUUID)();
  19690. const idPrev = prev.id;
  19691. const { version: version3, dialect: dialect6, ...rest } = serialized;
  19692. const result = {
  19693. version: version3,
  19694. dialect: dialect6,
  19695. id,
  19696. prevId: idPrev,
  19697. ...rest
  19698. };
  19699. return { prev, cur: result };
  19700. };
  19701. prepareMySqlMigrationSnapshot = async (migrationFolders, schemaPath, casing2) => {
  19702. const prevSnapshot = mysqlSchema.parse(
  19703. preparePrevSnapshot(migrationFolders, dryMySql)
  19704. );
  19705. const serialized = await serializeMySql(schemaPath, casing2);
  19706. const id = (0, import_crypto.randomUUID)();
  19707. const idPrev = prevSnapshot.id;
  19708. const { version: version3, dialect: dialect6, ...rest } = serialized;
  19709. const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
  19710. const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
  19711. const custom2 = {
  19712. id,
  19713. prevId: idPrev,
  19714. ...prevRest
  19715. };
  19716. return { prev: prevSnapshot, cur: result, custom: custom2 };
  19717. };
  19718. prepareSingleStoreMigrationSnapshot = async (migrationFolders, schemaPath, casing2) => {
  19719. const prevSnapshot = singlestoreSchema.parse(
  19720. preparePrevSnapshot(migrationFolders, drySingleStore)
  19721. );
  19722. const serialized = await serializeSingleStore(schemaPath, casing2);
  19723. const id = (0, import_crypto.randomUUID)();
  19724. const idPrev = prevSnapshot.id;
  19725. const { version: version3, dialect: dialect6, ...rest } = serialized;
  19726. const result = { version: version3, dialect: dialect6, id, prevId: idPrev, ...rest };
  19727. const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
  19728. const custom2 = {
  19729. id,
  19730. prevId: idPrev,
  19731. ...prevRest
  19732. };
  19733. return { prev: prevSnapshot, cur: result, custom: custom2 };
  19734. };
  19735. prepareSqliteMigrationSnapshot = async (snapshots, schemaPath, casing2) => {
  19736. const prevSnapshot = sqliteSchema.parse(
  19737. preparePrevSnapshot(snapshots, drySQLite)
  19738. );
  19739. const serialized = await serializeSQLite(schemaPath, casing2);
  19740. const id = (0, import_crypto.randomUUID)();
  19741. const idPrev = prevSnapshot.id;
  19742. const { version: version3, dialect: dialect6, ...rest } = serialized;
  19743. const result = {
  19744. version: version3,
  19745. dialect: dialect6,
  19746. id,
  19747. prevId: idPrev,
  19748. ...rest
  19749. };
  19750. const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
  19751. const custom2 = {
  19752. id,
  19753. prevId: idPrev,
  19754. ...prevRest
  19755. };
  19756. return { prev: prevSnapshot, cur: result, custom: custom2 };
  19757. };
  19758. preparePgMigrationSnapshot = async (snapshots, schemaPath, casing2) => {
  19759. const prevSnapshot = pgSchema.parse(preparePrevSnapshot(snapshots, dryPg));
  19760. const serialized = await serializePg(schemaPath, casing2);
  19761. const id = (0, import_crypto.randomUUID)();
  19762. const idPrev = prevSnapshot.id;
  19763. const result = { id, prevId: idPrev, ...serialized };
  19764. const { id: _ignoredId, prevId: _ignoredPrevId, ...prevRest } = prevSnapshot;
  19765. const custom2 = {
  19766. id,
  19767. prevId: idPrev,
  19768. ...prevRest
  19769. };
  19770. return { prev: prevSnapshot, cur: result, custom: custom2 };
  19771. };
  19772. preparePrevSnapshot = (snapshots, defaultPrev) => {
  19773. let prevSnapshot;
  19774. if (snapshots.length === 0) {
  19775. prevSnapshot = defaultPrev;
  19776. } else {
  19777. const lastSnapshot = snapshots[snapshots.length - 1];
  19778. prevSnapshot = JSON.parse(import_fs5.default.readFileSync(lastSnapshot).toString());
  19779. }
  19780. return prevSnapshot;
  19781. };
  19782. }
  19783. });
  19784. // ../node_modules/.pnpm/heap@0.2.7/node_modules/heap/lib/heap.js
  19785. var require_heap = __commonJS({
  19786. "../node_modules/.pnpm/heap@0.2.7/node_modules/heap/lib/heap.js"(exports2, module2) {
  19787. (function() {
  19788. var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
  19789. floor = Math.floor, min = Math.min;
  19790. defaultCmp = function(x4, y2) {
  19791. if (x4 < y2) {
  19792. return -1;
  19793. }
  19794. if (x4 > y2) {
  19795. return 1;
  19796. }
  19797. return 0;
  19798. };
  19799. insort = function(a3, x4, lo, hi, cmp) {
  19800. var mid;
  19801. if (lo == null) {
  19802. lo = 0;
  19803. }
  19804. if (cmp == null) {
  19805. cmp = defaultCmp;
  19806. }
  19807. if (lo < 0) {
  19808. throw new Error("lo must be non-negative");
  19809. }
  19810. if (hi == null) {
  19811. hi = a3.length;
  19812. }
  19813. while (lo < hi) {
  19814. mid = floor((lo + hi) / 2);
  19815. if (cmp(x4, a3[mid]) < 0) {
  19816. hi = mid;
  19817. } else {
  19818. lo = mid + 1;
  19819. }
  19820. }
  19821. return [].splice.apply(a3, [lo, lo - lo].concat(x4)), x4;
  19822. };
  19823. heappush = function(array2, item, cmp) {
  19824. if (cmp == null) {
  19825. cmp = defaultCmp;
  19826. }
  19827. array2.push(item);
  19828. return _siftdown(array2, 0, array2.length - 1, cmp);
  19829. };
  19830. heappop = function(array2, cmp) {
  19831. var lastelt, returnitem;
  19832. if (cmp == null) {
  19833. cmp = defaultCmp;
  19834. }
  19835. lastelt = array2.pop();
  19836. if (array2.length) {
  19837. returnitem = array2[0];
  19838. array2[0] = lastelt;
  19839. _siftup(array2, 0, cmp);
  19840. } else {
  19841. returnitem = lastelt;
  19842. }
  19843. return returnitem;
  19844. };
  19845. heapreplace = function(array2, item, cmp) {
  19846. var returnitem;
  19847. if (cmp == null) {
  19848. cmp = defaultCmp;
  19849. }
  19850. returnitem = array2[0];
  19851. array2[0] = item;
  19852. _siftup(array2, 0, cmp);
  19853. return returnitem;
  19854. };
  19855. heappushpop = function(array2, item, cmp) {
  19856. var _ref;
  19857. if (cmp == null) {
  19858. cmp = defaultCmp;
  19859. }
  19860. if (array2.length && cmp(array2[0], item) < 0) {
  19861. _ref = [array2[0], item], item = _ref[0], array2[0] = _ref[1];
  19862. _siftup(array2, 0, cmp);
  19863. }
  19864. return item;
  19865. };
  19866. heapify = function(array2, cmp) {
  19867. var i4, _i, _j, _len, _ref, _ref1, _results, _results1;
  19868. if (cmp == null) {
  19869. cmp = defaultCmp;
  19870. }
  19871. _ref1 = function() {
  19872. _results1 = [];
  19873. for (var _j2 = 0, _ref2 = floor(array2.length / 2); 0 <= _ref2 ? _j2 < _ref2 : _j2 > _ref2; 0 <= _ref2 ? _j2++ : _j2--) {
  19874. _results1.push(_j2);
  19875. }
  19876. return _results1;
  19877. }.apply(this).reverse();
  19878. _results = [];
  19879. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  19880. i4 = _ref1[_i];
  19881. _results.push(_siftup(array2, i4, cmp));
  19882. }
  19883. return _results;
  19884. };
  19885. updateItem = function(array2, item, cmp) {
  19886. var pos;
  19887. if (cmp == null) {
  19888. cmp = defaultCmp;
  19889. }
  19890. pos = array2.indexOf(item);
  19891. if (pos === -1) {
  19892. return;
  19893. }
  19894. _siftdown(array2, 0, pos, cmp);
  19895. return _siftup(array2, pos, cmp);
  19896. };
  19897. nlargest = function(array2, n3, cmp) {
  19898. var elem, result, _i, _len, _ref;
  19899. if (cmp == null) {
  19900. cmp = defaultCmp;
  19901. }
  19902. result = array2.slice(0, n3);
  19903. if (!result.length) {
  19904. return result;
  19905. }
  19906. heapify(result, cmp);
  19907. _ref = array2.slice(n3);
  19908. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  19909. elem = _ref[_i];
  19910. heappushpop(result, elem, cmp);
  19911. }
  19912. return result.sort(cmp).reverse();
  19913. };
  19914. nsmallest = function(array2, n3, cmp) {
  19915. var elem, i4, los, result, _i, _j, _len, _ref, _ref1, _results;
  19916. if (cmp == null) {
  19917. cmp = defaultCmp;
  19918. }
  19919. if (n3 * 10 <= array2.length) {
  19920. result = array2.slice(0, n3).sort(cmp);
  19921. if (!result.length) {
  19922. return result;
  19923. }
  19924. los = result[result.length - 1];
  19925. _ref = array2.slice(n3);
  19926. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  19927. elem = _ref[_i];
  19928. if (cmp(elem, los) < 0) {
  19929. insort(result, elem, 0, null, cmp);
  19930. result.pop();
  19931. los = result[result.length - 1];
  19932. }
  19933. }
  19934. return result;
  19935. }
  19936. heapify(array2, cmp);
  19937. _results = [];
  19938. for (i4 = _j = 0, _ref1 = min(n3, array2.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i4 = 0 <= _ref1 ? ++_j : --_j) {
  19939. _results.push(heappop(array2, cmp));
  19940. }
  19941. return _results;
  19942. };
  19943. _siftdown = function(array2, startpos, pos, cmp) {
  19944. var newitem, parent, parentpos;
  19945. if (cmp == null) {
  19946. cmp = defaultCmp;
  19947. }
  19948. newitem = array2[pos];
  19949. while (pos > startpos) {
  19950. parentpos = pos - 1 >> 1;
  19951. parent = array2[parentpos];
  19952. if (cmp(newitem, parent) < 0) {
  19953. array2[pos] = parent;
  19954. pos = parentpos;
  19955. continue;
  19956. }
  19957. break;
  19958. }
  19959. return array2[pos] = newitem;
  19960. };
  19961. _siftup = function(array2, pos, cmp) {
  19962. var childpos, endpos, newitem, rightpos, startpos;
  19963. if (cmp == null) {
  19964. cmp = defaultCmp;
  19965. }
  19966. endpos = array2.length;
  19967. startpos = pos;
  19968. newitem = array2[pos];
  19969. childpos = 2 * pos + 1;
  19970. while (childpos < endpos) {
  19971. rightpos = childpos + 1;
  19972. if (rightpos < endpos && !(cmp(array2[childpos], array2[rightpos]) < 0)) {
  19973. childpos = rightpos;
  19974. }
  19975. array2[pos] = array2[childpos];
  19976. pos = childpos;
  19977. childpos = 2 * pos + 1;
  19978. }
  19979. array2[pos] = newitem;
  19980. return _siftdown(array2, startpos, pos, cmp);
  19981. };
  19982. Heap = function() {
  19983. Heap2.push = heappush;
  19984. Heap2.pop = heappop;
  19985. Heap2.replace = heapreplace;
  19986. Heap2.pushpop = heappushpop;
  19987. Heap2.heapify = heapify;
  19988. Heap2.updateItem = updateItem;
  19989. Heap2.nlargest = nlargest;
  19990. Heap2.nsmallest = nsmallest;
  19991. function Heap2(cmp) {
  19992. this.cmp = cmp != null ? cmp : defaultCmp;
  19993. this.nodes = [];
  19994. }
  19995. Heap2.prototype.push = function(x4) {
  19996. return heappush(this.nodes, x4, this.cmp);
  19997. };
  19998. Heap2.prototype.pop = function() {
  19999. return heappop(this.nodes, this.cmp);
  20000. };
  20001. Heap2.prototype.peek = function() {
  20002. return this.nodes[0];
  20003. };
  20004. Heap2.prototype.contains = function(x4) {
  20005. return this.nodes.indexOf(x4) !== -1;
  20006. };
  20007. Heap2.prototype.replace = function(x4) {
  20008. return heapreplace(this.nodes, x4, this.cmp);
  20009. };
  20010. Heap2.prototype.pushpop = function(x4) {
  20011. return heappushpop(this.nodes, x4, this.cmp);
  20012. };
  20013. Heap2.prototype.heapify = function() {
  20014. return heapify(this.nodes, this.cmp);
  20015. };
  20016. Heap2.prototype.updateItem = function(x4) {
  20017. return updateItem(this.nodes, x4, this.cmp);
  20018. };
  20019. Heap2.prototype.clear = function() {
  20020. return this.nodes = [];
  20021. };
  20022. Heap2.prototype.empty = function() {
  20023. return this.nodes.length === 0;
  20024. };
  20025. Heap2.prototype.size = function() {
  20026. return this.nodes.length;
  20027. };
  20028. Heap2.prototype.clone = function() {
  20029. var heap;
  20030. heap = new Heap2();
  20031. heap.nodes = this.nodes.slice(0);
  20032. return heap;
  20033. };
  20034. Heap2.prototype.toArray = function() {
  20035. return this.nodes.slice(0);
  20036. };
  20037. Heap2.prototype.insert = Heap2.prototype.push;
  20038. Heap2.prototype.top = Heap2.prototype.peek;
  20039. Heap2.prototype.front = Heap2.prototype.peek;
  20040. Heap2.prototype.has = Heap2.prototype.contains;
  20041. Heap2.prototype.copy = Heap2.prototype.clone;
  20042. return Heap2;
  20043. }();
  20044. (function(root, factory) {
  20045. if (typeof define === "function" && define.amd) {
  20046. return define([], factory);
  20047. } else if (typeof exports2 === "object") {
  20048. return module2.exports = factory();
  20049. } else {
  20050. return root.Heap = factory();
  20051. }
  20052. })(this, function() {
  20053. return Heap;
  20054. });
  20055. }).call(exports2);
  20056. }
  20057. });
  20058. // ../node_modules/.pnpm/heap@0.2.7/node_modules/heap/index.js
  20059. var require_heap2 = __commonJS({
  20060. "../node_modules/.pnpm/heap@0.2.7/node_modules/heap/index.js"(exports2, module2) {
  20061. module2.exports = require_heap();
  20062. }
  20063. });
  20064. // ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js
  20065. var require_difflib = __commonJS({
  20066. "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js"(exports2) {
  20067. (function() {
  20068. var Differ, Heap, IS_CHARACTER_JUNK, IS_LINE_JUNK, SequenceMatcher, _any, _arrayCmp, _calculateRatio, _countLeading, _formatRangeContext, _formatRangeUnified, _has, assert, contextDiff, floor, getCloseMatches, max, min, ndiff, restore, unifiedDiff, indexOf = [].indexOf;
  20069. ({ floor, max, min } = Math);
  20070. Heap = require_heap2();
  20071. assert = require("assert");
  20072. _calculateRatio = function(matches, length) {
  20073. if (length) {
  20074. return 2 * matches / length;
  20075. } else {
  20076. return 1;
  20077. }
  20078. };
  20079. _arrayCmp = function(a3, b3) {
  20080. var i4, l3, la, lb, ref;
  20081. [la, lb] = [a3.length, b3.length];
  20082. for (i4 = l3 = 0, ref = min(la, lb); 0 <= ref ? l3 < ref : l3 > ref; i4 = 0 <= ref ? ++l3 : --l3) {
  20083. if (a3[i4] < b3[i4]) {
  20084. return -1;
  20085. }
  20086. if (a3[i4] > b3[i4]) {
  20087. return 1;
  20088. }
  20089. }
  20090. return la - lb;
  20091. };
  20092. _has = function(obj, key) {
  20093. return Object.prototype.hasOwnProperty.call(obj, key);
  20094. };
  20095. _any = function(items) {
  20096. var item, l3, len;
  20097. for (l3 = 0, len = items.length; l3 < len; l3++) {
  20098. item = items[l3];
  20099. if (item) {
  20100. return true;
  20101. }
  20102. }
  20103. return false;
  20104. };
  20105. SequenceMatcher = class SequenceMatcher {
  20106. /*
  20107. SequenceMatcher is a flexible class for comparing pairs of sequences of
  20108. any type, so long as the sequence elements are hashable. The basic
  20109. algorithm predates, and is a little fancier than, an algorithm
  20110. published in the late 1980's by Ratcliff and Obershelp under the
  20111. hyperbolic name "gestalt pattern matching". The basic idea is to find
  20112. the longest contiguous matching subsequence that contains no "junk"
  20113. elements (R-O doesn't address junk). The same idea is then applied
  20114. recursively to the pieces of the sequences to the left and to the right
  20115. of the matching subsequence. This does not yield minimal edit
  20116. sequences, but does tend to yield matches that "look right" to people.
  20117. SequenceMatcher tries to compute a "human-friendly diff" between two
  20118. sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
  20119. longest *contiguous* & junk-free matching subsequence. That's what
  20120. catches peoples' eyes. The Windows(tm) windiff has another interesting
  20121. notion, pairing up elements that appear uniquely in each sequence.
  20122. That, and the method here, appear to yield more intuitive difference
  20123. reports than does diff. This method appears to be the least vulnerable
  20124. to synching up on blocks of "junk lines", though (like blank lines in
  20125. ordinary text files, or maybe "<P>" lines in HTML files). That may be
  20126. because this is the only method of the 3 that has a *concept* of
  20127. "junk" <wink>.
  20128. Example, comparing two strings, and considering blanks to be "junk":
  20129. >>> isjunk = (c) -> c is ' '
  20130. >>> s = new SequenceMatcher(isjunk,
  20131. 'private Thread currentThread;',
  20132. 'private volatile Thread currentThread;')
  20133. .ratio() returns a float in [0, 1], measuring the "similarity" of the
  20134. sequences. As a rule of thumb, a .ratio() value over 0.6 means the
  20135. sequences are close matches:
  20136. >>> s.ratio().toPrecision(3)
  20137. '0.866'
  20138. If you're only interested in where the sequences match,
  20139. .getMatchingBlocks() is handy:
  20140. >>> for [a, b, size] in s.getMatchingBlocks()
  20141. ... console.log("a[#{a}] and b[#{b}] match for #{size} elements");
  20142. a[0] and b[0] match for 8 elements
  20143. a[8] and b[17] match for 21 elements
  20144. a[29] and b[38] match for 0 elements
  20145. Note that the last tuple returned by .get_matching_blocks() is always a
  20146. dummy, (len(a), len(b), 0), and this is the only case in which the last
  20147. tuple element (number of elements matched) is 0.
  20148. If you want to know how to change the first sequence into the second,
  20149. use .get_opcodes():
  20150. >>> for [op, a1, a2, b1, b2] in s.getOpcodes()
  20151. ... console.log "#{op} a[#{a1}:#{a2}] b[#{b1}:#{b2}]"
  20152. equal a[0:8] b[0:8]
  20153. insert a[8:8] b[8:17]
  20154. equal a[8:29] b[17:38]
  20155. See the Differ class for a fancy human-friendly file differencer, which
  20156. uses SequenceMatcher both to compare sequences of lines, and to compare
  20157. sequences of characters within similar (near-matching) lines.
  20158. See also function getCloseMatches() in this module, which shows how
  20159. simple code building on SequenceMatcher can be used to do useful work.
  20160. Timing: Basic R-O is cubic time worst case and quadratic time expected
  20161. case. SequenceMatcher is quadratic time for the worst case and has
  20162. expected-case behavior dependent in a complicated way on how many
  20163. elements the sequences have in common; best case time is linear.
  20164. Methods:
  20165. constructor(isjunk=null, a='', b='')
  20166. Construct a SequenceMatcher.
  20167. setSeqs(a, b)
  20168. Set the two sequences to be compared.
  20169. setSeq1(a)
  20170. Set the first sequence to be compared.
  20171. setSeq2(b)
  20172. Set the second sequence to be compared.
  20173. findLongestMatch(alo, ahi, blo, bhi)
  20174. Find longest matching block in a[alo:ahi] and b[blo:bhi].
  20175. getMatchingBlocks()
  20176. Return list of triples describing matching subsequences.
  20177. getOpcodes()
  20178. Return list of 5-tuples describing how to turn a into b.
  20179. ratio()
  20180. Return a measure of the sequences' similarity (float in [0,1]).
  20181. quickRatio()
  20182. Return an upper bound on .ratio() relatively quickly.
  20183. realQuickRatio()
  20184. Return an upper bound on ratio() very quickly.
  20185. */
  20186. constructor(isjunk1, a3 = "", b3 = "", autojunk = true) {
  20187. this.isjunk = isjunk1;
  20188. this.autojunk = autojunk;
  20189. this.a = this.b = null;
  20190. this.setSeqs(a3, b3);
  20191. }
  20192. setSeqs(a3, b3) {
  20193. this.setSeq1(a3);
  20194. return this.setSeq2(b3);
  20195. }
  20196. setSeq1(a3) {
  20197. if (a3 === this.a) {
  20198. return;
  20199. }
  20200. this.a = a3;
  20201. return this.matchingBlocks = this.opcodes = null;
  20202. }
  20203. setSeq2(b3) {
  20204. if (b3 === this.b) {
  20205. return;
  20206. }
  20207. this.b = b3;
  20208. this.matchingBlocks = this.opcodes = null;
  20209. this.fullbcount = null;
  20210. return this._chainB();
  20211. }
  20212. // For each element x in b, set b2j[x] to a list of the indices in
  20213. // b where x appears; the indices are in increasing order; note that
  20214. // the number of times x appears in b is b2j[x].length ...
  20215. // when @isjunk is defined, junk elements don't show up in this
  20216. // map at all, which stops the central findLongestMatch method
  20217. // from starting any matching block at a junk element ...
  20218. // also creates the fast isbjunk function ...
  20219. // b2j also does not contain entries for "popular" elements, meaning
  20220. // elements that account for more than 1 + 1% of the total elements, and
  20221. // when the sequence is reasonably large (>= 200 elements); this can
  20222. // be viewed as an adaptive notion of semi-junk, and yields an enormous
  20223. // speedup when, e.g., comparing program files with hundreds of
  20224. // instances of "return null;" ...
  20225. // note that this is only called when b changes; so for cross-product
  20226. // kinds of matches, it's best to call setSeq2 once, then setSeq1
  20227. // repeatedly
  20228. _chainB() {
  20229. var b3, b2j, elt, i4, indices, isjunk, junk, l3, len, n3, ntest, popular;
  20230. b3 = this.b;
  20231. this.b2j = b2j = /* @__PURE__ */ new Map();
  20232. for (i4 = l3 = 0, len = b3.length; l3 < len; i4 = ++l3) {
  20233. elt = b3[i4];
  20234. if (!b2j.has(elt)) {
  20235. b2j.set(elt, []);
  20236. }
  20237. indices = b2j.get(elt);
  20238. indices.push(i4);
  20239. }
  20240. junk = /* @__PURE__ */ new Map();
  20241. isjunk = this.isjunk;
  20242. if (isjunk) {
  20243. b2j.forEach(function(idxs, elt2) {
  20244. if (isjunk(elt2)) {
  20245. junk.set(elt2, true);
  20246. return b2j.delete(elt2);
  20247. }
  20248. });
  20249. }
  20250. popular = /* @__PURE__ */ new Map();
  20251. n3 = b3.length;
  20252. if (this.autojunk && n3 >= 200) {
  20253. ntest = floor(n3 / 100) + 1;
  20254. b2j.forEach(function(idxs, elt2) {
  20255. if (idxs.length > ntest) {
  20256. popular.set(elt2, true);
  20257. return b2j.delete(elt2);
  20258. }
  20259. });
  20260. }
  20261. this.isbjunk = function(b4) {
  20262. return junk.has(b4);
  20263. };
  20264. return this.isbpopular = function(b4) {
  20265. return popular.has(b4);
  20266. };
  20267. }
  20268. findLongestMatch(alo, ahi, blo, bhi) {
  20269. var a3, b3, b2j, besti, bestj, bestsize, i4, isbjunk, j3, j2len, jlist, k3, l3, len, m4, newj2len, ref, ref1;
  20270. [a3, b3, b2j, isbjunk] = [this.a, this.b, this.b2j, this.isbjunk];
  20271. [besti, bestj, bestsize] = [alo, blo, 0];
  20272. j2len = {};
  20273. for (i4 = l3 = ref = alo, ref1 = ahi; ref <= ref1 ? l3 < ref1 : l3 > ref1; i4 = ref <= ref1 ? ++l3 : --l3) {
  20274. newj2len = {};
  20275. jlist = [];
  20276. if (b2j.has(a3[i4])) {
  20277. jlist = b2j.get(a3[i4]);
  20278. }
  20279. for (m4 = 0, len = jlist.length; m4 < len; m4++) {
  20280. j3 = jlist[m4];
  20281. if (j3 < blo) {
  20282. continue;
  20283. }
  20284. if (j3 >= bhi) {
  20285. break;
  20286. }
  20287. k3 = newj2len[j3] = (j2len[j3 - 1] || 0) + 1;
  20288. if (k3 > bestsize) {
  20289. [besti, bestj, bestsize] = [i4 - k3 + 1, j3 - k3 + 1, k3];
  20290. }
  20291. }
  20292. j2len = newj2len;
  20293. }
  20294. while (besti > alo && bestj > blo && !isbjunk(b3[bestj - 1]) && a3[besti - 1] === b3[bestj - 1]) {
  20295. [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
  20296. }
  20297. while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b3[bestj + bestsize]) && a3[besti + bestsize] === b3[bestj + bestsize]) {
  20298. bestsize++;
  20299. }
  20300. while (besti > alo && bestj > blo && isbjunk(b3[bestj - 1]) && a3[besti - 1] === b3[bestj - 1]) {
  20301. [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
  20302. }
  20303. while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b3[bestj + bestsize]) && a3[besti + bestsize] === b3[bestj + bestsize]) {
  20304. bestsize++;
  20305. }
  20306. return [besti, bestj, bestsize];
  20307. }
  20308. getMatchingBlocks() {
  20309. var ahi, alo, bhi, blo, i4, i1, i22, j3, j1, j22, k3, k1, k22, l3, la, lb, len, matchingBlocks, nonAdjacent, queue, x4;
  20310. if (this.matchingBlocks) {
  20311. return this.matchingBlocks;
  20312. }
  20313. [la, lb] = [this.a.length, this.b.length];
  20314. queue = [[0, la, 0, lb]];
  20315. matchingBlocks = [];
  20316. while (queue.length) {
  20317. [alo, ahi, blo, bhi] = queue.pop();
  20318. [i4, j3, k3] = x4 = this.findLongestMatch(alo, ahi, blo, bhi);
  20319. if (k3) {
  20320. matchingBlocks.push(x4);
  20321. if (alo < i4 && blo < j3) {
  20322. queue.push([alo, i4, blo, j3]);
  20323. }
  20324. if (i4 + k3 < ahi && j3 + k3 < bhi) {
  20325. queue.push([i4 + k3, ahi, j3 + k3, bhi]);
  20326. }
  20327. }
  20328. }
  20329. matchingBlocks.sort(_arrayCmp);
  20330. i1 = j1 = k1 = 0;
  20331. nonAdjacent = [];
  20332. for (l3 = 0, len = matchingBlocks.length; l3 < len; l3++) {
  20333. [i22, j22, k22] = matchingBlocks[l3];
  20334. if (i1 + k1 === i22 && j1 + k1 === j22) {
  20335. k1 += k22;
  20336. } else {
  20337. if (k1) {
  20338. nonAdjacent.push([i1, j1, k1]);
  20339. }
  20340. [i1, j1, k1] = [i22, j22, k22];
  20341. }
  20342. }
  20343. if (k1) {
  20344. nonAdjacent.push([i1, j1, k1]);
  20345. }
  20346. nonAdjacent.push([la, lb, 0]);
  20347. return this.matchingBlocks = nonAdjacent;
  20348. }
  20349. getOpcodes() {
  20350. var ai, answer, bj, i4, j3, l3, len, ref, size, tag;
  20351. if (this.opcodes) {
  20352. return this.opcodes;
  20353. }
  20354. i4 = j3 = 0;
  20355. this.opcodes = answer = [];
  20356. ref = this.getMatchingBlocks();
  20357. for (l3 = 0, len = ref.length; l3 < len; l3++) {
  20358. [ai, bj, size] = ref[l3];
  20359. tag = "";
  20360. if (i4 < ai && j3 < bj) {
  20361. tag = "replace";
  20362. } else if (i4 < ai) {
  20363. tag = "delete";
  20364. } else if (j3 < bj) {
  20365. tag = "insert";
  20366. }
  20367. if (tag) {
  20368. answer.push([tag, i4, ai, j3, bj]);
  20369. }
  20370. [i4, j3] = [ai + size, bj + size];
  20371. if (size) {
  20372. answer.push(["equal", ai, i4, bj, j3]);
  20373. }
  20374. }
  20375. return answer;
  20376. }
  20377. getGroupedOpcodes(n3 = 3) {
  20378. var codes, group, groups, i1, i22, j1, j22, l3, len, nn, tag;
  20379. codes = this.getOpcodes();
  20380. if (!codes.length) {
  20381. codes = [["equal", 0, 1, 0, 1]];
  20382. }
  20383. if (codes[0][0] === "equal") {
  20384. [tag, i1, i22, j1, j22] = codes[0];
  20385. codes[0] = [tag, max(i1, i22 - n3), i22, max(j1, j22 - n3), j22];
  20386. }
  20387. if (codes[codes.length - 1][0] === "equal") {
  20388. [tag, i1, i22, j1, j22] = codes[codes.length - 1];
  20389. codes[codes.length - 1] = [tag, i1, min(i22, i1 + n3), j1, min(j22, j1 + n3)];
  20390. }
  20391. nn = n3 + n3;
  20392. groups = [];
  20393. group = [];
  20394. for (l3 = 0, len = codes.length; l3 < len; l3++) {
  20395. [tag, i1, i22, j1, j22] = codes[l3];
  20396. if (tag === "equal" && i22 - i1 > nn) {
  20397. group.push([tag, i1, min(i22, i1 + n3), j1, min(j22, j1 + n3)]);
  20398. groups.push(group);
  20399. group = [];
  20400. [i1, j1] = [max(i1, i22 - n3), max(j1, j22 - n3)];
  20401. }
  20402. group.push([tag, i1, i22, j1, j22]);
  20403. }
  20404. if (group.length && !(group.length === 1 && group[0][0] === "equal")) {
  20405. groups.push(group);
  20406. }
  20407. return groups;
  20408. }
  20409. ratio() {
  20410. var l3, len, match2, matches, ref;
  20411. matches = 0;
  20412. ref = this.getMatchingBlocks();
  20413. for (l3 = 0, len = ref.length; l3 < len; l3++) {
  20414. match2 = ref[l3];
  20415. matches += match2[2];
  20416. }
  20417. return _calculateRatio(matches, this.a.length + this.b.length);
  20418. }
  20419. quickRatio() {
  20420. var avail, elt, fullbcount, l3, len, len1, m4, matches, numb, ref, ref1;
  20421. if (!this.fullbcount) {
  20422. this.fullbcount = fullbcount = {};
  20423. ref = this.b;
  20424. for (l3 = 0, len = ref.length; l3 < len; l3++) {
  20425. elt = ref[l3];
  20426. fullbcount[elt] = (fullbcount[elt] || 0) + 1;
  20427. }
  20428. }
  20429. fullbcount = this.fullbcount;
  20430. avail = {};
  20431. matches = 0;
  20432. ref1 = this.a;
  20433. for (m4 = 0, len1 = ref1.length; m4 < len1; m4++) {
  20434. elt = ref1[m4];
  20435. if (_has(avail, elt)) {
  20436. numb = avail[elt];
  20437. } else {
  20438. numb = fullbcount[elt] || 0;
  20439. }
  20440. avail[elt] = numb - 1;
  20441. if (numb > 0) {
  20442. matches++;
  20443. }
  20444. }
  20445. return _calculateRatio(matches, this.a.length + this.b.length);
  20446. }
  20447. realQuickRatio() {
  20448. var la, lb;
  20449. [la, lb] = [this.a.length, this.b.length];
  20450. return _calculateRatio(min(la, lb), la + lb);
  20451. }
  20452. };
  20453. getCloseMatches = function(word, possibilities, n3 = 3, cutoff = 0.6) {
  20454. var l3, len, len1, m4, result, results, s4, score, x4;
  20455. if (!(n3 > 0)) {
  20456. throw new Error(`n must be > 0: (${n3})`);
  20457. }
  20458. if (!(0 <= cutoff && cutoff <= 1)) {
  20459. throw new Error(`cutoff must be in [0.0, 1.0]: (${cutoff})`);
  20460. }
  20461. result = [];
  20462. s4 = new SequenceMatcher();
  20463. s4.setSeq2(word);
  20464. for (l3 = 0, len = possibilities.length; l3 < len; l3++) {
  20465. x4 = possibilities[l3];
  20466. s4.setSeq1(x4);
  20467. if (s4.realQuickRatio() >= cutoff && s4.quickRatio() >= cutoff && s4.ratio() >= cutoff) {
  20468. result.push([s4.ratio(), x4]);
  20469. }
  20470. }
  20471. result = Heap.nlargest(result, n3, _arrayCmp);
  20472. results = [];
  20473. for (m4 = 0, len1 = result.length; m4 < len1; m4++) {
  20474. [score, x4] = result[m4];
  20475. results.push(x4);
  20476. }
  20477. return results;
  20478. };
  20479. _countLeading = function(line, ch) {
  20480. var i4, n3;
  20481. [i4, n3] = [0, line.length];
  20482. while (i4 < n3 && line[i4] === ch) {
  20483. i4++;
  20484. }
  20485. return i4;
  20486. };
  20487. Differ = class Differ {
  20488. /*
  20489. Differ is a class for comparing sequences of lines of text, and
  20490. producing human-readable differences or deltas. Differ uses
  20491. SequenceMatcher both to compare sequences of lines, and to compare
  20492. sequences of characters within similar (near-matching) lines.
  20493. Each line of a Differ delta begins with a two-letter code:
  20494. '- ' line unique to sequence 1
  20495. '+ ' line unique to sequence 2
  20496. ' ' line common to both sequences
  20497. '? ' line not present in either input sequence
  20498. Lines beginning with '? ' attempt to guide the eye to intraline
  20499. differences, and were not present in either input sequence. These lines
  20500. can be confusing if the sequences contain tab characters.
  20501. Note that Differ makes no claim to produce a *minimal* diff. To the
  20502. contrary, minimal diffs are often counter-intuitive, because they synch
  20503. up anywhere possible, sometimes accidental matches 100 pages apart.
  20504. Restricting synch points to contiguous matches preserves some notion of
  20505. locality, at the occasional cost of producing a longer diff.
  20506. Example: Comparing two texts.
  20507. >>> text1 = ['1. Beautiful is better than ugly.\n',
  20508. ... '2. Explicit is better than implicit.\n',
  20509. ... '3. Simple is better than complex.\n',
  20510. ... '4. Complex is better than complicated.\n']
  20511. >>> text1.length
  20512. 4
  20513. >>> text2 = ['1. Beautiful is better than ugly.\n',
  20514. ... '3. Simple is better than complex.\n',
  20515. ... '4. Complicated is better than complex.\n',
  20516. ... '5. Flat is better than nested.\n']
  20517. Next we instantiate a Differ object:
  20518. >>> d = new Differ()
  20519. Note that when instantiating a Differ object we may pass functions to
  20520. filter out line and character 'junk'.
  20521. Finally, we compare the two:
  20522. >>> result = d.compare(text1, text2)
  20523. [ ' 1. Beautiful is better than ugly.\n',
  20524. '- 2. Explicit is better than implicit.\n',
  20525. '- 3. Simple is better than complex.\n',
  20526. '+ 3. Simple is better than complex.\n',
  20527. '? ++\n',
  20528. '- 4. Complex is better than complicated.\n',
  20529. '? ^ ---- ^\n',
  20530. '+ 4. Complicated is better than complex.\n',
  20531. '? ++++ ^ ^\n',
  20532. '+ 5. Flat is better than nested.\n' ]
  20533. Methods:
  20534. constructor(linejunk=null, charjunk=null)
  20535. Construct a text differencer, with optional filters.
  20536. compare(a, b)
  20537. Compare two sequences of lines; generate the resulting delta.
  20538. */
  20539. constructor(linejunk1, charjunk1) {
  20540. this.linejunk = linejunk1;
  20541. this.charjunk = charjunk1;
  20542. }
  20543. /*
  20544. Construct a text differencer, with optional filters.
  20545. The two optional keyword parameters are for filter functions:
  20546. - `linejunk`: A function that should accept a single string argument,
  20547. and return true iff the string is junk. The module-level function
  20548. `IS_LINE_JUNK` may be used to filter out lines without visible
  20549. characters, except for at most one splat ('#'). It is recommended
  20550. to leave linejunk null.
  20551. - `charjunk`: A function that should accept a string of length 1. The
  20552. module-level function `IS_CHARACTER_JUNK` may be used to filter out
  20553. whitespace characters (a blank or tab; **note**: bad idea to include
  20554. newline in this!). Use of IS_CHARACTER_JUNK is recommended.
  20555. */
  20556. compare(a3, b3) {
  20557. var ahi, alo, bhi, blo, cruncher, g3, l3, len, len1, line, lines, m4, ref, tag;
  20558. cruncher = new SequenceMatcher(this.linejunk, a3, b3);
  20559. lines = [];
  20560. ref = cruncher.getOpcodes();
  20561. for (l3 = 0, len = ref.length; l3 < len; l3++) {
  20562. [tag, alo, ahi, blo, bhi] = ref[l3];
  20563. switch (tag) {
  20564. case "replace":
  20565. g3 = this._fancyReplace(a3, alo, ahi, b3, blo, bhi);
  20566. break;
  20567. case "delete":
  20568. g3 = this._dump("-", a3, alo, ahi);
  20569. break;
  20570. case "insert":
  20571. g3 = this._dump("+", b3, blo, bhi);
  20572. break;
  20573. case "equal":
  20574. g3 = this._dump(" ", a3, alo, ahi);
  20575. break;
  20576. default:
  20577. throw new Error(`unknow tag (${tag})`);
  20578. }
  20579. for (m4 = 0, len1 = g3.length; m4 < len1; m4++) {
  20580. line = g3[m4];
  20581. lines.push(line);
  20582. }
  20583. }
  20584. return lines;
  20585. }
  20586. _dump(tag, x4, lo, hi) {
  20587. var i4, l3, ref, ref1, results;
  20588. results = [];
  20589. for (i4 = l3 = ref = lo, ref1 = hi; ref <= ref1 ? l3 < ref1 : l3 > ref1; i4 = ref <= ref1 ? ++l3 : --l3) {
  20590. results.push(`${tag} ${x4[i4]}`);
  20591. }
  20592. return results;
  20593. }
  20594. _plainReplace(a3, alo, ahi, b3, blo, bhi) {
  20595. var first, g3, l3, len, len1, line, lines, m4, ref, second;
  20596. assert(alo < ahi && blo < bhi);
  20597. if (bhi - blo < ahi - alo) {
  20598. first = this._dump("+", b3, blo, bhi);
  20599. second = this._dump("-", a3, alo, ahi);
  20600. } else {
  20601. first = this._dump("-", a3, alo, ahi);
  20602. second = this._dump("+", b3, blo, bhi);
  20603. }
  20604. lines = [];
  20605. ref = [first, second];
  20606. for (l3 = 0, len = ref.length; l3 < len; l3++) {
  20607. g3 = ref[l3];
  20608. for (m4 = 0, len1 = g3.length; m4 < len1; m4++) {
  20609. line = g3[m4];
  20610. lines.push(line);
  20611. }
  20612. }
  20613. return lines;
  20614. }
  20615. _fancyReplace(a3, alo, ahi, b3, blo, bhi) {
  20616. var aelt, ai, ai1, ai2, atags, belt, bestRatio, besti, bestj, bj, bj1, bj2, btags, cruncher, cutoff, eqi, eqj, i4, j3, l3, la, lb, len, len1, len2, len3, len4, line, lines, m4, o3, p3, q3, r4, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, t4, tag;
  20617. [bestRatio, cutoff] = [0.74, 0.75];
  20618. cruncher = new SequenceMatcher(this.charjunk);
  20619. [eqi, eqj] = [
  20620. null,
  20621. null
  20622. // 1st indices of equal lines (if any)
  20623. ];
  20624. lines = [];
  20625. for (j3 = l3 = ref = blo, ref1 = bhi; ref <= ref1 ? l3 < ref1 : l3 > ref1; j3 = ref <= ref1 ? ++l3 : --l3) {
  20626. bj = b3[j3];
  20627. cruncher.setSeq2(bj);
  20628. for (i4 = m4 = ref2 = alo, ref3 = ahi; ref2 <= ref3 ? m4 < ref3 : m4 > ref3; i4 = ref2 <= ref3 ? ++m4 : --m4) {
  20629. ai = a3[i4];
  20630. if (ai === bj) {
  20631. if (eqi === null) {
  20632. [eqi, eqj] = [i4, j3];
  20633. }
  20634. continue;
  20635. }
  20636. cruncher.setSeq1(ai);
  20637. if (cruncher.realQuickRatio() > bestRatio && cruncher.quickRatio() > bestRatio && cruncher.ratio() > bestRatio) {
  20638. [bestRatio, besti, bestj] = [cruncher.ratio(), i4, j3];
  20639. }
  20640. }
  20641. }
  20642. if (bestRatio < cutoff) {
  20643. if (eqi === null) {
  20644. ref4 = this._plainReplace(a3, alo, ahi, b3, blo, bhi);
  20645. for (o3 = 0, len = ref4.length; o3 < len; o3++) {
  20646. line = ref4[o3];
  20647. lines.push(line);
  20648. }
  20649. return lines;
  20650. }
  20651. [besti, bestj, bestRatio] = [eqi, eqj, 1];
  20652. } else {
  20653. eqi = null;
  20654. }
  20655. ref5 = this._fancyHelper(a3, alo, besti, b3, blo, bestj);
  20656. for (p3 = 0, len1 = ref5.length; p3 < len1; p3++) {
  20657. line = ref5[p3];
  20658. lines.push(line);
  20659. }
  20660. [aelt, belt] = [a3[besti], b3[bestj]];
  20661. if (eqi === null) {
  20662. atags = btags = "";
  20663. cruncher.setSeqs(aelt, belt);
  20664. ref6 = cruncher.getOpcodes();
  20665. for (q3 = 0, len2 = ref6.length; q3 < len2; q3++) {
  20666. [tag, ai1, ai2, bj1, bj2] = ref6[q3];
  20667. [la, lb] = [ai2 - ai1, bj2 - bj1];
  20668. switch (tag) {
  20669. case "replace":
  20670. atags += Array(la + 1).join("^");
  20671. btags += Array(lb + 1).join("^");
  20672. break;
  20673. case "delete":
  20674. atags += Array(la + 1).join("-");
  20675. break;
  20676. case "insert":
  20677. btags += Array(lb + 1).join("+");
  20678. break;
  20679. case "equal":
  20680. atags += Array(la + 1).join(" ");
  20681. btags += Array(lb + 1).join(" ");
  20682. break;
  20683. default:
  20684. throw new Error(`unknow tag (${tag})`);
  20685. }
  20686. }
  20687. ref7 = this._qformat(aelt, belt, atags, btags);
  20688. for (r4 = 0, len3 = ref7.length; r4 < len3; r4++) {
  20689. line = ref7[r4];
  20690. lines.push(line);
  20691. }
  20692. } else {
  20693. lines.push(" " + aelt);
  20694. }
  20695. ref8 = this._fancyHelper(a3, besti + 1, ahi, b3, bestj + 1, bhi);
  20696. for (t4 = 0, len4 = ref8.length; t4 < len4; t4++) {
  20697. line = ref8[t4];
  20698. lines.push(line);
  20699. }
  20700. return lines;
  20701. }
  20702. _fancyHelper(a3, alo, ahi, b3, blo, bhi) {
  20703. var g3;
  20704. g3 = [];
  20705. if (alo < ahi) {
  20706. if (blo < bhi) {
  20707. g3 = this._fancyReplace(a3, alo, ahi, b3, blo, bhi);
  20708. } else {
  20709. g3 = this._dump("-", a3, alo, ahi);
  20710. }
  20711. } else if (blo < bhi) {
  20712. g3 = this._dump("+", b3, blo, bhi);
  20713. }
  20714. return g3;
  20715. }
  20716. _qformat(aline, bline, atags, btags) {
  20717. var common, lines;
  20718. lines = [];
  20719. common = min(_countLeading(aline, " "), _countLeading(bline, " "));
  20720. common = min(common, _countLeading(atags.slice(0, common), " "));
  20721. common = min(common, _countLeading(btags.slice(0, common), " "));
  20722. atags = atags.slice(common).replace(/\s+$/, "");
  20723. btags = btags.slice(common).replace(/\s+$/, "");
  20724. lines.push("- " + aline);
  20725. if (atags.length) {
  20726. lines.push(`? ${Array(common + 1).join(" ")}${atags}
  20727. `);
  20728. }
  20729. lines.push("+ " + bline);
  20730. if (btags.length) {
  20731. lines.push(`? ${Array(common + 1).join(" ")}${btags}
  20732. `);
  20733. }
  20734. return lines;
  20735. }
  20736. };
  20737. IS_LINE_JUNK = function(line, pat = /^\s*#?\s*$/) {
  20738. return pat.test(line);
  20739. };
  20740. IS_CHARACTER_JUNK = function(ch, ws = " ") {
  20741. return indexOf.call(ws, ch) >= 0;
  20742. };
  20743. _formatRangeUnified = function(start, stop) {
  20744. var beginning, length;
  20745. beginning = start + 1;
  20746. length = stop - start;
  20747. if (length === 1) {
  20748. return `${beginning}`;
  20749. }
  20750. if (!length) {
  20751. beginning--;
  20752. }
  20753. return `${beginning},${length}`;
  20754. };
  20755. unifiedDiff = function(a3, b3, { fromfile, tofile, fromfiledate, tofiledate, n: n3, lineterm } = {}) {
  20756. var file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l3, last, len, len1, len2, len3, len4, line, lines, m4, o3, p3, q3, ref, ref1, ref2, ref3, started, tag, todate;
  20757. if (fromfile == null) {
  20758. fromfile = "";
  20759. }
  20760. if (tofile == null) {
  20761. tofile = "";
  20762. }
  20763. if (fromfiledate == null) {
  20764. fromfiledate = "";
  20765. }
  20766. if (tofiledate == null) {
  20767. tofiledate = "";
  20768. }
  20769. if (n3 == null) {
  20770. n3 = 3;
  20771. }
  20772. if (lineterm == null) {
  20773. lineterm = "\n";
  20774. }
  20775. lines = [];
  20776. started = false;
  20777. ref = new SequenceMatcher(null, a3, b3).getGroupedOpcodes();
  20778. for (l3 = 0, len = ref.length; l3 < len; l3++) {
  20779. group = ref[l3];
  20780. if (!started) {
  20781. started = true;
  20782. fromdate = fromfiledate ? ` ${fromfiledate}` : "";
  20783. todate = tofiledate ? ` ${tofiledate}` : "";
  20784. lines.push(`--- ${fromfile}${fromdate}${lineterm}`);
  20785. lines.push(`+++ ${tofile}${todate}${lineterm}`);
  20786. }
  20787. [first, last] = [group[0], group[group.length - 1]];
  20788. file1Range = _formatRangeUnified(first[1], last[2]);
  20789. file2Range = _formatRangeUnified(first[3], last[4]);
  20790. lines.push(`@@ -${file1Range} +${file2Range} @@${lineterm}`);
  20791. for (m4 = 0, len1 = group.length; m4 < len1; m4++) {
  20792. [tag, i1, i22, j1, j22] = group[m4];
  20793. if (tag === "equal") {
  20794. ref1 = a3.slice(i1, i22);
  20795. for (o3 = 0, len2 = ref1.length; o3 < len2; o3++) {
  20796. line = ref1[o3];
  20797. lines.push(" " + line);
  20798. }
  20799. continue;
  20800. }
  20801. if (tag === "replace" || tag === "delete") {
  20802. ref2 = a3.slice(i1, i22);
  20803. for (p3 = 0, len3 = ref2.length; p3 < len3; p3++) {
  20804. line = ref2[p3];
  20805. lines.push("-" + line);
  20806. }
  20807. }
  20808. if (tag === "replace" || tag === "insert") {
  20809. ref3 = b3.slice(j1, j22);
  20810. for (q3 = 0, len4 = ref3.length; q3 < len4; q3++) {
  20811. line = ref3[q3];
  20812. lines.push("+" + line);
  20813. }
  20814. }
  20815. }
  20816. }
  20817. return lines;
  20818. };
  20819. _formatRangeContext = function(start, stop) {
  20820. var beginning, length;
  20821. beginning = start + 1;
  20822. length = stop - start;
  20823. if (!length) {
  20824. beginning--;
  20825. }
  20826. if (length <= 1) {
  20827. return `${beginning}`;
  20828. }
  20829. return `${beginning},${beginning + length - 1}`;
  20830. };
  20831. contextDiff = function(a3, b3, { fromfile, tofile, fromfiledate, tofiledate, n: n3, lineterm } = {}) {
  20832. var _3, file1Range, file2Range, first, fromdate, group, i1, i22, j1, j22, l3, last, len, len1, len2, len3, len4, line, lines, m4, o3, p3, prefix2, q3, ref, ref1, ref2, started, tag, todate;
  20833. if (fromfile == null) {
  20834. fromfile = "";
  20835. }
  20836. if (tofile == null) {
  20837. tofile = "";
  20838. }
  20839. if (fromfiledate == null) {
  20840. fromfiledate = "";
  20841. }
  20842. if (tofiledate == null) {
  20843. tofiledate = "";
  20844. }
  20845. if (n3 == null) {
  20846. n3 = 3;
  20847. }
  20848. if (lineterm == null) {
  20849. lineterm = "\n";
  20850. }
  20851. prefix2 = {
  20852. insert: "+ ",
  20853. delete: "- ",
  20854. replace: "! ",
  20855. equal: " "
  20856. };
  20857. started = false;
  20858. lines = [];
  20859. ref = new SequenceMatcher(null, a3, b3).getGroupedOpcodes();
  20860. for (l3 = 0, len = ref.length; l3 < len; l3++) {
  20861. group = ref[l3];
  20862. if (!started) {
  20863. started = true;
  20864. fromdate = fromfiledate ? ` ${fromfiledate}` : "";
  20865. todate = tofiledate ? ` ${tofiledate}` : "";
  20866. lines.push(`*** ${fromfile}${fromdate}${lineterm}`);
  20867. lines.push(`--- ${tofile}${todate}${lineterm}`);
  20868. [first, last] = [group[0], group[group.length - 1]];
  20869. lines.push("***************" + lineterm);
  20870. file1Range = _formatRangeContext(first[1], last[2]);
  20871. lines.push(`*** ${file1Range} ****${lineterm}`);
  20872. if (_any(function() {
  20873. var len12, m5, results;
  20874. results = [];
  20875. for (m5 = 0, len12 = group.length; m5 < len12; m5++) {
  20876. [tag, _3, _3, _3, _3] = group[m5];
  20877. results.push(tag === "replace" || tag === "delete");
  20878. }
  20879. return results;
  20880. }())) {
  20881. for (m4 = 0, len1 = group.length; m4 < len1; m4++) {
  20882. [tag, i1, i22, _3, _3] = group[m4];
  20883. if (tag !== "insert") {
  20884. ref1 = a3.slice(i1, i22);
  20885. for (o3 = 0, len2 = ref1.length; o3 < len2; o3++) {
  20886. line = ref1[o3];
  20887. lines.push(prefix2[tag] + line);
  20888. }
  20889. }
  20890. }
  20891. }
  20892. file2Range = _formatRangeContext(first[3], last[4]);
  20893. lines.push(`--- ${file2Range} ----${lineterm}`);
  20894. if (_any(function() {
  20895. var len32, p4, results;
  20896. results = [];
  20897. for (p4 = 0, len32 = group.length; p4 < len32; p4++) {
  20898. [tag, _3, _3, _3, _3] = group[p4];
  20899. results.push(tag === "replace" || tag === "insert");
  20900. }
  20901. return results;
  20902. }())) {
  20903. for (p3 = 0, len3 = group.length; p3 < len3; p3++) {
  20904. [tag, _3, _3, j1, j22] = group[p3];
  20905. if (tag !== "delete") {
  20906. ref2 = b3.slice(j1, j22);
  20907. for (q3 = 0, len4 = ref2.length; q3 < len4; q3++) {
  20908. line = ref2[q3];
  20909. lines.push(prefix2[tag] + line);
  20910. }
  20911. }
  20912. }
  20913. }
  20914. }
  20915. }
  20916. return lines;
  20917. };
  20918. ndiff = function(a3, b3, linejunk, charjunk = IS_CHARACTER_JUNK) {
  20919. return new Differ(linejunk, charjunk).compare(a3, b3);
  20920. };
  20921. restore = function(delta, which) {
  20922. var l3, len, line, lines, prefixes2, ref, tag;
  20923. tag = {
  20924. 1: "- ",
  20925. 2: "+ "
  20926. }[which];
  20927. if (!tag) {
  20928. throw new Error(`unknow delta choice (must be 1 or 2): ${which}`);
  20929. }
  20930. prefixes2 = [" ", tag];
  20931. lines = [];
  20932. for (l3 = 0, len = delta.length; l3 < len; l3++) {
  20933. line = delta[l3];
  20934. if (ref = line.slice(0, 2), indexOf.call(prefixes2, ref) >= 0) {
  20935. lines.push(line.slice(2));
  20936. }
  20937. }
  20938. return lines;
  20939. };
  20940. exports2._arrayCmp = _arrayCmp;
  20941. exports2.SequenceMatcher = SequenceMatcher;
  20942. exports2.getCloseMatches = getCloseMatches;
  20943. exports2._countLeading = _countLeading;
  20944. exports2.Differ = Differ;
  20945. exports2.IS_LINE_JUNK = IS_LINE_JUNK;
  20946. exports2.IS_CHARACTER_JUNK = IS_CHARACTER_JUNK;
  20947. exports2._formatRangeUnified = _formatRangeUnified;
  20948. exports2.unifiedDiff = unifiedDiff;
  20949. exports2._formatRangeContext = _formatRangeContext;
  20950. exports2.contextDiff = contextDiff;
  20951. exports2.ndiff = ndiff;
  20952. exports2.restore = restore;
  20953. }).call(exports2);
  20954. }
  20955. });
  20956. // ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js
  20957. var require_difflib2 = __commonJS({
  20958. "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js"(exports2, module2) {
  20959. module2.exports = require_difflib();
  20960. }
  20961. });
  20962. // ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js
  20963. var require_util = __commonJS({
  20964. "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js"(exports2, module2) {
  20965. var extendedTypeOf = function(obj) {
  20966. const result = typeof obj;
  20967. if (obj == null) {
  20968. return "null";
  20969. } else if (result === "object" && obj.constructor === Array) {
  20970. return "array";
  20971. } else if (result === "object" && obj instanceof Date) {
  20972. return "date";
  20973. } else {
  20974. return result;
  20975. }
  20976. };
  20977. var roundObj = function(data, precision) {
  20978. const type = typeof data;
  20979. if (type === "array") {
  20980. return data.map((x4) => roundObj(x4, precision));
  20981. } else if (type === "object") {
  20982. for (const key in data) {
  20983. data[key] = roundObj(data[key], precision);
  20984. }
  20985. return data;
  20986. } else if (type === "number" && Number.isFinite(data) && !Number.isInteger(data)) {
  20987. return +data.toFixed(precision);
  20988. } else {
  20989. return data;
  20990. }
  20991. };
  20992. module2.exports = { extendedTypeOf, roundObj };
  20993. }
  20994. });
  20995. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/styles.js
  20996. var require_styles = __commonJS({
  20997. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/styles.js"(exports2, module2) {
  20998. var styles3 = {};
  20999. module2["exports"] = styles3;
  21000. var codes = {
  21001. reset: [0, 0],
  21002. bold: [1, 22],
  21003. dim: [2, 22],
  21004. italic: [3, 23],
  21005. underline: [4, 24],
  21006. inverse: [7, 27],
  21007. hidden: [8, 28],
  21008. strikethrough: [9, 29],
  21009. black: [30, 39],
  21010. red: [31, 39],
  21011. green: [32, 39],
  21012. yellow: [33, 39],
  21013. blue: [34, 39],
  21014. magenta: [35, 39],
  21015. cyan: [36, 39],
  21016. white: [37, 39],
  21017. gray: [90, 39],
  21018. grey: [90, 39],
  21019. brightRed: [91, 39],
  21020. brightGreen: [92, 39],
  21021. brightYellow: [93, 39],
  21022. brightBlue: [94, 39],
  21023. brightMagenta: [95, 39],
  21024. brightCyan: [96, 39],
  21025. brightWhite: [97, 39],
  21026. bgBlack: [40, 49],
  21027. bgRed: [41, 49],
  21028. bgGreen: [42, 49],
  21029. bgYellow: [43, 49],
  21030. bgBlue: [44, 49],
  21031. bgMagenta: [45, 49],
  21032. bgCyan: [46, 49],
  21033. bgWhite: [47, 49],
  21034. bgGray: [100, 49],
  21035. bgGrey: [100, 49],
  21036. bgBrightRed: [101, 49],
  21037. bgBrightGreen: [102, 49],
  21038. bgBrightYellow: [103, 49],
  21039. bgBrightBlue: [104, 49],
  21040. bgBrightMagenta: [105, 49],
  21041. bgBrightCyan: [106, 49],
  21042. bgBrightWhite: [107, 49],
  21043. // legacy styles for colors pre v1.0.0
  21044. blackBG: [40, 49],
  21045. redBG: [41, 49],
  21046. greenBG: [42, 49],
  21047. yellowBG: [43, 49],
  21048. blueBG: [44, 49],
  21049. magentaBG: [45, 49],
  21050. cyanBG: [46, 49],
  21051. whiteBG: [47, 49]
  21052. };
  21053. Object.keys(codes).forEach(function(key) {
  21054. var val2 = codes[key];
  21055. var style = styles3[key] = [];
  21056. style.open = "\x1B[" + val2[0] + "m";
  21057. style.close = "\x1B[" + val2[1] + "m";
  21058. });
  21059. }
  21060. });
  21061. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js
  21062. var require_has_flag = __commonJS({
  21063. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js"(exports2, module2) {
  21064. "use strict";
  21065. module2.exports = function(flag, argv) {
  21066. argv = argv || process.argv;
  21067. var terminatorPos = argv.indexOf("--");
  21068. var prefix2 = /^-{1,2}/.test(flag) ? "" : "--";
  21069. var pos = argv.indexOf(prefix2 + flag);
  21070. return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
  21071. };
  21072. }
  21073. });
  21074. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js
  21075. var require_supports_colors = __commonJS({
  21076. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js"(exports2, module2) {
  21077. "use strict";
  21078. var os3 = require("os");
  21079. var hasFlag2 = require_has_flag();
  21080. var env3 = process.env;
  21081. var forceColor = void 0;
  21082. if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false")) {
  21083. forceColor = false;
  21084. } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
  21085. forceColor = true;
  21086. }
  21087. if ("FORCE_COLOR" in env3) {
  21088. forceColor = env3.FORCE_COLOR.length === 0 || parseInt(env3.FORCE_COLOR, 10) !== 0;
  21089. }
  21090. function translateLevel2(level) {
  21091. if (level === 0) {
  21092. return false;
  21093. }
  21094. return {
  21095. level,
  21096. hasBasic: true,
  21097. has256: level >= 2,
  21098. has16m: level >= 3
  21099. };
  21100. }
  21101. function supportsColor2(stream) {
  21102. if (forceColor === false) {
  21103. return 0;
  21104. }
  21105. if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
  21106. return 3;
  21107. }
  21108. if (hasFlag2("color=256")) {
  21109. return 2;
  21110. }
  21111. if (stream && !stream.isTTY && forceColor !== true) {
  21112. return 0;
  21113. }
  21114. var min = forceColor ? 1 : 0;
  21115. if (process.platform === "win32") {
  21116. var osRelease = os3.release().split(".");
  21117. if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
  21118. return Number(osRelease[2]) >= 14931 ? 3 : 2;
  21119. }
  21120. return 1;
  21121. }
  21122. if ("CI" in env3) {
  21123. if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
  21124. return sign in env3;
  21125. }) || env3.CI_NAME === "codeship") {
  21126. return 1;
  21127. }
  21128. return min;
  21129. }
  21130. if ("TEAMCITY_VERSION" in env3) {
  21131. return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env3.TEAMCITY_VERSION) ? 1 : 0;
  21132. }
  21133. if ("TERM_PROGRAM" in env3) {
  21134. var version3 = parseInt((env3.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
  21135. switch (env3.TERM_PROGRAM) {
  21136. case "iTerm.app":
  21137. return version3 >= 3 ? 3 : 2;
  21138. case "Hyper":
  21139. return 3;
  21140. case "Apple_Terminal":
  21141. return 2;
  21142. }
  21143. }
  21144. if (/-256(color)?$/i.test(env3.TERM)) {
  21145. return 2;
  21146. }
  21147. if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env3.TERM)) {
  21148. return 1;
  21149. }
  21150. if ("COLORTERM" in env3) {
  21151. return 1;
  21152. }
  21153. if (env3.TERM === "dumb") {
  21154. return min;
  21155. }
  21156. return min;
  21157. }
  21158. function getSupportLevel(stream) {
  21159. var level = supportsColor2(stream);
  21160. return translateLevel2(level);
  21161. }
  21162. module2.exports = {
  21163. supportsColor: getSupportLevel,
  21164. stdout: getSupportLevel(process.stdout),
  21165. stderr: getSupportLevel(process.stderr)
  21166. };
  21167. }
  21168. });
  21169. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js
  21170. var require_trap = __commonJS({
  21171. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js"(exports2, module2) {
  21172. module2["exports"] = function runTheTrap(text, options) {
  21173. var result = "";
  21174. text = text || "Run the trap, drop the bass";
  21175. text = text.split("");
  21176. var trap = {
  21177. a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"],
  21178. b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"],
  21179. c: ["\xA9", "\u023B", "\u03FE"],
  21180. d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"],
  21181. e: [
  21182. "\xCB",
  21183. "\u0115",
  21184. "\u018E",
  21185. "\u0258",
  21186. "\u03A3",
  21187. "\u03BE",
  21188. "\u04BC",
  21189. "\u0A6C"
  21190. ],
  21191. f: ["\u04FA"],
  21192. g: ["\u0262"],
  21193. h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"],
  21194. i: ["\u0F0F"],
  21195. j: ["\u0134"],
  21196. k: ["\u0138", "\u04A0", "\u04C3", "\u051E"],
  21197. l: ["\u0139"],
  21198. m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"],
  21199. n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"],
  21200. o: [
  21201. "\xD8",
  21202. "\xF5",
  21203. "\xF8",
  21204. "\u01FE",
  21205. "\u0298",
  21206. "\u047A",
  21207. "\u05DD",
  21208. "\u06DD",
  21209. "\u0E4F"
  21210. ],
  21211. p: ["\u01F7", "\u048E"],
  21212. q: ["\u09CD"],
  21213. r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"],
  21214. s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"],
  21215. t: ["\u0141", "\u0166", "\u0373"],
  21216. u: ["\u01B1", "\u054D"],
  21217. v: ["\u05D8"],
  21218. w: ["\u0428", "\u0460", "\u047C", "\u0D70"],
  21219. x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"],
  21220. y: ["\xA5", "\u04B0", "\u04CB"],
  21221. z: ["\u01B5", "\u0240"]
  21222. };
  21223. text.forEach(function(c3) {
  21224. c3 = c3.toLowerCase();
  21225. var chars = trap[c3] || [" "];
  21226. var rand = Math.floor(Math.random() * chars.length);
  21227. if (typeof trap[c3] !== "undefined") {
  21228. result += trap[c3][rand];
  21229. } else {
  21230. result += c3;
  21231. }
  21232. });
  21233. return result;
  21234. };
  21235. }
  21236. });
  21237. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/zalgo.js
  21238. var require_zalgo = __commonJS({
  21239. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/zalgo.js"(exports2, module2) {
  21240. module2["exports"] = function zalgo(text, options) {
  21241. text = text || " he is here ";
  21242. var soul = {
  21243. "up": [
  21244. "\u030D",
  21245. "\u030E",
  21246. "\u0304",
  21247. "\u0305",
  21248. "\u033F",
  21249. "\u0311",
  21250. "\u0306",
  21251. "\u0310",
  21252. "\u0352",
  21253. "\u0357",
  21254. "\u0351",
  21255. "\u0307",
  21256. "\u0308",
  21257. "\u030A",
  21258. "\u0342",
  21259. "\u0313",
  21260. "\u0308",
  21261. "\u034A",
  21262. "\u034B",
  21263. "\u034C",
  21264. "\u0303",
  21265. "\u0302",
  21266. "\u030C",
  21267. "\u0350",
  21268. "\u0300",
  21269. "\u0301",
  21270. "\u030B",
  21271. "\u030F",
  21272. "\u0312",
  21273. "\u0313",
  21274. "\u0314",
  21275. "\u033D",
  21276. "\u0309",
  21277. "\u0363",
  21278. "\u0364",
  21279. "\u0365",
  21280. "\u0366",
  21281. "\u0367",
  21282. "\u0368",
  21283. "\u0369",
  21284. "\u036A",
  21285. "\u036B",
  21286. "\u036C",
  21287. "\u036D",
  21288. "\u036E",
  21289. "\u036F",
  21290. "\u033E",
  21291. "\u035B",
  21292. "\u0346",
  21293. "\u031A"
  21294. ],
  21295. "down": [
  21296. "\u0316",
  21297. "\u0317",
  21298. "\u0318",
  21299. "\u0319",
  21300. "\u031C",
  21301. "\u031D",
  21302. "\u031E",
  21303. "\u031F",
  21304. "\u0320",
  21305. "\u0324",
  21306. "\u0325",
  21307. "\u0326",
  21308. "\u0329",
  21309. "\u032A",
  21310. "\u032B",
  21311. "\u032C",
  21312. "\u032D",
  21313. "\u032E",
  21314. "\u032F",
  21315. "\u0330",
  21316. "\u0331",
  21317. "\u0332",
  21318. "\u0333",
  21319. "\u0339",
  21320. "\u033A",
  21321. "\u033B",
  21322. "\u033C",
  21323. "\u0345",
  21324. "\u0347",
  21325. "\u0348",
  21326. "\u0349",
  21327. "\u034D",
  21328. "\u034E",
  21329. "\u0353",
  21330. "\u0354",
  21331. "\u0355",
  21332. "\u0356",
  21333. "\u0359",
  21334. "\u035A",
  21335. "\u0323"
  21336. ],
  21337. "mid": [
  21338. "\u0315",
  21339. "\u031B",
  21340. "\u0300",
  21341. "\u0301",
  21342. "\u0358",
  21343. "\u0321",
  21344. "\u0322",
  21345. "\u0327",
  21346. "\u0328",
  21347. "\u0334",
  21348. "\u0335",
  21349. "\u0336",
  21350. "\u035C",
  21351. "\u035D",
  21352. "\u035E",
  21353. "\u035F",
  21354. "\u0360",
  21355. "\u0362",
  21356. "\u0338",
  21357. "\u0337",
  21358. "\u0361",
  21359. " \u0489"
  21360. ]
  21361. };
  21362. var all = [].concat(soul.up, soul.down, soul.mid);
  21363. function randomNumber(range) {
  21364. var r4 = Math.floor(Math.random() * range);
  21365. return r4;
  21366. }
  21367. function isChar(character) {
  21368. var bool = false;
  21369. all.filter(function(i4) {
  21370. bool = i4 === character;
  21371. });
  21372. return bool;
  21373. }
  21374. function heComes(text2, options2) {
  21375. var result = "";
  21376. var counts;
  21377. var l3;
  21378. options2 = options2 || {};
  21379. options2["up"] = typeof options2["up"] !== "undefined" ? options2["up"] : true;
  21380. options2["mid"] = typeof options2["mid"] !== "undefined" ? options2["mid"] : true;
  21381. options2["down"] = typeof options2["down"] !== "undefined" ? options2["down"] : true;
  21382. options2["size"] = typeof options2["size"] !== "undefined" ? options2["size"] : "maxi";
  21383. text2 = text2.split("");
  21384. for (l3 in text2) {
  21385. if (isChar(l3)) {
  21386. continue;
  21387. }
  21388. result = result + text2[l3];
  21389. counts = { "up": 0, "down": 0, "mid": 0 };
  21390. switch (options2.size) {
  21391. case "mini":
  21392. counts.up = randomNumber(8);
  21393. counts.mid = randomNumber(2);
  21394. counts.down = randomNumber(8);
  21395. break;
  21396. case "maxi":
  21397. counts.up = randomNumber(16) + 3;
  21398. counts.mid = randomNumber(4) + 1;
  21399. counts.down = randomNumber(64) + 3;
  21400. break;
  21401. default:
  21402. counts.up = randomNumber(8) + 1;
  21403. counts.mid = randomNumber(6) / 2;
  21404. counts.down = randomNumber(8) + 1;
  21405. break;
  21406. }
  21407. var arr = ["up", "mid", "down"];
  21408. for (var d3 in arr) {
  21409. var index6 = arr[d3];
  21410. for (var i4 = 0; i4 <= counts[index6]; i4++) {
  21411. if (options2[index6]) {
  21412. result = result + soul[index6][randomNumber(soul[index6].length)];
  21413. }
  21414. }
  21415. }
  21416. }
  21417. return result;
  21418. }
  21419. return heComes(text, options);
  21420. };
  21421. }
  21422. });
  21423. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js
  21424. var require_america = __commonJS({
  21425. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js"(exports2, module2) {
  21426. module2["exports"] = function(colors) {
  21427. return function(letter, i4, exploded) {
  21428. if (letter === " ") return letter;
  21429. switch (i4 % 3) {
  21430. case 0:
  21431. return colors.red(letter);
  21432. case 1:
  21433. return colors.white(letter);
  21434. case 2:
  21435. return colors.blue(letter);
  21436. }
  21437. };
  21438. };
  21439. }
  21440. });
  21441. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/zebra.js
  21442. var require_zebra = __commonJS({
  21443. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/zebra.js"(exports2, module2) {
  21444. module2["exports"] = function(colors) {
  21445. return function(letter, i4, exploded) {
  21446. return i4 % 2 === 0 ? letter : colors.inverse(letter);
  21447. };
  21448. };
  21449. }
  21450. });
  21451. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/rainbow.js
  21452. var require_rainbow = __commonJS({
  21453. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/rainbow.js"(exports2, module2) {
  21454. module2["exports"] = function(colors) {
  21455. var rainbowColors = ["red", "yellow", "green", "blue", "magenta"];
  21456. return function(letter, i4, exploded) {
  21457. if (letter === " ") {
  21458. return letter;
  21459. } else {
  21460. return colors[rainbowColors[i4++ % rainbowColors.length]](letter);
  21461. }
  21462. };
  21463. };
  21464. }
  21465. });
  21466. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/random.js
  21467. var require_random = __commonJS({
  21468. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/random.js"(exports2, module2) {
  21469. module2["exports"] = function(colors) {
  21470. var available = [
  21471. "underline",
  21472. "inverse",
  21473. "grey",
  21474. "yellow",
  21475. "red",
  21476. "green",
  21477. "blue",
  21478. "white",
  21479. "cyan",
  21480. "magenta",
  21481. "brightYellow",
  21482. "brightRed",
  21483. "brightGreen",
  21484. "brightBlue",
  21485. "brightWhite",
  21486. "brightCyan",
  21487. "brightMagenta"
  21488. ];
  21489. return function(letter, i4, exploded) {
  21490. return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 2))]](letter);
  21491. };
  21492. };
  21493. }
  21494. });
  21495. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/colors.js
  21496. var require_colors = __commonJS({
  21497. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/colors.js"(exports2, module2) {
  21498. var colors = {};
  21499. module2["exports"] = colors;
  21500. colors.themes = {};
  21501. var util2 = require("util");
  21502. var ansiStyles2 = colors.styles = require_styles();
  21503. var defineProps = Object.defineProperties;
  21504. var newLineRegex = new RegExp(/[\r\n]+/g);
  21505. colors.supportsColor = require_supports_colors().supportsColor;
  21506. if (typeof colors.enabled === "undefined") {
  21507. colors.enabled = colors.supportsColor() !== false;
  21508. }
  21509. colors.enable = function() {
  21510. colors.enabled = true;
  21511. };
  21512. colors.disable = function() {
  21513. colors.enabled = false;
  21514. };
  21515. colors.stripColors = colors.strip = function(str) {
  21516. return ("" + str).replace(/\x1B\[\d+m/g, "");
  21517. };
  21518. var stylize = colors.stylize = function stylize2(str, style) {
  21519. if (!colors.enabled) {
  21520. return str + "";
  21521. }
  21522. var styleMap = ansiStyles2[style];
  21523. if (!styleMap && style in colors) {
  21524. return colors[style](str);
  21525. }
  21526. return styleMap.open + str + styleMap.close;
  21527. };
  21528. var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
  21529. var escapeStringRegexp = function(str) {
  21530. if (typeof str !== "string") {
  21531. throw new TypeError("Expected a string");
  21532. }
  21533. return str.replace(matchOperatorsRe, "\\$&");
  21534. };
  21535. function build(_styles) {
  21536. var builder = function builder2() {
  21537. return applyStyle2.apply(builder2, arguments);
  21538. };
  21539. builder._styles = _styles;
  21540. builder.__proto__ = proto2;
  21541. return builder;
  21542. }
  21543. var styles3 = function() {
  21544. var ret = {};
  21545. ansiStyles2.grey = ansiStyles2.gray;
  21546. Object.keys(ansiStyles2).forEach(function(key) {
  21547. ansiStyles2[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles2[key].close), "g");
  21548. ret[key] = {
  21549. get: function() {
  21550. return build(this._styles.concat(key));
  21551. }
  21552. };
  21553. });
  21554. return ret;
  21555. }();
  21556. var proto2 = defineProps(function colors2() {
  21557. }, styles3);
  21558. function applyStyle2() {
  21559. var args = Array.prototype.slice.call(arguments);
  21560. var str = args.map(function(arg) {
  21561. if (arg != null && arg.constructor === String) {
  21562. return arg;
  21563. } else {
  21564. return util2.inspect(arg);
  21565. }
  21566. }).join(" ");
  21567. if (!colors.enabled || !str) {
  21568. return str;
  21569. }
  21570. var newLinesPresent = str.indexOf("\n") != -1;
  21571. var nestedStyles = this._styles;
  21572. var i4 = nestedStyles.length;
  21573. while (i4--) {
  21574. var code = ansiStyles2[nestedStyles[i4]];
  21575. str = code.open + str.replace(code.closeRe, code.open) + code.close;
  21576. if (newLinesPresent) {
  21577. str = str.replace(newLineRegex, function(match2) {
  21578. return code.close + match2 + code.open;
  21579. });
  21580. }
  21581. }
  21582. return str;
  21583. }
  21584. colors.setTheme = function(theme) {
  21585. if (typeof theme === "string") {
  21586. console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");
  21587. return;
  21588. }
  21589. for (var style in theme) {
  21590. (function(style2) {
  21591. colors[style2] = function(str) {
  21592. if (typeof theme[style2] === "object") {
  21593. var out = str;
  21594. for (var i4 in theme[style2]) {
  21595. out = colors[theme[style2][i4]](out);
  21596. }
  21597. return out;
  21598. }
  21599. return colors[theme[style2]](str);
  21600. };
  21601. })(style);
  21602. }
  21603. };
  21604. function init2() {
  21605. var ret = {};
  21606. Object.keys(styles3).forEach(function(name) {
  21607. ret[name] = {
  21608. get: function() {
  21609. return build([name]);
  21610. }
  21611. };
  21612. });
  21613. return ret;
  21614. }
  21615. var sequencer = function sequencer2(map3, str) {
  21616. var exploded = str.split("");
  21617. exploded = exploded.map(map3);
  21618. return exploded.join("");
  21619. };
  21620. colors.trap = require_trap();
  21621. colors.zalgo = require_zalgo();
  21622. colors.maps = {};
  21623. colors.maps.america = require_america()(colors);
  21624. colors.maps.zebra = require_zebra()(colors);
  21625. colors.maps.rainbow = require_rainbow()(colors);
  21626. colors.maps.random = require_random()(colors);
  21627. for (map2 in colors.maps) {
  21628. (function(map3) {
  21629. colors[map3] = function(str) {
  21630. return sequencer(colors.maps[map3], str);
  21631. };
  21632. })(map2);
  21633. }
  21634. var map2;
  21635. defineProps(colors, init2());
  21636. }
  21637. });
  21638. // ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js
  21639. var require_safe = __commonJS({
  21640. "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js"(exports2, module2) {
  21641. var colors = require_colors();
  21642. module2["exports"] = colors;
  21643. }
  21644. });
  21645. // ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js
  21646. var require_colorize = __commonJS({
  21647. "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js"(exports2, module2) {
  21648. var color = require_safe();
  21649. var { extendedTypeOf } = require_util();
  21650. var Theme = {
  21651. " "(s4) {
  21652. return s4;
  21653. },
  21654. "+": color.green,
  21655. "-": color.red
  21656. };
  21657. var subcolorizeToCallback = function(options, key, diff2, output, color2, indent) {
  21658. let subvalue;
  21659. const prefix2 = key ? `${key}: ` : "";
  21660. const subindent = indent + " ";
  21661. const outputElisions = (n3) => {
  21662. const maxElisions = options.maxElisions === void 0 ? Infinity : options.maxElisions;
  21663. if (n3 < maxElisions) {
  21664. for (let i4 = 0; i4 < n3; i4++) {
  21665. output(" ", subindent + "...");
  21666. }
  21667. } else {
  21668. output(" ", subindent + `... (${n3} entries)`);
  21669. }
  21670. };
  21671. switch (extendedTypeOf(diff2)) {
  21672. case "object":
  21673. if ("__old" in diff2 && "__new" in diff2 && Object.keys(diff2).length === 2) {
  21674. subcolorizeToCallback(options, key, diff2.__old, output, "-", indent);
  21675. return subcolorizeToCallback(options, key, diff2.__new, output, "+", indent);
  21676. } else {
  21677. output(color2, `${indent}${prefix2}{`);
  21678. for (const subkey of Object.keys(diff2)) {
  21679. let m4;
  21680. subvalue = diff2[subkey];
  21681. if (m4 = subkey.match(/^(.*)__deleted$/)) {
  21682. subcolorizeToCallback(options, m4[1], subvalue, output, "-", subindent);
  21683. } else if (m4 = subkey.match(/^(.*)__added$/)) {
  21684. subcolorizeToCallback(options, m4[1], subvalue, output, "+", subindent);
  21685. } else {
  21686. subcolorizeToCallback(options, subkey, subvalue, output, color2, subindent);
  21687. }
  21688. }
  21689. return output(color2, `${indent}}`);
  21690. }
  21691. case "array": {
  21692. output(color2, `${indent}${prefix2}[`);
  21693. let looksLikeDiff = true;
  21694. for (const item of diff2) {
  21695. if (extendedTypeOf(item) !== "array" || !(item.length === 2 || item.length === 1 && item[0] === " ") || !(typeof item[0] === "string") || item[0].length !== 1 || ![" ", "-", "+", "~"].includes(item[0])) {
  21696. looksLikeDiff = false;
  21697. }
  21698. }
  21699. if (looksLikeDiff) {
  21700. let op;
  21701. let elisionCount = 0;
  21702. for ([op, subvalue] of diff2) {
  21703. if (op === " " && subvalue == null) {
  21704. elisionCount++;
  21705. } else {
  21706. if (elisionCount > 0) {
  21707. outputElisions(elisionCount);
  21708. }
  21709. elisionCount = 0;
  21710. if (![" ", "~", "+", "-"].includes(op)) {
  21711. throw new Error(`Unexpected op '${op}' in ${JSON.stringify(diff2, null, 2)}`);
  21712. }
  21713. if (op === "~") {
  21714. op = " ";
  21715. }
  21716. subcolorizeToCallback(options, "", subvalue, output, op, subindent);
  21717. }
  21718. }
  21719. if (elisionCount > 0) {
  21720. outputElisions(elisionCount);
  21721. }
  21722. } else {
  21723. for (subvalue of diff2) {
  21724. subcolorizeToCallback(options, "", subvalue, output, color2, subindent);
  21725. }
  21726. }
  21727. return output(color2, `${indent}]`);
  21728. }
  21729. default:
  21730. if (diff2 === 0 || diff2 === null || diff2 === false || diff2 === "" || diff2) {
  21731. return output(color2, indent + prefix2 + JSON.stringify(diff2));
  21732. }
  21733. }
  21734. };
  21735. var colorizeToCallback = (diff2, options, output) => subcolorizeToCallback(options, "", diff2, output, " ", "");
  21736. var colorizeToArray = function(diff2, options = {}) {
  21737. const output = [];
  21738. colorizeToCallback(diff2, options, (color2, line) => output.push(`${color2}${line}`));
  21739. return output;
  21740. };
  21741. var colorize = function(diff2, options = {}) {
  21742. const output = [];
  21743. colorizeToCallback(diff2, options, function(color2, line) {
  21744. if (options.color != null ? options.color : true) {
  21745. return output.push(((options.theme != null ? options.theme[color2] : void 0) != null ? options.theme != null ? options.theme[color2] : void 0 : Theme[color2])(`${color2}${line}`) + "\n");
  21746. } else {
  21747. return output.push(`${color2}${line}
  21748. `);
  21749. }
  21750. });
  21751. return output.join("");
  21752. };
  21753. module2.exports = { colorize, colorizeToArray, colorizeToCallback };
  21754. }
  21755. });
  21756. // ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js
  21757. var require_lib = __commonJS({
  21758. "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js"(exports2, module2) {
  21759. var { SequenceMatcher } = require_difflib2();
  21760. var { extendedTypeOf, roundObj } = require_util();
  21761. var { colorize, colorizeToCallback } = require_colorize();
  21762. var JsonDiff = class {
  21763. constructor(options) {
  21764. options.outputKeys = options.outputKeys || [];
  21765. options.excludeKeys = options.excludeKeys || [];
  21766. this.options = options;
  21767. }
  21768. isScalar(obj) {
  21769. return typeof obj !== "object" || obj === null;
  21770. }
  21771. objectDiff(obj1, obj2) {
  21772. let result = {};
  21773. let score = 0;
  21774. let equal = true;
  21775. for (const [key, value] of Object.entries(obj1)) {
  21776. if (!this.options.outputNewOnly) {
  21777. const postfix = "__deleted";
  21778. if (!(key in obj2) && !this.options.excludeKeys.includes(key)) {
  21779. result[`${key}${postfix}`] = value;
  21780. score -= 30;
  21781. equal = false;
  21782. }
  21783. }
  21784. }
  21785. for (const [key, value] of Object.entries(obj2)) {
  21786. const postfix = !this.options.outputNewOnly ? "__added" : "";
  21787. if (!(key in obj1) && !this.options.excludeKeys.includes(key)) {
  21788. result[`${key}${postfix}`] = value;
  21789. score -= 30;
  21790. equal = false;
  21791. }
  21792. }
  21793. for (const [key, value1] of Object.entries(obj1)) {
  21794. if (key in obj2) {
  21795. if (this.options.excludeKeys.includes(key)) {
  21796. continue;
  21797. }
  21798. score += 20;
  21799. const value2 = obj2[key];
  21800. const change = this.diff(value1, value2);
  21801. if (!change.equal) {
  21802. result[key] = change.result;
  21803. equal = false;
  21804. } else if (this.options.full || this.options.outputKeys.includes(key)) {
  21805. result[key] = value1;
  21806. }
  21807. score += Math.min(20, Math.max(-10, change.score / 5));
  21808. }
  21809. }
  21810. if (equal) {
  21811. score = 100 * Math.max(Object.keys(obj1).length, 0.5);
  21812. if (!this.options.full) {
  21813. result = void 0;
  21814. }
  21815. } else {
  21816. score = Math.max(0, score);
  21817. }
  21818. return { score, result, equal };
  21819. }
  21820. findMatchingObject(item, index6, fuzzyOriginals) {
  21821. let bestMatch = null;
  21822. for (const [key, { item: candidate, index: matchIndex }] of Object.entries(fuzzyOriginals)) {
  21823. if (key !== "__next") {
  21824. const indexDistance = Math.abs(matchIndex - index6);
  21825. if (extendedTypeOf(item) === extendedTypeOf(candidate)) {
  21826. const { score } = this.diff(item, candidate);
  21827. if (!bestMatch || score > bestMatch.score || score === bestMatch.score && indexDistance < bestMatch.indexDistance) {
  21828. bestMatch = { score, key, indexDistance };
  21829. }
  21830. }
  21831. }
  21832. }
  21833. return bestMatch;
  21834. }
  21835. scalarize(array2, originals, fuzzyOriginals) {
  21836. const fuzzyMatches = [];
  21837. if (fuzzyOriginals) {
  21838. const keyScores = {};
  21839. for (let index6 = 0; index6 < array2.length; index6++) {
  21840. const item = array2[index6];
  21841. if (this.isScalar(item)) {
  21842. continue;
  21843. }
  21844. const bestMatch = this.findMatchingObject(item, index6, fuzzyOriginals);
  21845. if (bestMatch && (!keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score)) {
  21846. keyScores[bestMatch.key] = { score: bestMatch.score, index: index6 };
  21847. }
  21848. }
  21849. for (const [key, match2] of Object.entries(keyScores)) {
  21850. fuzzyMatches[match2.index] = key;
  21851. }
  21852. }
  21853. const result = [];
  21854. for (let index6 = 0; index6 < array2.length; index6++) {
  21855. const item = array2[index6];
  21856. if (this.isScalar(item)) {
  21857. result.push(item);
  21858. } else {
  21859. const key = fuzzyMatches[index6] || "__$!SCALAR" + originals.__next++;
  21860. originals[key] = { item, index: index6 };
  21861. result.push(key);
  21862. }
  21863. }
  21864. return result;
  21865. }
  21866. isScalarized(item, originals) {
  21867. return typeof item === "string" && item in originals;
  21868. }
  21869. descalarize(item, originals) {
  21870. if (this.isScalarized(item, originals)) {
  21871. return originals[item].item;
  21872. } else {
  21873. return item;
  21874. }
  21875. }
  21876. arrayDiff(obj1, obj2) {
  21877. const originals1 = { __next: 1 };
  21878. const seq1 = this.scalarize(obj1, originals1);
  21879. const originals2 = { __next: originals1.__next };
  21880. const seq2 = this.scalarize(obj2, originals2, originals1);
  21881. if (this.options.sort) {
  21882. seq1.sort();
  21883. seq2.sort();
  21884. }
  21885. const opcodes = new SequenceMatcher(null, seq1, seq2).getOpcodes();
  21886. let result = [];
  21887. let score = 0;
  21888. let equal = true;
  21889. for (const [op, i1, i22, j1, j22] of opcodes) {
  21890. let i4, j3;
  21891. let asc, end;
  21892. let asc1, end1;
  21893. let asc2, end2;
  21894. if (!(op === "equal" || this.options.keysOnly && op === "replace")) {
  21895. equal = false;
  21896. }
  21897. switch (op) {
  21898. case "equal":
  21899. for (i4 = i1, end = i22, asc = i1 <= end; asc ? i4 < end : i4 > end; asc ? i4++ : i4--) {
  21900. const item = seq1[i4];
  21901. if (this.isScalarized(item, originals1)) {
  21902. if (!this.isScalarized(item, originals2)) {
  21903. throw new Error(
  21904. `internal bug: isScalarized(item, originals1) != isScalarized(item, originals2) for item ${JSON.stringify(
  21905. item
  21906. )}`
  21907. );
  21908. }
  21909. const item1 = this.descalarize(item, originals1);
  21910. const item2 = this.descalarize(item, originals2);
  21911. const change = this.diff(item1, item2);
  21912. if (!change.equal) {
  21913. result.push(["~", change.result]);
  21914. equal = false;
  21915. } else {
  21916. if (this.options.full || this.options.keepUnchangedValues) {
  21917. result.push([" ", item1]);
  21918. } else {
  21919. result.push([" "]);
  21920. }
  21921. }
  21922. } else {
  21923. if (this.options.full || this.options.keepUnchangedValues) {
  21924. result.push([" ", item]);
  21925. } else {
  21926. result.push([" "]);
  21927. }
  21928. }
  21929. score += 10;
  21930. }
  21931. break;
  21932. case "delete":
  21933. for (i4 = i1, end1 = i22, asc1 = i1 <= end1; asc1 ? i4 < end1 : i4 > end1; asc1 ? i4++ : i4--) {
  21934. result.push(["-", this.descalarize(seq1[i4], originals1)]);
  21935. score -= 5;
  21936. }
  21937. break;
  21938. case "insert":
  21939. for (j3 = j1, end2 = j22, asc2 = j1 <= end2; asc2 ? j3 < end2 : j3 > end2; asc2 ? j3++ : j3--) {
  21940. result.push(["+", this.descalarize(seq2[j3], originals2)]);
  21941. score -= 5;
  21942. }
  21943. break;
  21944. case "replace":
  21945. if (!this.options.keysOnly) {
  21946. let asc3, end3;
  21947. let asc4, end4;
  21948. for (i4 = i1, end3 = i22, asc3 = i1 <= end3; asc3 ? i4 < end3 : i4 > end3; asc3 ? i4++ : i4--) {
  21949. result.push(["-", this.descalarize(seq1[i4], originals1)]);
  21950. score -= 5;
  21951. }
  21952. for (j3 = j1, end4 = j22, asc4 = j1 <= end4; asc4 ? j3 < end4 : j3 > end4; asc4 ? j3++ : j3--) {
  21953. result.push(["+", this.descalarize(seq2[j3], originals2)]);
  21954. score -= 5;
  21955. }
  21956. } else {
  21957. let asc5, end5;
  21958. for (i4 = i1, end5 = i22, asc5 = i1 <= end5; asc5 ? i4 < end5 : i4 > end5; asc5 ? i4++ : i4--) {
  21959. const change = this.diff(
  21960. this.descalarize(seq1[i4], originals1),
  21961. this.descalarize(seq2[i4 - i1 + j1], originals2)
  21962. );
  21963. if (!change.equal) {
  21964. result.push(["~", change.result]);
  21965. equal = false;
  21966. } else {
  21967. result.push([" "]);
  21968. }
  21969. }
  21970. }
  21971. break;
  21972. }
  21973. }
  21974. if (equal || opcodes.length === 0) {
  21975. if (!this.options.full) {
  21976. result = void 0;
  21977. } else {
  21978. result = obj1;
  21979. }
  21980. score = 100;
  21981. } else {
  21982. score = Math.max(0, score);
  21983. }
  21984. return { score, result, equal };
  21985. }
  21986. diff(obj1, obj2) {
  21987. const type1 = extendedTypeOf(obj1);
  21988. const type2 = extendedTypeOf(obj2);
  21989. if (type1 === type2) {
  21990. switch (type1) {
  21991. case "object":
  21992. return this.objectDiff(obj1, obj2);
  21993. case "array":
  21994. return this.arrayDiff(obj1, obj2);
  21995. }
  21996. }
  21997. let score = 100;
  21998. let result = obj1;
  21999. let equal;
  22000. if (!this.options.keysOnly) {
  22001. if (type1 === "date" && type2 === "date") {
  22002. equal = obj1.getTime() === obj2.getTime();
  22003. } else {
  22004. equal = obj1 === obj2;
  22005. }
  22006. if (!equal) {
  22007. score = 0;
  22008. if (this.options.outputNewOnly) {
  22009. result = obj2;
  22010. } else {
  22011. result = { __old: obj1, __new: obj2 };
  22012. }
  22013. } else if (!this.options.full) {
  22014. result = void 0;
  22015. }
  22016. } else {
  22017. equal = true;
  22018. result = void 0;
  22019. }
  22020. return { score, result, equal };
  22021. }
  22022. };
  22023. function diff2(obj1, obj2, options = {}) {
  22024. if (options.precision !== void 0) {
  22025. obj1 = roundObj(obj1, options.precision);
  22026. obj2 = roundObj(obj2, options.precision);
  22027. }
  22028. return new JsonDiff(options).diff(obj1, obj2).result;
  22029. }
  22030. function diffString(obj1, obj2, options = {}) {
  22031. return colorize(diff2(obj1, obj2, options), options);
  22032. }
  22033. module2.exports = { diff: diff2, diffString, colorize, colorizeToCallback };
  22034. }
  22035. });
  22036. // src/jsonDiffer.js
  22037. function diffSchemasOrTables(left, right) {
  22038. left = JSON.parse(JSON.stringify(left));
  22039. right = JSON.parse(JSON.stringify(right));
  22040. const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  22041. const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  22042. const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  22043. return { added, deleted };
  22044. }
  22045. function diffIndPolicies(left, right) {
  22046. left = JSON.parse(JSON.stringify(left));
  22047. right = JSON.parse(JSON.stringify(right));
  22048. const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  22049. const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  22050. const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  22051. return { added, deleted };
  22052. }
  22053. function diffColumns(left, right) {
  22054. left = JSON.parse(JSON.stringify(left));
  22055. right = JSON.parse(JSON.stringify(right));
  22056. const result = (0, import_json_diff.diff)(left, right) ?? {};
  22057. const alteredTables = Object.fromEntries(
  22058. Object.entries(result).filter((it) => {
  22059. return !(it[0].includes("__added") || it[0].includes("__deleted"));
  22060. }).map((tableEntry) => {
  22061. const deletedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
  22062. return it[0].endsWith("__deleted");
  22063. }).map((it) => {
  22064. return it[1];
  22065. });
  22066. const addedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
  22067. return it[0].endsWith("__added");
  22068. }).map((it) => {
  22069. return it[1];
  22070. });
  22071. tableEntry[1].columns = {
  22072. added: addedColumns,
  22073. deleted: deletedColumns
  22074. };
  22075. const table6 = left[tableEntry[0]];
  22076. return [
  22077. tableEntry[0],
  22078. { name: table6.name, schema: table6.schema, ...tableEntry[1] }
  22079. ];
  22080. })
  22081. );
  22082. return alteredTables;
  22083. }
  22084. function diffPolicies(left, right) {
  22085. left = JSON.parse(JSON.stringify(left));
  22086. right = JSON.parse(JSON.stringify(right));
  22087. const result = (0, import_json_diff.diff)(left, right) ?? {};
  22088. const alteredTables = Object.fromEntries(
  22089. Object.entries(result).filter((it) => {
  22090. return !(it[0].includes("__added") || it[0].includes("__deleted"));
  22091. }).map((tableEntry) => {
  22092. const deletedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
  22093. return it[0].endsWith("__deleted");
  22094. }).map((it) => {
  22095. return it[1];
  22096. });
  22097. const addedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
  22098. return it[0].endsWith("__added");
  22099. }).map((it) => {
  22100. return it[1];
  22101. });
  22102. tableEntry[1].policies = {
  22103. added: addedPolicies,
  22104. deleted: deletedPolicies
  22105. };
  22106. const table6 = left[tableEntry[0]];
  22107. return [
  22108. tableEntry[0],
  22109. { name: table6.name, schema: table6.schema, ...tableEntry[1] }
  22110. ];
  22111. })
  22112. );
  22113. return alteredTables;
  22114. }
  22115. function applyJsonDiff(json1, json2) {
  22116. json1 = JSON.parse(JSON.stringify(json1));
  22117. json2 = JSON.parse(JSON.stringify(json2));
  22118. const rawDiff = (0, import_json_diff.diff)(json1, json2);
  22119. const difference = JSON.parse(JSON.stringify(rawDiff || {}));
  22120. difference.schemas = difference.schemas || {};
  22121. difference.tables = difference.tables || {};
  22122. difference.enums = difference.enums || {};
  22123. difference.sequences = difference.sequences || {};
  22124. difference.roles = difference.roles || {};
  22125. difference.policies = difference.policies || {};
  22126. difference.views = difference.views || {};
  22127. const schemaKeys = Object.keys(difference.schemas);
  22128. for (let key of schemaKeys) {
  22129. if (key.endsWith("__added") || key.endsWith("__deleted")) {
  22130. delete difference.schemas[key];
  22131. continue;
  22132. }
  22133. }
  22134. const tableKeys = Object.keys(difference.tables);
  22135. for (let key of tableKeys) {
  22136. if (key.endsWith("__added") || key.endsWith("__deleted")) {
  22137. delete difference.tables[key];
  22138. continue;
  22139. }
  22140. const table6 = json1.tables[key];
  22141. difference.tables[key] = {
  22142. name: table6.name,
  22143. schema: table6.schema,
  22144. ...difference.tables[key]
  22145. };
  22146. }
  22147. for (let [tableKey2, tableValue] of Object.entries(difference.tables)) {
  22148. const table6 = difference.tables[tableKey2];
  22149. const columns = tableValue.columns || {};
  22150. const columnKeys = Object.keys(columns);
  22151. for (let key of columnKeys) {
  22152. if (key.endsWith("__added") || key.endsWith("__deleted")) {
  22153. delete table6.columns[key];
  22154. continue;
  22155. }
  22156. }
  22157. if (Object.keys(columns).length === 0) {
  22158. delete table6["columns"];
  22159. }
  22160. if ("name" in table6 && "schema" in table6 && Object.keys(table6).length === 2) {
  22161. delete difference.tables[tableKey2];
  22162. }
  22163. }
  22164. const enumsEntries = Object.entries(difference.enums);
  22165. const alteredEnums = enumsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
  22166. const enumEntry = json1.enums[it[0]];
  22167. const { name, schema: schema6, values } = enumEntry;
  22168. const sequence = mapArraysDiff(values, it[1].values);
  22169. const addedValues = sequence.filter((it2) => it2.type === "added").map((it2) => {
  22170. return {
  22171. before: it2.before,
  22172. value: it2.value
  22173. };
  22174. });
  22175. const deletedValues = sequence.filter((it2) => it2.type === "removed").map((it2) => it2.value);
  22176. return { name, schema: schema6, addedValues, deletedValues };
  22177. });
  22178. const sequencesEntries = Object.entries(difference.sequences);
  22179. const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
  22180. return json2.sequences[it[0]];
  22181. });
  22182. const rolesEntries = Object.entries(difference.roles);
  22183. const alteredRoles = rolesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
  22184. return json2.roles[it[0]];
  22185. });
  22186. const policiesEntries = Object.entries(difference.policies);
  22187. const alteredPolicies = policiesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
  22188. return json2.policies[it[0]];
  22189. });
  22190. const viewsEntries = Object.entries(difference.views);
  22191. const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
  22192. ([nameWithSchema, view5]) => {
  22193. const deletedWithOption = view5.with__deleted;
  22194. const addedWithOption = view5.with__added;
  22195. const deletedWith = Object.fromEntries(
  22196. Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
  22197. return [key.replace("__deleted", ""), value];
  22198. })
  22199. );
  22200. const addedWith = Object.fromEntries(
  22201. Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
  22202. return [key.replace("__added", ""), value];
  22203. })
  22204. );
  22205. const alterWith = Object.fromEntries(
  22206. Object.entries(view5.with || {}).filter(
  22207. (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
  22208. ).map(
  22209. (it) => {
  22210. return [it[0], it[1].__new];
  22211. }
  22212. )
  22213. );
  22214. const alteredSchema = view5.schema;
  22215. const alteredDefinition = view5.definition;
  22216. const alteredExisting = view5.isExisting;
  22217. const addedTablespace = view5.tablespace__added;
  22218. const droppedTablespace = view5.tablespace__deleted;
  22219. const alterTablespaceTo = view5.tablespace;
  22220. let alteredTablespace;
  22221. if (addedTablespace) alteredTablespace = { __new: addedTablespace, __old: "pg_default" };
  22222. if (droppedTablespace) alteredTablespace = { __new: "pg_default", __old: droppedTablespace };
  22223. if (alterTablespaceTo) alteredTablespace = alterTablespaceTo;
  22224. const addedUsing = view5.using__added;
  22225. const droppedUsing = view5.using__deleted;
  22226. const alterUsingTo = view5.using;
  22227. let alteredUsing;
  22228. if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" };
  22229. if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing };
  22230. if (alterUsingTo) alteredUsing = alterUsingTo;
  22231. const alteredMeta = view5.meta;
  22232. return Object.fromEntries(
  22233. Object.entries({
  22234. name: json2.views[nameWithSchema].name,
  22235. schema: json2.views[nameWithSchema].schema,
  22236. // pg
  22237. deletedWithOption,
  22238. addedWithOption,
  22239. deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0,
  22240. addedWith: Object.keys(addedWith).length ? addedWith : void 0,
  22241. alteredWith: Object.keys(alterWith).length ? alterWith : void 0,
  22242. alteredSchema,
  22243. alteredTablespace,
  22244. alteredUsing,
  22245. // mysql
  22246. alteredMeta,
  22247. // common
  22248. alteredDefinition,
  22249. alteredExisting
  22250. }).filter(([_3, value]) => value !== void 0)
  22251. );
  22252. }
  22253. );
  22254. const alteredTablesWithColumns = Object.values(difference.tables).map(
  22255. (table6) => {
  22256. return findAlternationsInTable(table6);
  22257. }
  22258. );
  22259. return {
  22260. alteredTablesWithColumns,
  22261. alteredEnums,
  22262. alteredSequences,
  22263. alteredRoles,
  22264. alteredViews,
  22265. alteredPolicies
  22266. };
  22267. }
  22268. var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
  22269. var init_jsonDiffer = __esm({
  22270. "src/jsonDiffer.js"() {
  22271. "use strict";
  22272. "use-strict";
  22273. import_json_diff = __toESM(require_lib());
  22274. mapArraysDiff = (source, diff2) => {
  22275. const sequence = [];
  22276. let sourceIndex = 0;
  22277. for (let i4 = 0; i4 < diff2.length; i4++) {
  22278. const it = diff2[i4];
  22279. if (it.length === 1) {
  22280. sequence.push({ type: "same", value: source[sourceIndex] });
  22281. sourceIndex += 1;
  22282. } else {
  22283. if (it[0] === "-") {
  22284. sequence.push({ type: "removed", value: it[1] });
  22285. } else {
  22286. sequence.push({ type: "added", value: it[1], before: "" });
  22287. }
  22288. }
  22289. }
  22290. const result = sequence.reverse().reduce(
  22291. (acc, it) => {
  22292. if (it.type === "same") {
  22293. acc.prev = it.value;
  22294. }
  22295. if (it.type === "added" && acc.prev) {
  22296. it.before = acc.prev;
  22297. }
  22298. acc.result.push(it);
  22299. return acc;
  22300. },
  22301. { result: [] }
  22302. );
  22303. return result.result.reverse();
  22304. };
  22305. findAlternationsInTable = (table6) => {
  22306. const columns = table6.columns ?? {};
  22307. const altered = Object.keys(columns).filter((it) => !(it.includes("__deleted") || it.includes("__added"))).map((it) => {
  22308. return { name: it, ...columns[it] };
  22309. });
  22310. const deletedIndexes = Object.fromEntries(
  22311. Object.entries(table6.indexes__deleted || {}).concat(
  22312. Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__deleted"))
  22313. ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
  22314. );
  22315. const addedIndexes = Object.fromEntries(
  22316. Object.entries(table6.indexes__added || {}).concat(
  22317. Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__added"))
  22318. ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
  22319. );
  22320. const alteredIndexes = Object.fromEntries(
  22321. Object.entries(table6.indexes || {}).filter((it) => {
  22322. return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
  22323. })
  22324. );
  22325. const deletedPolicies = Object.fromEntries(
  22326. Object.entries(table6.policies__deleted || {}).concat(
  22327. Object.entries(table6.policies || {}).filter((it) => it[0].includes("__deleted"))
  22328. ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
  22329. );
  22330. const addedPolicies = Object.fromEntries(
  22331. Object.entries(table6.policies__added || {}).concat(
  22332. Object.entries(table6.policies || {}).filter((it) => it[0].includes("__added"))
  22333. ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
  22334. );
  22335. const alteredPolicies = Object.fromEntries(
  22336. Object.entries(table6.policies || {}).filter((it) => {
  22337. return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
  22338. })
  22339. );
  22340. const deletedForeignKeys = Object.fromEntries(
  22341. Object.entries(table6.foreignKeys__deleted || {}).concat(
  22342. Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
  22343. ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
  22344. );
  22345. const addedForeignKeys = Object.fromEntries(
  22346. Object.entries(table6.foreignKeys__added || {}).concat(
  22347. Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__added"))
  22348. ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
  22349. );
  22350. const alteredForeignKeys = Object.fromEntries(
  22351. Object.entries(table6.foreignKeys || {}).filter(
  22352. (it) => !it[0].endsWith("__added") && !it[0].endsWith("__deleted")
  22353. ).map((entry) => [entry[0], entry[1]])
  22354. );
  22355. const addedCompositePKs = Object.fromEntries(
  22356. Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
  22357. return it[0].endsWith("__added");
  22358. })
  22359. );
  22360. const deletedCompositePKs = Object.fromEntries(
  22361. Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
  22362. return it[0].endsWith("__deleted");
  22363. })
  22364. );
  22365. const alteredCompositePKs = Object.fromEntries(
  22366. Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
  22367. return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
  22368. })
  22369. );
  22370. const addedUniqueConstraints = Object.fromEntries(
  22371. Object.entries(table6.uniqueConstraints || {}).filter((it) => {
  22372. return it[0].endsWith("__added");
  22373. })
  22374. );
  22375. const deletedUniqueConstraints = Object.fromEntries(
  22376. Object.entries(table6.uniqueConstraints || {}).filter((it) => {
  22377. return it[0].endsWith("__deleted");
  22378. })
  22379. );
  22380. const alteredUniqueConstraints = Object.fromEntries(
  22381. Object.entries(table6.uniqueConstraints || {}).filter((it) => {
  22382. return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
  22383. })
  22384. );
  22385. const addedCheckConstraints = Object.fromEntries(
  22386. Object.entries(table6.checkConstraints || {}).filter((it) => {
  22387. return it[0].endsWith("__added");
  22388. })
  22389. );
  22390. const deletedCheckConstraints = Object.fromEntries(
  22391. Object.entries(table6.checkConstraints || {}).filter((it) => {
  22392. return it[0].endsWith("__deleted");
  22393. })
  22394. );
  22395. const alteredCheckConstraints = Object.fromEntries(
  22396. Object.entries(table6.checkConstraints || {}).filter((it) => {
  22397. return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
  22398. })
  22399. );
  22400. const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean);
  22401. return {
  22402. name: table6.name,
  22403. schema: table6.schema || "",
  22404. altered: mappedAltered,
  22405. addedIndexes,
  22406. deletedIndexes,
  22407. alteredIndexes,
  22408. addedForeignKeys,
  22409. deletedForeignKeys,
  22410. alteredForeignKeys,
  22411. addedCompositePKs,
  22412. deletedCompositePKs,
  22413. alteredCompositePKs,
  22414. addedUniqueConstraints,
  22415. deletedUniqueConstraints,
  22416. alteredUniqueConstraints,
  22417. deletedPolicies,
  22418. addedPolicies,
  22419. alteredPolicies,
  22420. addedCheckConstraints,
  22421. deletedCheckConstraints,
  22422. alteredCheckConstraints
  22423. };
  22424. };
  22425. alternationsInColumn = (column11) => {
  22426. const altered = [column11];
  22427. const result = altered.filter((it) => {
  22428. if ("type" in it && it.type.__old.replace(" (", "(") === it.type.__new.replace(" (", "(")) {
  22429. return false;
  22430. }
  22431. return true;
  22432. }).map((it) => {
  22433. if (typeof it.name !== "string" && "__old" in it.name) {
  22434. return {
  22435. ...it,
  22436. name: { type: "changed", old: it.name.__old, new: it.name.__new }
  22437. };
  22438. }
  22439. return it;
  22440. }).map((it) => {
  22441. if ("type" in it) {
  22442. return {
  22443. ...it,
  22444. type: { type: "changed", old: it.type.__old, new: it.type.__new }
  22445. };
  22446. }
  22447. return it;
  22448. }).map((it) => {
  22449. if ("default" in it) {
  22450. return {
  22451. ...it,
  22452. default: {
  22453. type: "changed",
  22454. old: it.default.__old,
  22455. new: it.default.__new
  22456. }
  22457. };
  22458. }
  22459. if ("default__added" in it) {
  22460. const { default__added, ...others } = it;
  22461. return {
  22462. ...others,
  22463. default: { type: "added", value: it.default__added }
  22464. };
  22465. }
  22466. if ("default__deleted" in it) {
  22467. const { default__deleted, ...others } = it;
  22468. return {
  22469. ...others,
  22470. default: { type: "deleted", value: it.default__deleted }
  22471. };
  22472. }
  22473. return it;
  22474. }).map((it) => {
  22475. if ("generated" in it) {
  22476. if ("as" in it.generated && "type" in it.generated) {
  22477. return {
  22478. ...it,
  22479. generated: {
  22480. type: "changed",
  22481. old: { as: it.generated.as.__old, type: it.generated.type.__old },
  22482. new: { as: it.generated.as.__new, type: it.generated.type.__new }
  22483. }
  22484. };
  22485. } else if ("as" in it.generated) {
  22486. return {
  22487. ...it,
  22488. generated: {
  22489. type: "changed",
  22490. old: { as: it.generated.as.__old },
  22491. new: { as: it.generated.as.__new }
  22492. }
  22493. };
  22494. } else {
  22495. return {
  22496. ...it,
  22497. generated: {
  22498. type: "changed",
  22499. old: { as: it.generated.type.__old },
  22500. new: { as: it.generated.type.__new }
  22501. }
  22502. };
  22503. }
  22504. }
  22505. if ("generated__added" in it) {
  22506. const { generated__added, ...others } = it;
  22507. return {
  22508. ...others,
  22509. generated: { type: "added", value: it.generated__added }
  22510. };
  22511. }
  22512. if ("generated__deleted" in it) {
  22513. const { generated__deleted, ...others } = it;
  22514. return {
  22515. ...others,
  22516. generated: { type: "deleted", value: it.generated__deleted }
  22517. };
  22518. }
  22519. return it;
  22520. }).map((it) => {
  22521. if ("identity" in it) {
  22522. return {
  22523. ...it,
  22524. identity: {
  22525. type: "changed",
  22526. old: it.identity.__old,
  22527. new: it.identity.__new
  22528. }
  22529. };
  22530. }
  22531. if ("identity__added" in it) {
  22532. const { identity__added, ...others } = it;
  22533. return {
  22534. ...others,
  22535. identity: { type: "added", value: it.identity__added }
  22536. };
  22537. }
  22538. if ("identity__deleted" in it) {
  22539. const { identity__deleted, ...others } = it;
  22540. return {
  22541. ...others,
  22542. identity: { type: "deleted", value: it.identity__deleted }
  22543. };
  22544. }
  22545. return it;
  22546. }).map((it) => {
  22547. if ("notNull" in it) {
  22548. return {
  22549. ...it,
  22550. notNull: {
  22551. type: "changed",
  22552. old: it.notNull.__old,
  22553. new: it.notNull.__new
  22554. }
  22555. };
  22556. }
  22557. if ("notNull__added" in it) {
  22558. const { notNull__added, ...others } = it;
  22559. return {
  22560. ...others,
  22561. notNull: { type: "added", value: it.notNull__added }
  22562. };
  22563. }
  22564. if ("notNull__deleted" in it) {
  22565. const { notNull__deleted, ...others } = it;
  22566. return {
  22567. ...others,
  22568. notNull: { type: "deleted", value: it.notNull__deleted }
  22569. };
  22570. }
  22571. return it;
  22572. }).map((it) => {
  22573. if ("primaryKey" in it) {
  22574. return {
  22575. ...it,
  22576. primaryKey: {
  22577. type: "changed",
  22578. old: it.primaryKey.__old,
  22579. new: it.primaryKey.__new
  22580. }
  22581. };
  22582. }
  22583. if ("primaryKey__added" in it) {
  22584. const { notNull__added, ...others } = it;
  22585. return {
  22586. ...others,
  22587. primaryKey: { type: "added", value: it.primaryKey__added }
  22588. };
  22589. }
  22590. if ("primaryKey__deleted" in it) {
  22591. const { notNull__deleted, ...others } = it;
  22592. return {
  22593. ...others,
  22594. primaryKey: { type: "deleted", value: it.primaryKey__deleted }
  22595. };
  22596. }
  22597. return it;
  22598. }).map((it) => {
  22599. if ("typeSchema" in it) {
  22600. return {
  22601. ...it,
  22602. typeSchema: {
  22603. type: "changed",
  22604. old: it.typeSchema.__old,
  22605. new: it.typeSchema.__new
  22606. }
  22607. };
  22608. }
  22609. if ("typeSchema__added" in it) {
  22610. const { typeSchema__added, ...others } = it;
  22611. return {
  22612. ...others,
  22613. typeSchema: { type: "added", value: it.typeSchema__added }
  22614. };
  22615. }
  22616. if ("typeSchema__deleted" in it) {
  22617. const { typeSchema__deleted, ...others } = it;
  22618. return {
  22619. ...others,
  22620. typeSchema: { type: "deleted", value: it.typeSchema__deleted }
  22621. };
  22622. }
  22623. return it;
  22624. }).map((it) => {
  22625. if ("onUpdate" in it) {
  22626. return {
  22627. ...it,
  22628. onUpdate: {
  22629. type: "changed",
  22630. old: it.onUpdate.__old,
  22631. new: it.onUpdate.__new
  22632. }
  22633. };
  22634. }
  22635. if ("onUpdate__added" in it) {
  22636. const { onUpdate__added, ...others } = it;
  22637. return {
  22638. ...others,
  22639. onUpdate: { type: "added", value: it.onUpdate__added }
  22640. };
  22641. }
  22642. if ("onUpdate__deleted" in it) {
  22643. const { onUpdate__deleted, ...others } = it;
  22644. return {
  22645. ...others,
  22646. onUpdate: { type: "deleted", value: it.onUpdate__deleted }
  22647. };
  22648. }
  22649. return it;
  22650. }).map((it) => {
  22651. if ("autoincrement" in it) {
  22652. return {
  22653. ...it,
  22654. autoincrement: {
  22655. type: "changed",
  22656. old: it.autoincrement.__old,
  22657. new: it.autoincrement.__new
  22658. }
  22659. };
  22660. }
  22661. if ("autoincrement__added" in it) {
  22662. const { autoincrement__added, ...others } = it;
  22663. return {
  22664. ...others,
  22665. autoincrement: { type: "added", value: it.autoincrement__added }
  22666. };
  22667. }
  22668. if ("autoincrement__deleted" in it) {
  22669. const { autoincrement__deleted, ...others } = it;
  22670. return {
  22671. ...others,
  22672. autoincrement: { type: "deleted", value: it.autoincrement__deleted }
  22673. };
  22674. }
  22675. return it;
  22676. }).map((it) => {
  22677. if ("" in it) {
  22678. return {
  22679. ...it,
  22680. autoincrement: {
  22681. type: "changed",
  22682. old: it.autoincrement.__old,
  22683. new: it.autoincrement.__new
  22684. }
  22685. };
  22686. }
  22687. if ("autoincrement__added" in it) {
  22688. const { autoincrement__added, ...others } = it;
  22689. return {
  22690. ...others,
  22691. autoincrement: { type: "added", value: it.autoincrement__added }
  22692. };
  22693. }
  22694. if ("autoincrement__deleted" in it) {
  22695. const { autoincrement__deleted, ...others } = it;
  22696. return {
  22697. ...others,
  22698. autoincrement: { type: "deleted", value: it.autoincrement__deleted }
  22699. };
  22700. }
  22701. return it;
  22702. }).filter(Boolean);
  22703. return result[0];
  22704. };
  22705. }
  22706. });
  22707. // src/sqlgenerator.ts
  22708. function fromJson(statements, dialect6, action, json2) {
  22709. const result = statements.flatMap((statement) => {
  22710. const filtered = convertors.filter((it) => {
  22711. return it.can(statement, dialect6);
  22712. });
  22713. const convertor = filtered.length === 1 ? filtered[0] : void 0;
  22714. if (!convertor) {
  22715. return "";
  22716. }
  22717. return convertor.convert(statement, json2, action);
  22718. }).filter((it) => it !== "");
  22719. return result;
  22720. }
  22721. var parseType, Convertor, PgCreateRoleConvertor, PgDropRoleConvertor, PgRenameRoleConvertor, PgAlterRoleConvertor, PgCreatePolicyConvertor, PgDropPolicyConvertor, PgRenamePolicyConvertor, PgAlterPolicyConvertor, PgCreateIndPolicyConvertor, PgDropIndPolicyConvertor, PgRenameIndPolicyConvertor, PgAlterIndPolicyConvertor, PgEnableRlsConvertor, PgDisableRlsConvertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SingleStoreCreateTableConvertor, SQLiteCreateTableConvertor, PgCreateViewConvertor, MySqlCreateViewConvertor, SqliteCreateViewConvertor, PgDropViewConvertor, MySqlDropViewConvertor, SqliteDropViewConvertor, MySqlAlterViewConvertor, PgRenameViewConvertor, MySqlRenameViewConvertor, PgAlterViewSchemaConvertor, PgAlterViewAddWithOptionConvertor, PgAlterViewDropWithOptionConvertor, PgAlterViewAlterTablespaceConvertor, PgAlterViewAlterUsingConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, PgAlterTableAddCheckConstraintConvertor, PgAlterTableDeleteCheckConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, MySqlAlterTableAddCheckConstraintConvertor, SingleStoreAlterTableAddUniqueConstraintConvertor, SingleStoreAlterTableDropUniqueConstraintConvertor, MySqlAlterTableDeleteCheckConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SingleStoreDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, SingleStoreRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SingleStoreAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SingleStoreAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SingleStoreAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor, SingleStoreAlterTableAddPk, SingleStoreAlterTableDropPk, SingleStoreModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSingleStoreIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SingleStoreDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, SingleStoreRecreateTableConvertor, convertors;
  22722. var init_sqlgenerator = __esm({
  22723. "src/sqlgenerator.ts"() {
  22724. "use strict";
  22725. init_migrate();
  22726. init_mysqlSchema();
  22727. init_pgSchema();
  22728. init_singlestoreSchema();
  22729. init_sqliteSchema();
  22730. init_utils2();
  22731. parseType = (schemaPrefix, type) => {
  22732. const pgNativeTypes = [
  22733. "uuid",
  22734. "smallint",
  22735. "integer",
  22736. "bigint",
  22737. "boolean",
  22738. "text",
  22739. "varchar",
  22740. "serial",
  22741. "bigserial",
  22742. "decimal",
  22743. "numeric",
  22744. "real",
  22745. "json",
  22746. "jsonb",
  22747. "time",
  22748. "time with time zone",
  22749. "time without time zone",
  22750. "time",
  22751. "timestamp",
  22752. "timestamp with time zone",
  22753. "timestamp without time zone",
  22754. "date",
  22755. "interval",
  22756. "bigint",
  22757. "bigserial",
  22758. "double precision",
  22759. "interval year",
  22760. "interval month",
  22761. "interval day",
  22762. "interval hour",
  22763. "interval minute",
  22764. "interval second",
  22765. "interval year to month",
  22766. "interval day to hour",
  22767. "interval day to minute",
  22768. "interval day to second",
  22769. "interval hour to minute",
  22770. "interval hour to second",
  22771. "interval minute to second",
  22772. "char",
  22773. "vector",
  22774. "geometry",
  22775. "halfvec",
  22776. "sparsevec",
  22777. "bit"
  22778. ];
  22779. const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
  22780. const arrayDefinition = (type.match(arrayDefinitionRegex) ?? []).join("");
  22781. const withoutArrayDefinition = type.replace(arrayDefinitionRegex, "");
  22782. return pgNativeTypes.some((it) => type.startsWith(it)) ? `${withoutArrayDefinition}${arrayDefinition}` : `${schemaPrefix}"${withoutArrayDefinition}"${arrayDefinition}`;
  22783. };
  22784. Convertor = class {
  22785. };
  22786. PgCreateRoleConvertor = class extends Convertor {
  22787. can(statement, dialect6) {
  22788. return statement.type === "create_role" && dialect6 === "postgresql";
  22789. }
  22790. convert(statement) {
  22791. return `CREATE ROLE "${statement.name}"${statement.values.createDb || statement.values.createRole || !statement.values.inherit ? ` WITH${statement.values.createDb ? " CREATEDB" : ""}${statement.values.createRole ? " CREATEROLE" : ""}${statement.values.inherit ? "" : " NOINHERIT"}` : ""};`;
  22792. }
  22793. };
  22794. PgDropRoleConvertor = class extends Convertor {
  22795. can(statement, dialect6) {
  22796. return statement.type === "drop_role" && dialect6 === "postgresql";
  22797. }
  22798. convert(statement) {
  22799. return `DROP ROLE "${statement.name}";`;
  22800. }
  22801. };
  22802. PgRenameRoleConvertor = class extends Convertor {
  22803. can(statement, dialect6) {
  22804. return statement.type === "rename_role" && dialect6 === "postgresql";
  22805. }
  22806. convert(statement) {
  22807. return `ALTER ROLE "${statement.nameFrom}" RENAME TO "${statement.nameTo}";`;
  22808. }
  22809. };
  22810. PgAlterRoleConvertor = class extends Convertor {
  22811. can(statement, dialect6) {
  22812. return statement.type === "alter_role" && dialect6 === "postgresql";
  22813. }
  22814. convert(statement) {
  22815. return `ALTER ROLE "${statement.name}"${` WITH${statement.values.createDb ? " CREATEDB" : " NOCREATEDB"}${statement.values.createRole ? " CREATEROLE" : " NOCREATEROLE"}${statement.values.inherit ? " INHERIT" : " NOINHERIT"}`};`;
  22816. }
  22817. };
  22818. PgCreatePolicyConvertor = class extends Convertor {
  22819. can(statement, dialect6) {
  22820. return statement.type === "create_policy" && dialect6 === "postgresql";
  22821. }
  22822. convert(statement) {
  22823. var _a2, _b, _c;
  22824. const policy5 = statement.data;
  22825. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  22826. const usingPart = policy5.using ? ` USING (${policy5.using})` : "";
  22827. const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : "";
  22828. const policyToPart = (_a2 = policy5.to) == null ? void 0 : _a2.map(
  22829. (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"`
  22830. ).join(", ");
  22831. return `CREATE POLICY "${policy5.name}" ON ${tableNameWithSchema} AS ${(_b = policy5.as) == null ? void 0 : _b.toUpperCase()} FOR ${(_c = policy5.for) == null ? void 0 : _c.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
  22832. }
  22833. };
  22834. PgDropPolicyConvertor = class extends Convertor {
  22835. can(statement, dialect6) {
  22836. return statement.type === "drop_policy" && dialect6 === "postgresql";
  22837. }
  22838. convert(statement) {
  22839. const policy5 = statement.data;
  22840. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  22841. return `DROP POLICY "${policy5.name}" ON ${tableNameWithSchema} CASCADE;`;
  22842. }
  22843. };
  22844. PgRenamePolicyConvertor = class extends Convertor {
  22845. can(statement, dialect6) {
  22846. return statement.type === "rename_policy" && dialect6 === "postgresql";
  22847. }
  22848. convert(statement) {
  22849. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  22850. return `ALTER POLICY "${statement.oldName}" ON ${tableNameWithSchema} RENAME TO "${statement.newName}";`;
  22851. }
  22852. };
  22853. PgAlterPolicyConvertor = class extends Convertor {
  22854. can(statement, dialect6) {
  22855. return statement.type === "alter_policy" && dialect6 === "postgresql";
  22856. }
  22857. convert(statement, _dialect, action) {
  22858. const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.newData) : PgSquasher.unsquashPolicy(statement.newData);
  22859. const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.oldData) : PgSquasher.unsquashPolicy(statement.oldData);
  22860. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  22861. const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
  22862. const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK (${oldPolicy.withCheck})` : "";
  22863. return `ALTER POLICY "${oldPolicy.name}" ON ${tableNameWithSchema} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
  22864. }
  22865. };
  22866. PgCreateIndPolicyConvertor = class extends Convertor {
  22867. can(statement, dialect6) {
  22868. return statement.type === "create_ind_policy" && dialect6 === "postgresql";
  22869. }
  22870. convert(statement) {
  22871. var _a2, _b, _c;
  22872. const policy5 = statement.data;
  22873. const usingPart = policy5.using ? ` USING (${policy5.using})` : "";
  22874. const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : "";
  22875. const policyToPart = (_a2 = policy5.to) == null ? void 0 : _a2.map(
  22876. (v6) => ["current_user", "current_role", "session_user", "public"].includes(v6) ? v6 : `"${v6}"`
  22877. ).join(", ");
  22878. return `CREATE POLICY "${policy5.name}" ON ${policy5.on} AS ${(_b = policy5.as) == null ? void 0 : _b.toUpperCase()} FOR ${(_c = policy5.for) == null ? void 0 : _c.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
  22879. }
  22880. };
  22881. PgDropIndPolicyConvertor = class extends Convertor {
  22882. can(statement, dialect6) {
  22883. return statement.type === "drop_ind_policy" && dialect6 === "postgresql";
  22884. }
  22885. convert(statement) {
  22886. const policy5 = statement.data;
  22887. return `DROP POLICY "${policy5.name}" ON ${policy5.on} CASCADE;`;
  22888. }
  22889. };
  22890. PgRenameIndPolicyConvertor = class extends Convertor {
  22891. can(statement, dialect6) {
  22892. return statement.type === "rename_ind_policy" && dialect6 === "postgresql";
  22893. }
  22894. convert(statement) {
  22895. return `ALTER POLICY "${statement.oldName}" ON ${statement.tableKey} RENAME TO "${statement.newName}";`;
  22896. }
  22897. };
  22898. PgAlterIndPolicyConvertor = class extends Convertor {
  22899. can(statement, dialect6) {
  22900. return statement.type === "alter_ind_policy" && dialect6 === "postgresql";
  22901. }
  22902. convert(statement) {
  22903. const newPolicy = statement.newData;
  22904. const oldPolicy = statement.oldData;
  22905. const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
  22906. const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK (${oldPolicy.withCheck})` : "";
  22907. return `ALTER POLICY "${oldPolicy.name}" ON ${oldPolicy.on} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
  22908. }
  22909. };
  22910. PgEnableRlsConvertor = class extends Convertor {
  22911. can(statement, dialect6) {
  22912. return statement.type === "enable_rls" && dialect6 === "postgresql";
  22913. }
  22914. convert(statement) {
  22915. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  22916. return `ALTER TABLE ${tableNameWithSchema} ENABLE ROW LEVEL SECURITY;`;
  22917. }
  22918. };
  22919. PgDisableRlsConvertor = class extends Convertor {
  22920. can(statement, dialect6) {
  22921. return statement.type === "disable_rls" && dialect6 === "postgresql";
  22922. }
  22923. convert(statement) {
  22924. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  22925. return `ALTER TABLE ${tableNameWithSchema} DISABLE ROW LEVEL SECURITY;`;
  22926. }
  22927. };
  22928. PgCreateTableConvertor = class extends Convertor {
  22929. can(statement, dialect6) {
  22930. return statement.type === "create_table" && dialect6 === "postgresql";
  22931. }
  22932. convert(st) {
  22933. const { tableName, schema: schema6, columns, compositePKs, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = st;
  22934. let statement = "";
  22935. const name = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  22936. statement += `CREATE TABLE ${name} (
  22937. `;
  22938. for (let i4 = 0; i4 < columns.length; i4++) {
  22939. const column11 = columns[i4];
  22940. const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : "";
  22941. const notNullStatement = column11.notNull && !column11.identity ? " NOT NULL" : "";
  22942. const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : "";
  22943. const uniqueConstraint6 = column11.isUnique ? ` CONSTRAINT "${column11.uniqueName}" UNIQUE${column11.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}` : "";
  22944. const schemaPrefix = column11.typeSchema && column11.typeSchema !== "public" ? `"${column11.typeSchema}".` : "";
  22945. const type = parseType(schemaPrefix, column11.type);
  22946. const generated = column11.generated;
  22947. const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated == null ? void 0 : generated.as}) STORED` : "";
  22948. const unsquashedIdentity = column11.identity ? PgSquasher.unsquashIdentity(column11.identity) : void 0;
  22949. const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"` : `"${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"`;
  22950. const identity = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
  22951. statement += ` "${column11.name}" ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${uniqueConstraint6}${identity}`;
  22952. statement += i4 === columns.length - 1 ? "" : ",\n";
  22953. }
  22954. if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
  22955. statement += ",\n";
  22956. const compositePK6 = PgSquasher.unsquashPK(compositePKs[0]);
  22957. statement += ` CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK6.columns.join(`","`)}")`;
  22958. }
  22959. if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
  22960. for (const uniqueConstraint6 of uniqueConstraints) {
  22961. statement += ",\n";
  22962. const unsquashedUnique = PgSquasher.unsquashUnique(uniqueConstraint6);
  22963. statement += ` CONSTRAINT "${unsquashedUnique.name}" UNIQUE${unsquashedUnique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashedUnique.columns.join(`","`)}")`;
  22964. }
  22965. }
  22966. if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
  22967. for (const checkConstraint5 of checkConstraints) {
  22968. statement += ",\n";
  22969. const unsquashedCheck = PgSquasher.unsquashCheck(checkConstraint5);
  22970. statement += ` CONSTRAINT "${unsquashedCheck.name}" CHECK (${unsquashedCheck.value})`;
  22971. }
  22972. }
  22973. statement += `
  22974. );`;
  22975. statement += `
  22976. `;
  22977. const enableRls = new PgEnableRlsConvertor().convert({
  22978. type: "enable_rls",
  22979. tableName,
  22980. schema: schema6
  22981. });
  22982. return [statement, ...policies && policies.length > 0 || isRLSEnabled ? [enableRls] : []];
  22983. }
  22984. };
  22985. MySqlCreateTableConvertor = class extends Convertor {
  22986. can(statement, dialect6) {
  22987. return statement.type === "create_table" && dialect6 === "mysql";
  22988. }
  22989. convert(st) {
  22990. var _a2, _b;
  22991. const {
  22992. tableName,
  22993. columns,
  22994. schema: schema6,
  22995. checkConstraints,
  22996. compositePKs,
  22997. uniqueConstraints,
  22998. internals
  22999. } = st;
  23000. let statement = "";
  23001. statement += `CREATE TABLE \`${tableName}\` (
  23002. `;
  23003. for (let i4 = 0; i4 < columns.length; i4++) {
  23004. const column11 = columns[i4];
  23005. const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : "";
  23006. const notNullStatement = column11.notNull ? " NOT NULL" : "";
  23007. const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : "";
  23008. const onUpdateStatement = column11.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  23009. const autoincrementStatement = column11.autoincrement ? " AUTO_INCREMENT" : "";
  23010. const generatedStatement = column11.generated ? ` GENERATED ALWAYS AS (${(_a2 = column11.generated) == null ? void 0 : _a2.as}) ${(_b = column11.generated) == null ? void 0 : _b.type.toUpperCase()}` : "";
  23011. statement += ` \`${column11.name}\` ${column11.type}${autoincrementStatement}${primaryKeyStatement}${generatedStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}`;
  23012. statement += i4 === columns.length - 1 ? "" : ",\n";
  23013. }
  23014. if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
  23015. statement += ",\n";
  23016. const compositePK6 = MySqlSquasher.unsquashPK(compositePKs[0]);
  23017. statement += ` CONSTRAINT \`${st.compositePkName}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`;
  23018. }
  23019. if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
  23020. for (const uniqueConstraint6 of uniqueConstraints) {
  23021. statement += ",\n";
  23022. const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint6);
  23023. const uniqueString = unsquashedUnique.columns.map((it) => {
  23024. var _a3, _b2;
  23025. return (internals == null ? void 0 : internals.indexes) ? ((_b2 = (_a3 = internals == null ? void 0 : internals.indexes[unsquashedUnique.name]) == null ? void 0 : _a3.columns[it]) == null ? void 0 : _b2.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
  23026. }).join(",");
  23027. statement += ` CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
  23028. }
  23029. }
  23030. if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
  23031. for (const checkConstraint5 of checkConstraints) {
  23032. statement += ",\n";
  23033. const unsquashedCheck = MySqlSquasher.unsquashCheck(checkConstraint5);
  23034. statement += ` CONSTRAINT \`${unsquashedCheck.name}\` CHECK(${unsquashedCheck.value})`;
  23035. }
  23036. }
  23037. statement += `
  23038. );`;
  23039. statement += `
  23040. `;
  23041. return statement;
  23042. }
  23043. };
  23044. SingleStoreCreateTableConvertor = class extends Convertor {
  23045. can(statement, dialect6) {
  23046. return statement.type === "create_table" && dialect6 === "singlestore";
  23047. }
  23048. convert(st) {
  23049. var _a2, _b;
  23050. const {
  23051. tableName,
  23052. columns,
  23053. schema: schema6,
  23054. compositePKs,
  23055. uniqueConstraints,
  23056. internals
  23057. } = st;
  23058. let statement = "";
  23059. statement += `CREATE TABLE \`${tableName}\` (
  23060. `;
  23061. for (let i4 = 0; i4 < columns.length; i4++) {
  23062. const column11 = columns[i4];
  23063. const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : "";
  23064. const notNullStatement = column11.notNull ? " NOT NULL" : "";
  23065. const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : "";
  23066. const onUpdateStatement = column11.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  23067. const autoincrementStatement = column11.autoincrement ? " AUTO_INCREMENT" : "";
  23068. const generatedStatement = column11.generated ? ` GENERATED ALWAYS AS (${(_a2 = column11.generated) == null ? void 0 : _a2.as}) ${(_b = column11.generated) == null ? void 0 : _b.type.toUpperCase()}` : "";
  23069. statement += ` \`${column11.name}\` ${column11.type}${autoincrementStatement}${primaryKeyStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}${generatedStatement}`;
  23070. statement += i4 === columns.length - 1 ? "" : ",\n";
  23071. }
  23072. if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
  23073. statement += ",\n";
  23074. const compositePK6 = SingleStoreSquasher.unsquashPK(compositePKs[0]);
  23075. statement += ` CONSTRAINT \`${compositePK6.name}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`;
  23076. }
  23077. if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
  23078. for (const uniqueConstraint6 of uniqueConstraints) {
  23079. statement += ",\n";
  23080. const unsquashedUnique = SingleStoreSquasher.unsquashUnique(uniqueConstraint6);
  23081. const uniqueString = unsquashedUnique.columns.map((it) => {
  23082. var _a3, _b2;
  23083. return (internals == null ? void 0 : internals.indexes) ? ((_b2 = (_a3 = internals == null ? void 0 : internals.indexes[unsquashedUnique.name]) == null ? void 0 : _a3.columns[it]) == null ? void 0 : _b2.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
  23084. }).join(",");
  23085. statement += ` CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
  23086. }
  23087. }
  23088. statement += `
  23089. );`;
  23090. statement += `
  23091. `;
  23092. return statement;
  23093. }
  23094. };
  23095. SQLiteCreateTableConvertor = class extends Convertor {
  23096. can(statement, dialect6) {
  23097. return statement.type === "sqlite_create_table" && (dialect6 === "sqlite" || dialect6 === "turso");
  23098. }
  23099. convert(st) {
  23100. const {
  23101. tableName,
  23102. columns,
  23103. referenceData,
  23104. compositePKs,
  23105. uniqueConstraints,
  23106. checkConstraints
  23107. } = st;
  23108. let statement = "";
  23109. statement += `CREATE TABLE \`${tableName}\` (
  23110. `;
  23111. for (let i4 = 0; i4 < columns.length; i4++) {
  23112. const column11 = columns[i4];
  23113. const primaryKeyStatement = column11.primaryKey ? " PRIMARY KEY" : "";
  23114. const notNullStatement = column11.notNull ? " NOT NULL" : "";
  23115. const defaultStatement = column11.default !== void 0 ? ` DEFAULT ${column11.default}` : "";
  23116. const autoincrementStatement = column11.autoincrement ? " AUTOINCREMENT" : "";
  23117. const generatedStatement = column11.generated ? ` GENERATED ALWAYS AS ${column11.generated.as} ${column11.generated.type.toUpperCase()}` : "";
  23118. statement += " ";
  23119. statement += `\`${column11.name}\` ${column11.type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}`;
  23120. statement += i4 === columns.length - 1 ? "" : ",\n";
  23121. }
  23122. compositePKs.forEach((it) => {
  23123. statement += ",\n ";
  23124. statement += `PRIMARY KEY(${it.map((it2) => `\`${it2}\``).join(", ")})`;
  23125. });
  23126. for (let i4 = 0; i4 < referenceData.length; i4++) {
  23127. const {
  23128. name,
  23129. tableFrom,
  23130. tableTo,
  23131. columnsFrom,
  23132. columnsTo,
  23133. onDelete,
  23134. onUpdate
  23135. } = referenceData[i4];
  23136. const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
  23137. const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
  23138. const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(",");
  23139. const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(",");
  23140. statement += ",";
  23141. statement += "\n ";
  23142. statement += `FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onUpdateStatement}${onDeleteStatement}`;
  23143. }
  23144. if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
  23145. for (const uniqueConstraint6 of uniqueConstraints) {
  23146. statement += ",\n";
  23147. const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint6);
  23148. statement += ` CONSTRAINT ${unsquashedUnique.name} UNIQUE(\`${unsquashedUnique.columns.join(`\`,\``)}\`)`;
  23149. }
  23150. }
  23151. if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
  23152. for (const check2 of checkConstraints) {
  23153. statement += ",\n";
  23154. const { value, name } = SQLiteSquasher.unsquashCheck(check2);
  23155. statement += ` CONSTRAINT "${name}" CHECK(${value})`;
  23156. }
  23157. }
  23158. statement += `
  23159. `;
  23160. statement += `);`;
  23161. statement += `
  23162. `;
  23163. return statement;
  23164. }
  23165. };
  23166. PgCreateViewConvertor = class extends Convertor {
  23167. can(statement, dialect6) {
  23168. return statement.type === "create_view" && dialect6 === "postgresql";
  23169. }
  23170. convert(st) {
  23171. const { definition, name: viewName, schema: schema6, with: withOption, materialized, withNoData, tablespace, using } = st;
  23172. const name = schema6 ? `"${schema6}"."${viewName}"` : `"${viewName}"`;
  23173. let statement = materialized ? `CREATE MATERIALIZED VIEW ${name}` : `CREATE VIEW ${name}`;
  23174. if (using) statement += ` USING "${using}"`;
  23175. const options = [];
  23176. if (withOption) {
  23177. statement += ` WITH (`;
  23178. Object.entries(withOption).forEach(([key, value]) => {
  23179. if (typeof value === "undefined") return;
  23180. options.push(`${key.snake_case()} = ${value}`);
  23181. });
  23182. statement += options.join(", ");
  23183. statement += `)`;
  23184. }
  23185. if (tablespace) statement += ` TABLESPACE ${tablespace}`;
  23186. statement += ` AS (${definition})`;
  23187. if (withNoData) statement += ` WITH NO DATA`;
  23188. statement += `;`;
  23189. return statement;
  23190. }
  23191. };
  23192. MySqlCreateViewConvertor = class extends Convertor {
  23193. can(statement, dialect6) {
  23194. return statement.type === "mysql_create_view" && dialect6 === "mysql";
  23195. }
  23196. convert(st) {
  23197. const { definition, name, algorithm, sqlSecurity, withCheckOption, replace } = st;
  23198. let statement = `CREATE `;
  23199. statement += replace ? `OR REPLACE ` : "";
  23200. statement += algorithm ? `ALGORITHM = ${algorithm}
  23201. ` : "";
  23202. statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
  23203. ` : "";
  23204. statement += `VIEW \`${name}\` AS (${definition})`;
  23205. statement += withCheckOption ? `
  23206. WITH ${withCheckOption} CHECK OPTION` : "";
  23207. statement += ";";
  23208. return statement;
  23209. }
  23210. };
  23211. SqliteCreateViewConvertor = class extends Convertor {
  23212. can(statement, dialect6) {
  23213. return statement.type === "sqlite_create_view" && (dialect6 === "sqlite" || dialect6 === "turso");
  23214. }
  23215. convert(st) {
  23216. const { definition, name } = st;
  23217. return `CREATE VIEW \`${name}\` AS ${definition};`;
  23218. }
  23219. };
  23220. PgDropViewConvertor = class extends Convertor {
  23221. can(statement, dialect6) {
  23222. return statement.type === "drop_view" && dialect6 === "postgresql";
  23223. }
  23224. convert(st) {
  23225. const { name: viewName, schema: schema6, materialized } = st;
  23226. const name = schema6 ? `"${schema6}"."${viewName}"` : `"${viewName}"`;
  23227. return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name};`;
  23228. }
  23229. };
  23230. MySqlDropViewConvertor = class extends Convertor {
  23231. can(statement, dialect6) {
  23232. return statement.type === "drop_view" && dialect6 === "mysql";
  23233. }
  23234. convert(st) {
  23235. const { name } = st;
  23236. return `DROP VIEW \`${name}\`;`;
  23237. }
  23238. };
  23239. SqliteDropViewConvertor = class extends Convertor {
  23240. can(statement, dialect6) {
  23241. return statement.type === "drop_view" && (dialect6 === "sqlite" || dialect6 === "turso");
  23242. }
  23243. convert(st) {
  23244. const { name } = st;
  23245. return `DROP VIEW \`${name}\`;`;
  23246. }
  23247. };
  23248. MySqlAlterViewConvertor = class extends Convertor {
  23249. can(statement, dialect6) {
  23250. return statement.type === "alter_mysql_view" && dialect6 === "mysql";
  23251. }
  23252. convert(st) {
  23253. const { name, algorithm, definition, sqlSecurity, withCheckOption } = st;
  23254. let statement = `ALTER `;
  23255. statement += algorithm ? `ALGORITHM = ${algorithm}
  23256. ` : "";
  23257. statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
  23258. ` : "";
  23259. statement += `VIEW \`${name}\` AS ${definition}`;
  23260. statement += withCheckOption ? `
  23261. WITH ${withCheckOption} CHECK OPTION` : "";
  23262. statement += ";";
  23263. return statement;
  23264. }
  23265. };
  23266. PgRenameViewConvertor = class extends Convertor {
  23267. can(statement, dialect6) {
  23268. return statement.type === "rename_view" && dialect6 === "postgresql";
  23269. }
  23270. convert(st) {
  23271. const { nameFrom: from, nameTo: to, schema: schema6, materialized } = st;
  23272. const nameFrom = `"${schema6}"."${from}"`;
  23273. return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
  23274. }
  23275. };
  23276. MySqlRenameViewConvertor = class extends Convertor {
  23277. can(statement, dialect6) {
  23278. return statement.type === "rename_view" && dialect6 === "mysql";
  23279. }
  23280. convert(st) {
  23281. const { nameFrom: from, nameTo: to } = st;
  23282. return `RENAME TABLE \`${from}\` TO \`${to}\`;`;
  23283. }
  23284. };
  23285. PgAlterViewSchemaConvertor = class extends Convertor {
  23286. can(statement, dialect6) {
  23287. return statement.type === "alter_view_alter_schema" && dialect6 === "postgresql";
  23288. }
  23289. convert(st) {
  23290. const { fromSchema, toSchema, name, materialized } = st;
  23291. const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name}" SET SCHEMA "${toSchema}";`;
  23292. return statement;
  23293. }
  23294. };
  23295. PgAlterViewAddWithOptionConvertor = class extends Convertor {
  23296. can(statement, dialect6) {
  23297. return statement.type === "alter_view_add_with_option" && dialect6 === "postgresql";
  23298. }
  23299. convert(st) {
  23300. const { schema: schema6, with: withOption, name, materialized } = st;
  23301. let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema6}"."${name}" SET (`;
  23302. const options = [];
  23303. Object.entries(withOption).forEach(([key, value]) => {
  23304. options.push(`${key.snake_case()} = ${value}`);
  23305. });
  23306. statement += options.join(", ");
  23307. statement += `);`;
  23308. return statement;
  23309. }
  23310. };
  23311. PgAlterViewDropWithOptionConvertor = class extends Convertor {
  23312. can(statement, dialect6) {
  23313. return statement.type === "alter_view_drop_with_option" && dialect6 === "postgresql";
  23314. }
  23315. convert(st) {
  23316. const { schema: schema6, name, materialized, with: withOptions } = st;
  23317. let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema6}"."${name}" RESET (`;
  23318. const options = [];
  23319. Object.entries(withOptions).forEach(([key, value]) => {
  23320. options.push(`${key.snake_case()}`);
  23321. });
  23322. statement += options.join(", ");
  23323. statement += ");";
  23324. return statement;
  23325. }
  23326. };
  23327. PgAlterViewAlterTablespaceConvertor = class extends Convertor {
  23328. can(statement, dialect6) {
  23329. return statement.type === "alter_view_alter_tablespace" && dialect6 === "postgresql";
  23330. }
  23331. convert(st) {
  23332. const { schema: schema6, name, toTablespace } = st;
  23333. const statement = `ALTER MATERIALIZED VIEW "${schema6}"."${name}" SET TABLESPACE ${toTablespace};`;
  23334. return statement;
  23335. }
  23336. };
  23337. PgAlterViewAlterUsingConvertor = class extends Convertor {
  23338. can(statement, dialect6) {
  23339. return statement.type === "alter_view_alter_using" && dialect6 === "postgresql";
  23340. }
  23341. convert(st) {
  23342. const { schema: schema6, name, toUsing } = st;
  23343. const statement = `ALTER MATERIALIZED VIEW "${schema6}"."${name}" SET ACCESS METHOD "${toUsing}";`;
  23344. return statement;
  23345. }
  23346. };
  23347. PgAlterTableAlterColumnSetGenerated = class extends Convertor {
  23348. can(statement, dialect6) {
  23349. return statement.type === "alter_table_alter_column_set_identity" && dialect6 === "postgresql";
  23350. }
  23351. convert(statement) {
  23352. const { identity, tableName, columnName, schema: schema6 } = statement;
  23353. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23354. const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
  23355. const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"` : `"${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"`;
  23356. const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
  23357. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" ADD${identityStatement};`;
  23358. }
  23359. };
  23360. PgAlterTableAlterColumnDropGenerated = class extends Convertor {
  23361. can(statement, dialect6) {
  23362. return statement.type === "alter_table_alter_column_drop_identity" && dialect6 === "postgresql";
  23363. }
  23364. convert(statement) {
  23365. const { tableName, columnName, schema: schema6 } = statement;
  23366. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23367. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP IDENTITY;`;
  23368. }
  23369. };
  23370. PgAlterTableAlterColumnAlterGenerated = class extends Convertor {
  23371. can(statement, dialect6) {
  23372. return statement.type === "alter_table_alter_column_change_identity" && dialect6 === "postgresql";
  23373. }
  23374. convert(statement) {
  23375. const { identity, oldIdentity, tableName, columnName, schema: schema6 } = statement;
  23376. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23377. const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
  23378. const unsquashedOldIdentity = PgSquasher.unsquashIdentity(oldIdentity);
  23379. const statementsToReturn = [];
  23380. if (unsquashedOldIdentity.type !== unsquashedIdentity.type) {
  23381. statementsToReturn.push(
  23382. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"};`
  23383. );
  23384. }
  23385. if (unsquashedOldIdentity.minValue !== unsquashedIdentity.minValue) {
  23386. statementsToReturn.push(
  23387. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MINVALUE ${unsquashedIdentity.minValue};`
  23388. );
  23389. }
  23390. if (unsquashedOldIdentity.maxValue !== unsquashedIdentity.maxValue) {
  23391. statementsToReturn.push(
  23392. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MAXVALUE ${unsquashedIdentity.maxValue};`
  23393. );
  23394. }
  23395. if (unsquashedOldIdentity.increment !== unsquashedIdentity.increment) {
  23396. statementsToReturn.push(
  23397. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET INCREMENT BY ${unsquashedIdentity.increment};`
  23398. );
  23399. }
  23400. if (unsquashedOldIdentity.startWith !== unsquashedIdentity.startWith) {
  23401. statementsToReturn.push(
  23402. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET START WITH ${unsquashedIdentity.startWith};`
  23403. );
  23404. }
  23405. if (unsquashedOldIdentity.cache !== unsquashedIdentity.cache) {
  23406. statementsToReturn.push(
  23407. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET CACHE ${unsquashedIdentity.cache};`
  23408. );
  23409. }
  23410. if (unsquashedOldIdentity.cycle !== unsquashedIdentity.cycle) {
  23411. statementsToReturn.push(
  23412. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET ${unsquashedIdentity.cycle ? `CYCLE` : "NO CYCLE"};`
  23413. );
  23414. }
  23415. return statementsToReturn;
  23416. }
  23417. };
  23418. PgAlterTableAddUniqueConstraintConvertor = class extends Convertor {
  23419. can(statement, dialect6) {
  23420. return statement.type === "create_unique_constraint" && dialect6 === "postgresql";
  23421. }
  23422. convert(statement) {
  23423. const unsquashed = PgSquasher.unsquashUnique(statement.data);
  23424. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  23425. return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" UNIQUE${unsquashed.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashed.columns.join('","')}");`;
  23426. }
  23427. };
  23428. PgAlterTableDropUniqueConstraintConvertor = class extends Convertor {
  23429. can(statement, dialect6) {
  23430. return statement.type === "delete_unique_constraint" && dialect6 === "postgresql";
  23431. }
  23432. convert(statement) {
  23433. const unsquashed = PgSquasher.unsquashUnique(statement.data);
  23434. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  23435. return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${unsquashed.name}";`;
  23436. }
  23437. };
  23438. PgAlterTableAddCheckConstraintConvertor = class extends Convertor {
  23439. can(statement, dialect6) {
  23440. return statement.type === "create_check_constraint" && dialect6 === "postgresql";
  23441. }
  23442. convert(statement) {
  23443. const unsquashed = PgSquasher.unsquashCheck(statement.data);
  23444. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  23445. return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" CHECK (${unsquashed.value});`;
  23446. }
  23447. };
  23448. PgAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
  23449. can(statement, dialect6) {
  23450. return statement.type === "delete_check_constraint" && dialect6 === "postgresql";
  23451. }
  23452. convert(statement) {
  23453. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  23454. return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
  23455. }
  23456. };
  23457. MySQLAlterTableAddUniqueConstraintConvertor = class extends Convertor {
  23458. can(statement, dialect6) {
  23459. return statement.type === "create_unique_constraint" && dialect6 === "mysql";
  23460. }
  23461. convert(statement) {
  23462. const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
  23463. return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`;
  23464. }
  23465. };
  23466. MySQLAlterTableDropUniqueConstraintConvertor = class extends Convertor {
  23467. can(statement, dialect6) {
  23468. return statement.type === "delete_unique_constraint" && dialect6 === "mysql";
  23469. }
  23470. convert(statement) {
  23471. const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
  23472. return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
  23473. }
  23474. };
  23475. MySqlAlterTableAddCheckConstraintConvertor = class extends Convertor {
  23476. can(statement, dialect6) {
  23477. return statement.type === "create_check_constraint" && dialect6 === "mysql";
  23478. }
  23479. convert(statement) {
  23480. const unsquashed = MySqlSquasher.unsquashCheck(statement.data);
  23481. const { tableName } = statement;
  23482. return `ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` CHECK (${unsquashed.value});`;
  23483. }
  23484. };
  23485. SingleStoreAlterTableAddUniqueConstraintConvertor = class extends Convertor {
  23486. can(statement, dialect6) {
  23487. return statement.type === "create_unique_constraint" && dialect6 === "singlestore";
  23488. }
  23489. convert(statement) {
  23490. const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
  23491. return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`;
  23492. }
  23493. };
  23494. SingleStoreAlterTableDropUniqueConstraintConvertor = class extends Convertor {
  23495. can(statement, dialect6) {
  23496. return statement.type === "delete_unique_constraint" && dialect6 === "singlestore";
  23497. }
  23498. convert(statement) {
  23499. const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
  23500. return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
  23501. }
  23502. };
  23503. MySqlAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
  23504. can(statement, dialect6) {
  23505. return statement.type === "delete_check_constraint" && dialect6 === "mysql";
  23506. }
  23507. convert(statement) {
  23508. const { tableName } = statement;
  23509. return `ALTER TABLE \`${tableName}\` DROP CONSTRAINT \`${statement.constraintName}\`;`;
  23510. }
  23511. };
  23512. CreatePgSequenceConvertor = class extends Convertor {
  23513. can(statement, dialect6) {
  23514. return statement.type === "create_sequence" && dialect6 === "postgresql";
  23515. }
  23516. convert(st) {
  23517. const { name, values, schema: schema6 } = st;
  23518. const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  23519. return `CREATE SEQUENCE ${sequenceWithSchema}${values.increment ? ` INCREMENT BY ${values.increment}` : ""}${values.minValue ? ` MINVALUE ${values.minValue}` : ""}${values.maxValue ? ` MAXVALUE ${values.maxValue}` : ""}${values.startWith ? ` START WITH ${values.startWith}` : ""}${values.cache ? ` CACHE ${values.cache}` : ""}${values.cycle ? ` CYCLE` : ""};`;
  23520. }
  23521. };
  23522. DropPgSequenceConvertor = class extends Convertor {
  23523. can(statement, dialect6) {
  23524. return statement.type === "drop_sequence" && dialect6 === "postgresql";
  23525. }
  23526. convert(st) {
  23527. const { name, schema: schema6 } = st;
  23528. const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  23529. return `DROP SEQUENCE ${sequenceWithSchema};`;
  23530. }
  23531. };
  23532. RenamePgSequenceConvertor = class extends Convertor {
  23533. can(statement, dialect6) {
  23534. return statement.type === "rename_sequence" && dialect6 === "postgresql";
  23535. }
  23536. convert(st) {
  23537. const { nameFrom, nameTo, schema: schema6 } = st;
  23538. const sequenceWithSchemaFrom = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`;
  23539. const sequenceWithSchemaTo = schema6 ? `"${schema6}"."${nameTo}"` : `"${nameTo}"`;
  23540. return `ALTER SEQUENCE ${sequenceWithSchemaFrom} RENAME TO "${nameTo}";`;
  23541. }
  23542. };
  23543. MovePgSequenceConvertor = class extends Convertor {
  23544. can(statement, dialect6) {
  23545. return statement.type === "move_sequence" && dialect6 === "postgresql";
  23546. }
  23547. convert(st) {
  23548. const { schemaFrom, schemaTo, name } = st;
  23549. const sequenceWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`;
  23550. const seqSchemaTo = schemaTo ? `"${schemaTo}"` : `public`;
  23551. return `ALTER SEQUENCE ${sequenceWithSchema} SET SCHEMA ${seqSchemaTo};`;
  23552. }
  23553. };
  23554. AlterPgSequenceConvertor = class extends Convertor {
  23555. can(statement, dialect6) {
  23556. return statement.type === "alter_sequence" && dialect6 === "postgresql";
  23557. }
  23558. convert(st) {
  23559. const { name, schema: schema6, values } = st;
  23560. const { increment, minValue, maxValue, startWith, cache: cache3, cycle } = values;
  23561. const sequenceWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  23562. return `ALTER SEQUENCE ${sequenceWithSchema}${increment ? ` INCREMENT BY ${increment}` : ""}${minValue ? ` MINVALUE ${minValue}` : ""}${maxValue ? ` MAXVALUE ${maxValue}` : ""}${startWith ? ` START WITH ${startWith}` : ""}${cache3 ? ` CACHE ${cache3}` : ""}${cycle ? ` CYCLE` : ""};`;
  23563. }
  23564. };
  23565. CreateTypeEnumConvertor = class extends Convertor {
  23566. can(statement) {
  23567. return statement.type === "create_type_enum";
  23568. }
  23569. convert(st) {
  23570. const { name, values, schema: schema6 } = st;
  23571. const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  23572. let valuesStatement = "(";
  23573. valuesStatement += values.map((it) => `'${escapeSingleQuotes(it)}'`).join(", ");
  23574. valuesStatement += ")";
  23575. let statement = `CREATE TYPE ${enumNameWithSchema} AS ENUM${valuesStatement};`;
  23576. return statement;
  23577. }
  23578. };
  23579. DropTypeEnumConvertor = class extends Convertor {
  23580. can(statement) {
  23581. return statement.type === "drop_type_enum";
  23582. }
  23583. convert(st) {
  23584. const { name, schema: schema6 } = st;
  23585. const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  23586. let statement = `DROP TYPE ${enumNameWithSchema};`;
  23587. return statement;
  23588. }
  23589. };
  23590. AlterTypeAddValueConvertor = class extends Convertor {
  23591. can(statement) {
  23592. return statement.type === "alter_type_add_value";
  23593. }
  23594. convert(st) {
  23595. const { name, schema: schema6, value, before } = st;
  23596. const enumNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  23597. return `ALTER TYPE ${enumNameWithSchema} ADD VALUE '${value}'${before.length ? ` BEFORE '${before}'` : ""};`;
  23598. }
  23599. };
  23600. AlterTypeSetSchemaConvertor = class extends Convertor {
  23601. can(statement) {
  23602. return statement.type === "move_type_enum";
  23603. }
  23604. convert(st) {
  23605. const { name, schemaFrom, schemaTo } = st;
  23606. const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name}"` : `"${name}"`;
  23607. return `ALTER TYPE ${enumNameWithSchema} SET SCHEMA "${schemaTo}";`;
  23608. }
  23609. };
  23610. AlterRenameTypeConvertor = class extends Convertor {
  23611. can(statement) {
  23612. return statement.type === "rename_type_enum";
  23613. }
  23614. convert(st) {
  23615. const { nameTo, nameFrom, schema: schema6 } = st;
  23616. const enumNameWithSchema = schema6 ? `"${schema6}"."${nameFrom}"` : `"${nameFrom}"`;
  23617. return `ALTER TYPE ${enumNameWithSchema} RENAME TO "${nameTo}";`;
  23618. }
  23619. };
  23620. AlterTypeDropValueConvertor = class extends Convertor {
  23621. can(statement) {
  23622. return statement.type === "alter_type_drop_value";
  23623. }
  23624. convert(st) {
  23625. const { columnsWithEnum, name, newValues, enumSchema: enumSchema4 } = st;
  23626. const statements = [];
  23627. for (const withEnum of columnsWithEnum) {
  23628. const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`;
  23629. statements.push(
  23630. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;`
  23631. );
  23632. if (withEnum.default) {
  23633. statements.push(
  23634. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::text;`
  23635. );
  23636. }
  23637. }
  23638. statements.push(new DropTypeEnumConvertor().convert({ name, schema: enumSchema4, type: "drop_type_enum" }));
  23639. statements.push(new CreateTypeEnumConvertor().convert({
  23640. name,
  23641. schema: enumSchema4,
  23642. values: newValues,
  23643. type: "create_type_enum"
  23644. }));
  23645. for (const withEnum of columnsWithEnum) {
  23646. const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`;
  23647. const parsedType = parseType(`"${enumSchema4}".`, withEnum.columnType);
  23648. if (withEnum.default) {
  23649. statements.push(
  23650. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::${parsedType};`
  23651. );
  23652. }
  23653. statements.push(
  23654. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE ${parsedType} USING "${withEnum.column}"::${parsedType};`
  23655. );
  23656. }
  23657. return statements;
  23658. }
  23659. };
  23660. PgDropTableConvertor = class extends Convertor {
  23661. can(statement, dialect6) {
  23662. return statement.type === "drop_table" && dialect6 === "postgresql";
  23663. }
  23664. convert(statement, _d, action) {
  23665. const { tableName, schema: schema6, policies } = statement;
  23666. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23667. const dropPolicyConvertor = new PgDropPolicyConvertor();
  23668. const droppedPolicies = (policies == null ? void 0 : policies.map((p3) => {
  23669. return dropPolicyConvertor.convert({
  23670. type: "drop_policy",
  23671. tableName,
  23672. data: action === "push" ? PgSquasher.unsquashPolicyPush(p3) : PgSquasher.unsquashPolicy(p3),
  23673. schema: schema6
  23674. });
  23675. })) ?? [];
  23676. return [
  23677. ...droppedPolicies,
  23678. `DROP TABLE ${tableNameWithSchema} CASCADE;`
  23679. ];
  23680. }
  23681. };
  23682. MySQLDropTableConvertor = class extends Convertor {
  23683. can(statement, dialect6) {
  23684. return statement.type === "drop_table" && dialect6 === "mysql";
  23685. }
  23686. convert(statement) {
  23687. const { tableName } = statement;
  23688. return `DROP TABLE \`${tableName}\`;`;
  23689. }
  23690. };
  23691. SingleStoreDropTableConvertor = class extends Convertor {
  23692. can(statement, dialect6) {
  23693. return statement.type === "drop_table" && dialect6 === "singlestore";
  23694. }
  23695. convert(statement) {
  23696. const { tableName } = statement;
  23697. return `DROP TABLE \`${tableName}\`;`;
  23698. }
  23699. };
  23700. SQLiteDropTableConvertor = class extends Convertor {
  23701. can(statement, dialect6) {
  23702. return statement.type === "drop_table" && (dialect6 === "sqlite" || dialect6 === "turso");
  23703. }
  23704. convert(statement) {
  23705. const { tableName } = statement;
  23706. return `DROP TABLE \`${tableName}\`;`;
  23707. }
  23708. };
  23709. PgRenameTableConvertor = class extends Convertor {
  23710. can(statement, dialect6) {
  23711. return statement.type === "rename_table" && dialect6 === "postgresql";
  23712. }
  23713. convert(statement) {
  23714. const { tableNameFrom, tableNameTo, toSchema, fromSchema } = statement;
  23715. const from = fromSchema ? `"${fromSchema}"."${tableNameFrom}"` : `"${tableNameFrom}"`;
  23716. const to = `"${tableNameTo}"`;
  23717. return `ALTER TABLE ${from} RENAME TO ${to};`;
  23718. }
  23719. };
  23720. SqliteRenameTableConvertor = class extends Convertor {
  23721. can(statement, dialect6) {
  23722. return statement.type === "rename_table" && (dialect6 === "sqlite" || dialect6 === "turso");
  23723. }
  23724. convert(statement) {
  23725. const { tableNameFrom, tableNameTo } = statement;
  23726. return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
  23727. }
  23728. };
  23729. MySqlRenameTableConvertor = class extends Convertor {
  23730. can(statement, dialect6) {
  23731. return statement.type === "rename_table" && dialect6 === "mysql";
  23732. }
  23733. convert(statement) {
  23734. const { tableNameFrom, tableNameTo } = statement;
  23735. return `RENAME TABLE \`${tableNameFrom}\` TO \`${tableNameTo}\`;`;
  23736. }
  23737. };
  23738. SingleStoreRenameTableConvertor = class extends Convertor {
  23739. can(statement, dialect6) {
  23740. return statement.type === "rename_table" && dialect6 === "singlestore";
  23741. }
  23742. convert(statement) {
  23743. const { tableNameFrom, tableNameTo } = statement;
  23744. return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
  23745. }
  23746. };
  23747. PgAlterTableRenameColumnConvertor = class extends Convertor {
  23748. can(statement, dialect6) {
  23749. return statement.type === "alter_table_rename_column" && dialect6 === "postgresql";
  23750. }
  23751. convert(statement) {
  23752. const { tableName, oldColumnName, newColumnName, schema: schema6 } = statement;
  23753. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23754. return `ALTER TABLE ${tableNameWithSchema} RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
  23755. }
  23756. };
  23757. MySqlAlterTableRenameColumnConvertor = class extends Convertor {
  23758. can(statement, dialect6) {
  23759. return statement.type === "alter_table_rename_column" && dialect6 === "mysql";
  23760. }
  23761. convert(statement) {
  23762. const { tableName, oldColumnName, newColumnName } = statement;
  23763. return `ALTER TABLE \`${tableName}\` RENAME COLUMN \`${oldColumnName}\` TO \`${newColumnName}\`;`;
  23764. }
  23765. };
  23766. SingleStoreAlterTableRenameColumnConvertor = class extends Convertor {
  23767. can(statement, dialect6) {
  23768. return statement.type === "alter_table_rename_column" && dialect6 === "singlestore";
  23769. }
  23770. convert(statement) {
  23771. const { tableName, oldColumnName, newColumnName } = statement;
  23772. return `ALTER TABLE \`${tableName}\` CHANGE \`${oldColumnName}\` \`${newColumnName}\`;`;
  23773. }
  23774. };
  23775. SQLiteAlterTableRenameColumnConvertor = class extends Convertor {
  23776. can(statement, dialect6) {
  23777. return statement.type === "alter_table_rename_column" && (dialect6 === "sqlite" || dialect6 === "turso");
  23778. }
  23779. convert(statement) {
  23780. const { tableName, oldColumnName, newColumnName } = statement;
  23781. return `ALTER TABLE \`${tableName}\` RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
  23782. }
  23783. };
  23784. PgAlterTableDropColumnConvertor = class extends Convertor {
  23785. can(statement, dialect6) {
  23786. return statement.type === "alter_table_drop_column" && dialect6 === "postgresql";
  23787. }
  23788. convert(statement) {
  23789. const { tableName, columnName, schema: schema6 } = statement;
  23790. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23791. return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN "${columnName}";`;
  23792. }
  23793. };
  23794. MySqlAlterTableDropColumnConvertor = class extends Convertor {
  23795. can(statement, dialect6) {
  23796. return statement.type === "alter_table_drop_column" && dialect6 === "mysql";
  23797. }
  23798. convert(statement) {
  23799. const { tableName, columnName } = statement;
  23800. return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
  23801. }
  23802. };
  23803. SingleStoreAlterTableDropColumnConvertor = class extends Convertor {
  23804. can(statement, dialect6) {
  23805. return statement.type === "alter_table_drop_column" && dialect6 === "singlestore";
  23806. }
  23807. convert(statement) {
  23808. const { tableName, columnName } = statement;
  23809. return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
  23810. }
  23811. };
  23812. SQLiteAlterTableDropColumnConvertor = class extends Convertor {
  23813. can(statement, dialect6) {
  23814. return statement.type === "alter_table_drop_column" && (dialect6 === "sqlite" || dialect6 === "turso");
  23815. }
  23816. convert(statement) {
  23817. const { tableName, columnName } = statement;
  23818. return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
  23819. }
  23820. };
  23821. PgAlterTableAddColumnConvertor = class extends Convertor {
  23822. can(statement, dialect6) {
  23823. return statement.type === "alter_table_add_column" && dialect6 === "postgresql";
  23824. }
  23825. convert(statement) {
  23826. const { tableName, column: column11, schema: schema6 } = statement;
  23827. const { name, type, notNull, generated, primaryKey, identity } = column11;
  23828. const primaryKeyStatement = primaryKey ? " PRIMARY KEY" : "";
  23829. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23830. const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""}`;
  23831. const schemaPrefix = column11.typeSchema && column11.typeSchema !== "public" ? `"${column11.typeSchema}".` : "";
  23832. const fixedType = parseType(schemaPrefix, column11.type);
  23833. const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
  23834. const unsquashedIdentity = identity ? PgSquasher.unsquashIdentity(identity) : void 0;
  23835. const identityWithSchema = schema6 ? `"${schema6}"."${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"` : `"${unsquashedIdentity == null ? void 0 : unsquashedIdentity.name}"`;
  23836. const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
  23837. const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated == null ? void 0 : generated.as}) STORED` : "";
  23838. return `ALTER TABLE ${tableNameWithSchema} ADD COLUMN "${name}" ${fixedType}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${identityStatement};`;
  23839. }
  23840. };
  23841. MySqlAlterTableAddColumnConvertor = class extends Convertor {
  23842. can(statement, dialect6) {
  23843. return statement.type === "alter_table_add_column" && dialect6 === "mysql";
  23844. }
  23845. convert(statement) {
  23846. const { tableName, column: column11 } = statement;
  23847. const {
  23848. name,
  23849. type,
  23850. notNull,
  23851. primaryKey,
  23852. autoincrement,
  23853. onUpdate,
  23854. generated
  23855. } = column11;
  23856. const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""}`;
  23857. const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
  23858. const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
  23859. const autoincrementStatement = `${autoincrement ? " AUTO_INCREMENT" : ""}`;
  23860. const onUpdateStatement = `${onUpdate ? " ON UPDATE CURRENT_TIMESTAMP" : ""}`;
  23861. const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated == null ? void 0 : generated.as}) ${generated == null ? void 0 : generated.type.toUpperCase()}` : "";
  23862. return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}${onUpdateStatement};`;
  23863. }
  23864. };
  23865. SingleStoreAlterTableAddColumnConvertor = class extends Convertor {
  23866. can(statement, dialect6) {
  23867. return statement.type === "alter_table_add_column" && dialect6 === "singlestore";
  23868. }
  23869. convert(statement) {
  23870. const { tableName, column: column11 } = statement;
  23871. const {
  23872. name,
  23873. type,
  23874. notNull,
  23875. primaryKey,
  23876. autoincrement,
  23877. onUpdate,
  23878. generated
  23879. } = column11;
  23880. const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""}`;
  23881. const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
  23882. const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
  23883. const autoincrementStatement = `${autoincrement ? " AUTO_INCREMENT" : ""}`;
  23884. const onUpdateStatement = `${onUpdate ? " ON UPDATE CURRENT_TIMESTAMP" : ""}`;
  23885. const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated == null ? void 0 : generated.as}) ${generated == null ? void 0 : generated.type.toUpperCase()}` : "";
  23886. return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${notNullStatement}${onUpdateStatement}${generatedStatement};`;
  23887. }
  23888. };
  23889. SQLiteAlterTableAddColumnConvertor = class extends Convertor {
  23890. can(statement, dialect6) {
  23891. return statement.type === "sqlite_alter_table_add_column" && (dialect6 === "sqlite" || dialect6 === "turso");
  23892. }
  23893. convert(statement) {
  23894. const { tableName, column: column11, referenceData } = statement;
  23895. const { name, type, notNull, primaryKey, generated } = column11;
  23896. const defaultStatement = `${column11.default !== void 0 ? ` DEFAULT ${column11.default}` : ""}`;
  23897. const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
  23898. const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
  23899. const referenceAsObject = referenceData ? SQLiteSquasher.unsquashFK(referenceData) : void 0;
  23900. const referenceStatement = `${referenceAsObject ? ` REFERENCES ${referenceAsObject.tableTo}(${referenceAsObject.columnsTo})` : ""}`;
  23901. const generatedStatement = generated ? ` GENERATED ALWAYS AS ${generated.as} ${generated.type.toUpperCase()}` : "";
  23902. return `ALTER TABLE \`${tableName}\` ADD \`${name}\` ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${referenceStatement};`;
  23903. }
  23904. };
  23905. PgAlterTableAlterColumnSetTypeConvertor = class extends Convertor {
  23906. can(statement, dialect6) {
  23907. return statement.type === "pg_alter_table_alter_column_set_type" && dialect6 === "postgresql";
  23908. }
  23909. convert(statement) {
  23910. const { tableName, columnName, newDataType, schema: schema6, oldDataType, columnDefault, typeSchema } = statement;
  23911. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23912. const statements = [];
  23913. const type = parseType(`"${typeSchema}".`, newDataType.name);
  23914. if (!oldDataType.isEnum && !newDataType.isEnum) {
  23915. statements.push(
  23916. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};`
  23917. );
  23918. if (columnDefault) {
  23919. statements.push(
  23920. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
  23921. );
  23922. }
  23923. }
  23924. if (oldDataType.isEnum && !newDataType.isEnum) {
  23925. statements.push(
  23926. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};`
  23927. );
  23928. if (columnDefault) {
  23929. statements.push(
  23930. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
  23931. );
  23932. }
  23933. }
  23934. if (!oldDataType.isEnum && newDataType.isEnum) {
  23935. if (columnDefault) {
  23936. statements.push(
  23937. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault}::${type};`
  23938. );
  23939. }
  23940. statements.push(
  23941. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::${type};`
  23942. );
  23943. }
  23944. if (oldDataType.isEnum && newDataType.isEnum) {
  23945. const alterType = `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::text::${type};`;
  23946. if (newDataType.name !== oldDataType.name && columnDefault) {
  23947. statements.push(
  23948. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`,
  23949. alterType,
  23950. `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
  23951. );
  23952. } else {
  23953. statements.push(alterType);
  23954. }
  23955. }
  23956. return statements;
  23957. }
  23958. };
  23959. PgAlterTableAlterColumnSetDefaultConvertor = class extends Convertor {
  23960. can(statement, dialect6) {
  23961. return statement.type === "alter_table_alter_column_set_default" && dialect6 === "postgresql";
  23962. }
  23963. convert(statement) {
  23964. const { tableName, columnName, schema: schema6 } = statement;
  23965. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23966. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${statement.newDefaultValue};`;
  23967. }
  23968. };
  23969. PgAlterTableAlterColumnDropDefaultConvertor = class extends Convertor {
  23970. can(statement, dialect6) {
  23971. return statement.type === "alter_table_alter_column_drop_default" && dialect6 === "postgresql";
  23972. }
  23973. convert(statement) {
  23974. const { tableName, columnName, schema: schema6 } = statement;
  23975. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23976. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`;
  23977. }
  23978. };
  23979. PgAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
  23980. can(statement, dialect6) {
  23981. return statement.type === "alter_table_alter_column_drop_generated" && dialect6 === "postgresql";
  23982. }
  23983. convert(statement) {
  23984. const { tableName, columnName, schema: schema6 } = statement;
  23985. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  23986. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP EXPRESSION;`;
  23987. }
  23988. };
  23989. PgAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
  23990. can(statement, dialect6) {
  23991. return statement.type === "alter_table_alter_column_set_generated" && dialect6 === "postgresql";
  23992. }
  23993. convert(statement) {
  23994. const {
  23995. tableName,
  23996. columnName,
  23997. schema: schema6,
  23998. columnNotNull: notNull,
  23999. columnDefault,
  24000. columnOnUpdate,
  24001. columnAutoIncrement,
  24002. columnPk,
  24003. columnGenerated
  24004. } = statement;
  24005. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  24006. const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
  24007. schema: schema6,
  24008. tableName,
  24009. column: {
  24010. name: columnName,
  24011. type: statement.newDataType,
  24012. notNull,
  24013. default: columnDefault,
  24014. onUpdate: columnOnUpdate,
  24015. autoincrement: columnAutoIncrement,
  24016. primaryKey: columnPk,
  24017. generated: columnGenerated
  24018. },
  24019. type: "alter_table_add_column"
  24020. });
  24021. return [
  24022. `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`,
  24023. addColumnStatement
  24024. ];
  24025. }
  24026. };
  24027. PgAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
  24028. can(statement, dialect6) {
  24029. return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "postgresql";
  24030. }
  24031. convert(statement) {
  24032. const {
  24033. tableName,
  24034. columnName,
  24035. schema: schema6,
  24036. columnNotNull: notNull,
  24037. columnDefault,
  24038. columnOnUpdate,
  24039. columnAutoIncrement,
  24040. columnPk,
  24041. columnGenerated
  24042. } = statement;
  24043. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  24044. const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
  24045. schema: schema6,
  24046. tableName,
  24047. column: {
  24048. name: columnName,
  24049. type: statement.newDataType,
  24050. notNull,
  24051. default: columnDefault,
  24052. onUpdate: columnOnUpdate,
  24053. autoincrement: columnAutoIncrement,
  24054. primaryKey: columnPk,
  24055. generated: columnGenerated
  24056. },
  24057. type: "alter_table_add_column"
  24058. });
  24059. return [
  24060. `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`,
  24061. addColumnStatement
  24062. ];
  24063. }
  24064. };
  24065. SqliteAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
  24066. can(statement, dialect6) {
  24067. return statement.type === "alter_table_alter_column_drop_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
  24068. }
  24069. convert(statement) {
  24070. const {
  24071. tableName,
  24072. columnName,
  24073. schema: schema6,
  24074. columnDefault,
  24075. columnOnUpdate,
  24076. columnAutoIncrement,
  24077. columnPk,
  24078. columnGenerated,
  24079. columnNotNull
  24080. } = statement;
  24081. const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
  24082. {
  24083. tableName,
  24084. column: {
  24085. name: columnName,
  24086. type: statement.newDataType,
  24087. notNull: columnNotNull,
  24088. default: columnDefault,
  24089. onUpdate: columnOnUpdate,
  24090. autoincrement: columnAutoIncrement,
  24091. primaryKey: columnPk,
  24092. generated: columnGenerated
  24093. },
  24094. type: "sqlite_alter_table_add_column"
  24095. }
  24096. );
  24097. const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
  24098. tableName,
  24099. columnName,
  24100. schema: schema6,
  24101. type: "alter_table_drop_column"
  24102. });
  24103. return [dropColumnStatement, addColumnStatement];
  24104. }
  24105. };
  24106. SqliteAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
  24107. can(statement, dialect6) {
  24108. return statement.type === "alter_table_alter_column_set_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
  24109. }
  24110. convert(statement) {
  24111. const {
  24112. tableName,
  24113. columnName,
  24114. schema: schema6,
  24115. columnNotNull: notNull,
  24116. columnDefault,
  24117. columnOnUpdate,
  24118. columnAutoIncrement,
  24119. columnPk,
  24120. columnGenerated
  24121. } = statement;
  24122. const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
  24123. {
  24124. tableName,
  24125. column: {
  24126. name: columnName,
  24127. type: statement.newDataType,
  24128. notNull,
  24129. default: columnDefault,
  24130. onUpdate: columnOnUpdate,
  24131. autoincrement: columnAutoIncrement,
  24132. primaryKey: columnPk,
  24133. generated: columnGenerated
  24134. },
  24135. type: "sqlite_alter_table_add_column"
  24136. }
  24137. );
  24138. const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
  24139. tableName,
  24140. columnName,
  24141. schema: schema6,
  24142. type: "alter_table_drop_column"
  24143. });
  24144. return [dropColumnStatement, addColumnStatement];
  24145. }
  24146. };
  24147. SqliteAlterTableAlterColumnAlterGeneratedConvertor = class extends Convertor {
  24148. can(statement, dialect6) {
  24149. return statement.type === "alter_table_alter_column_alter_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
  24150. }
  24151. convert(statement) {
  24152. const {
  24153. tableName,
  24154. columnName,
  24155. schema: schema6,
  24156. columnNotNull,
  24157. columnDefault,
  24158. columnOnUpdate,
  24159. columnAutoIncrement,
  24160. columnPk,
  24161. columnGenerated
  24162. } = statement;
  24163. const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
  24164. {
  24165. tableName,
  24166. column: {
  24167. name: columnName,
  24168. type: statement.newDataType,
  24169. notNull: columnNotNull,
  24170. default: columnDefault,
  24171. onUpdate: columnOnUpdate,
  24172. autoincrement: columnAutoIncrement,
  24173. primaryKey: columnPk,
  24174. generated: columnGenerated
  24175. },
  24176. type: "sqlite_alter_table_add_column"
  24177. }
  24178. );
  24179. const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
  24180. tableName,
  24181. columnName,
  24182. schema: schema6,
  24183. type: "alter_table_drop_column"
  24184. });
  24185. return [dropColumnStatement, addColumnStatement];
  24186. }
  24187. };
  24188. MySqlAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
  24189. can(statement, dialect6) {
  24190. return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "mysql";
  24191. }
  24192. convert(statement) {
  24193. const {
  24194. tableName,
  24195. columnName,
  24196. schema: schema6,
  24197. columnNotNull: notNull,
  24198. columnDefault,
  24199. columnOnUpdate,
  24200. columnAutoIncrement,
  24201. columnPk,
  24202. columnGenerated
  24203. } = statement;
  24204. const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``;
  24205. const addColumnStatement = new MySqlAlterTableAddColumnConvertor().convert({
  24206. schema: schema6,
  24207. tableName,
  24208. column: {
  24209. name: columnName,
  24210. type: statement.newDataType,
  24211. notNull,
  24212. default: columnDefault,
  24213. onUpdate: columnOnUpdate,
  24214. autoincrement: columnAutoIncrement,
  24215. primaryKey: columnPk,
  24216. generated: columnGenerated
  24217. },
  24218. type: "alter_table_add_column"
  24219. });
  24220. return [
  24221. `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`,
  24222. addColumnStatement
  24223. ];
  24224. }
  24225. };
  24226. MySqlAlterTableAddPk = class extends Convertor {
  24227. can(statement, dialect6) {
  24228. return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "mysql";
  24229. }
  24230. convert(statement) {
  24231. return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
  24232. }
  24233. };
  24234. MySqlAlterTableDropPk = class extends Convertor {
  24235. can(statement, dialect6) {
  24236. return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "mysql";
  24237. }
  24238. convert(statement) {
  24239. return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
  24240. }
  24241. };
  24242. LibSQLModifyColumn = class extends Convertor {
  24243. can(statement, dialect6) {
  24244. return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") && dialect6 === "turso";
  24245. }
  24246. convert(statement, json2) {
  24247. const { tableName, columnName } = statement;
  24248. let columnType = ``;
  24249. let columnDefault = "";
  24250. let columnNotNull = "";
  24251. const sqlStatements = [];
  24252. const indexes = [];
  24253. for (const table6 of Object.values(json2.tables)) {
  24254. for (const index6 of Object.values(table6.indexes)) {
  24255. const unsquashed = SQLiteSquasher.unsquashIdx(index6);
  24256. sqlStatements.push(`DROP INDEX "${unsquashed.name}";`);
  24257. indexes.push({ ...unsquashed, tableName: table6.name });
  24258. }
  24259. }
  24260. switch (statement.type) {
  24261. case "alter_table_alter_column_set_type":
  24262. columnType = ` ${statement.newDataType}`;
  24263. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24264. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24265. break;
  24266. case "alter_table_alter_column_drop_notnull":
  24267. columnType = ` ${statement.newDataType}`;
  24268. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24269. columnNotNull = "";
  24270. break;
  24271. case "alter_table_alter_column_set_notnull":
  24272. columnType = ` ${statement.newDataType}`;
  24273. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24274. columnNotNull = ` NOT NULL`;
  24275. break;
  24276. case "alter_table_alter_column_set_default":
  24277. columnType = ` ${statement.newDataType}`;
  24278. columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
  24279. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24280. break;
  24281. case "alter_table_alter_column_drop_default":
  24282. columnType = ` ${statement.newDataType}`;
  24283. columnDefault = "";
  24284. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24285. break;
  24286. }
  24287. columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
  24288. sqlStatements.push(
  24289. `ALTER TABLE \`${tableName}\` ALTER COLUMN "${columnName}" TO "${columnName}"${columnType}${columnNotNull}${columnDefault};`
  24290. );
  24291. for (const index6 of indexes) {
  24292. const indexPart = index6.isUnique ? "UNIQUE INDEX" : "INDEX";
  24293. const whereStatement = index6.where ? ` WHERE ${index6.where}` : "";
  24294. const uniqueString = index6.columns.map((it) => `\`${it}\``).join(",");
  24295. const tableName2 = index6.tableName;
  24296. sqlStatements.push(
  24297. `CREATE ${indexPart} \`${index6.name}\` ON \`${tableName2}\` (${uniqueString})${whereStatement};`
  24298. );
  24299. }
  24300. return sqlStatements;
  24301. }
  24302. };
  24303. MySqlModifyColumn = class extends Convertor {
  24304. can(statement, dialect6) {
  24305. return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "mysql";
  24306. }
  24307. convert(statement) {
  24308. var _a2, _b, _c, _d, _e, _f, _g;
  24309. const { tableName, columnName } = statement;
  24310. let columnType = ``;
  24311. let columnDefault = "";
  24312. let columnNotNull = "";
  24313. let columnOnUpdate = "";
  24314. let columnAutoincrement = "";
  24315. let primaryKey = statement.columnPk ? " PRIMARY KEY" : "";
  24316. let columnGenerated = "";
  24317. if (statement.type === "alter_table_alter_column_drop_notnull") {
  24318. columnType = ` ${statement.newDataType}`;
  24319. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24320. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24321. columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24322. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24323. } else if (statement.type === "alter_table_alter_column_set_notnull") {
  24324. columnNotNull = ` NOT NULL`;
  24325. columnType = ` ${statement.newDataType}`;
  24326. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24327. columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24328. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24329. } else if (statement.type === "alter_table_alter_column_drop_on_update") {
  24330. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24331. columnType = ` ${statement.newDataType}`;
  24332. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24333. columnOnUpdate = "";
  24334. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24335. } else if (statement.type === "alter_table_alter_column_set_on_update") {
  24336. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24337. columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`;
  24338. columnType = ` ${statement.newDataType}`;
  24339. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24340. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24341. } else if (statement.type === "alter_table_alter_column_set_autoincrement") {
  24342. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24343. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24344. columnType = ` ${statement.newDataType}`;
  24345. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24346. columnAutoincrement = " AUTO_INCREMENT";
  24347. } else if (statement.type === "alter_table_alter_column_drop_autoincrement") {
  24348. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24349. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24350. columnType = ` ${statement.newDataType}`;
  24351. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24352. columnAutoincrement = "";
  24353. } else if (statement.type === "alter_table_alter_column_set_default") {
  24354. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24355. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24356. columnType = ` ${statement.newDataType}`;
  24357. columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
  24358. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24359. } else if (statement.type === "alter_table_alter_column_drop_default") {
  24360. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24361. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24362. columnType = ` ${statement.newDataType}`;
  24363. columnDefault = "";
  24364. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24365. } else if (statement.type === "alter_table_alter_column_set_generated") {
  24366. columnType = ` ${statement.newDataType}`;
  24367. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24368. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24369. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24370. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24371. if (((_a2 = statement.columnGenerated) == null ? void 0 : _a2.type) === "virtual") {
  24372. return [
  24373. new MySqlAlterTableDropColumnConvertor().convert({
  24374. type: "alter_table_drop_column",
  24375. tableName: statement.tableName,
  24376. columnName: statement.columnName,
  24377. schema: statement.schema
  24378. }),
  24379. new MySqlAlterTableAddColumnConvertor().convert({
  24380. tableName,
  24381. column: {
  24382. name: columnName,
  24383. type: statement.newDataType,
  24384. notNull: statement.columnNotNull,
  24385. default: statement.columnDefault,
  24386. onUpdate: statement.columnOnUpdate,
  24387. autoincrement: statement.columnAutoIncrement,
  24388. primaryKey: statement.columnPk,
  24389. generated: statement.columnGenerated
  24390. },
  24391. schema: statement.schema,
  24392. type: "alter_table_add_column"
  24393. })
  24394. ];
  24395. } else {
  24396. columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${(_b = statement.columnGenerated) == null ? void 0 : _b.as}) ${(_c = statement.columnGenerated) == null ? void 0 : _c.type.toUpperCase()}` : "";
  24397. }
  24398. } else if (statement.type === "alter_table_alter_column_drop_generated") {
  24399. columnType = ` ${statement.newDataType}`;
  24400. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24401. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24402. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24403. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24404. if (((_e = (_d = statement.oldColumn) == null ? void 0 : _d.generated) == null ? void 0 : _e.type) === "virtual") {
  24405. return [
  24406. new MySqlAlterTableDropColumnConvertor().convert({
  24407. type: "alter_table_drop_column",
  24408. tableName: statement.tableName,
  24409. columnName: statement.columnName,
  24410. schema: statement.schema
  24411. }),
  24412. new MySqlAlterTableAddColumnConvertor().convert({
  24413. tableName,
  24414. column: {
  24415. name: columnName,
  24416. type: statement.newDataType,
  24417. notNull: statement.columnNotNull,
  24418. default: statement.columnDefault,
  24419. onUpdate: statement.columnOnUpdate,
  24420. autoincrement: statement.columnAutoIncrement,
  24421. primaryKey: statement.columnPk,
  24422. generated: statement.columnGenerated
  24423. },
  24424. schema: statement.schema,
  24425. type: "alter_table_add_column"
  24426. })
  24427. ];
  24428. }
  24429. } else {
  24430. columnType = ` ${statement.newDataType}`;
  24431. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24432. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24433. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24434. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24435. columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${(_f = statement.columnGenerated) == null ? void 0 : _f.as}) ${(_g = statement.columnGenerated) == null ? void 0 : _g.type.toUpperCase()}` : "";
  24436. }
  24437. columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
  24438. return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnGenerated}${columnNotNull}${columnDefault}${columnOnUpdate};`;
  24439. }
  24440. };
  24441. SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
  24442. can(statement, dialect6) {
  24443. return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "singlestore";
  24444. }
  24445. convert(statement) {
  24446. const {
  24447. tableName,
  24448. columnName,
  24449. schema: schema6,
  24450. columnNotNull: notNull,
  24451. columnDefault,
  24452. columnOnUpdate,
  24453. columnAutoIncrement,
  24454. columnPk,
  24455. columnGenerated
  24456. } = statement;
  24457. const tableNameWithSchema = schema6 ? `\`${schema6}\`.\`${tableName}\`` : `\`${tableName}\``;
  24458. const addColumnStatement = new SingleStoreAlterTableAddColumnConvertor().convert({
  24459. schema: schema6,
  24460. tableName,
  24461. column: {
  24462. name: columnName,
  24463. type: statement.newDataType,
  24464. notNull,
  24465. default: columnDefault,
  24466. onUpdate: columnOnUpdate,
  24467. autoincrement: columnAutoIncrement,
  24468. primaryKey: columnPk,
  24469. generated: columnGenerated
  24470. },
  24471. type: "alter_table_add_column"
  24472. });
  24473. return [
  24474. `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`,
  24475. addColumnStatement
  24476. ];
  24477. }
  24478. };
  24479. SingleStoreAlterTableAddPk = class extends Convertor {
  24480. can(statement, dialect6) {
  24481. return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "singlestore";
  24482. }
  24483. convert(statement) {
  24484. return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
  24485. }
  24486. };
  24487. SingleStoreAlterTableDropPk = class extends Convertor {
  24488. can(statement, dialect6) {
  24489. return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "singlestore";
  24490. }
  24491. convert(statement) {
  24492. return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
  24493. }
  24494. };
  24495. SingleStoreModifyColumn = class extends Convertor {
  24496. can(statement, dialect6) {
  24497. return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "singlestore";
  24498. }
  24499. convert(statement) {
  24500. var _a2, _b, _c, _d, _e, _f, _g;
  24501. const { tableName, columnName } = statement;
  24502. let columnType = ``;
  24503. let columnDefault = "";
  24504. let columnNotNull = "";
  24505. let columnOnUpdate = "";
  24506. let columnAutoincrement = "";
  24507. let primaryKey = statement.columnPk ? " PRIMARY KEY" : "";
  24508. let columnGenerated = "";
  24509. if (statement.type === "alter_table_alter_column_drop_notnull") {
  24510. columnType = ` ${statement.newDataType}`;
  24511. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24512. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24513. columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24514. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24515. } else if (statement.type === "alter_table_alter_column_set_notnull") {
  24516. columnNotNull = ` NOT NULL`;
  24517. columnType = ` ${statement.newDataType}`;
  24518. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24519. columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24520. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24521. } else if (statement.type === "alter_table_alter_column_drop_on_update") {
  24522. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24523. columnType = ` ${statement.newDataType}`;
  24524. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24525. columnOnUpdate = "";
  24526. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24527. } else if (statement.type === "alter_table_alter_column_set_on_update") {
  24528. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24529. columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`;
  24530. columnType = ` ${statement.newDataType}`;
  24531. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24532. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24533. } else if (statement.type === "alter_table_alter_column_set_autoincrement") {
  24534. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24535. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24536. columnType = ` ${statement.newDataType}`;
  24537. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24538. columnAutoincrement = " AUTO_INCREMENT";
  24539. } else if (statement.type === "alter_table_alter_column_drop_autoincrement") {
  24540. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24541. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24542. columnType = ` ${statement.newDataType}`;
  24543. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24544. columnAutoincrement = "";
  24545. } else if (statement.type === "alter_table_alter_column_set_default") {
  24546. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24547. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24548. columnType = ` ${statement.newDataType}`;
  24549. columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
  24550. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24551. } else if (statement.type === "alter_table_alter_column_drop_default") {
  24552. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24553. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24554. columnType = ` ${statement.newDataType}`;
  24555. columnDefault = "";
  24556. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24557. } else if (statement.type === "alter_table_alter_column_set_generated") {
  24558. columnType = ` ${statement.newDataType}`;
  24559. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24560. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24561. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24562. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24563. if (((_a2 = statement.columnGenerated) == null ? void 0 : _a2.type) === "virtual") {
  24564. return [
  24565. new SingleStoreAlterTableDropColumnConvertor().convert({
  24566. type: "alter_table_drop_column",
  24567. tableName: statement.tableName,
  24568. columnName: statement.columnName,
  24569. schema: statement.schema
  24570. }),
  24571. new SingleStoreAlterTableAddColumnConvertor().convert({
  24572. tableName,
  24573. column: {
  24574. name: columnName,
  24575. type: statement.newDataType,
  24576. notNull: statement.columnNotNull,
  24577. default: statement.columnDefault,
  24578. onUpdate: statement.columnOnUpdate,
  24579. autoincrement: statement.columnAutoIncrement,
  24580. primaryKey: statement.columnPk,
  24581. generated: statement.columnGenerated
  24582. },
  24583. schema: statement.schema,
  24584. type: "alter_table_add_column"
  24585. })
  24586. ];
  24587. } else {
  24588. columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${(_b = statement.columnGenerated) == null ? void 0 : _b.as}) ${(_c = statement.columnGenerated) == null ? void 0 : _c.type.toUpperCase()}` : "";
  24589. }
  24590. } else if (statement.type === "alter_table_alter_column_drop_generated") {
  24591. columnType = ` ${statement.newDataType}`;
  24592. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24593. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24594. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24595. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24596. if (((_e = (_d = statement.oldColumn) == null ? void 0 : _d.generated) == null ? void 0 : _e.type) === "virtual") {
  24597. return [
  24598. new SingleStoreAlterTableDropColumnConvertor().convert({
  24599. type: "alter_table_drop_column",
  24600. tableName: statement.tableName,
  24601. columnName: statement.columnName,
  24602. schema: statement.schema
  24603. }),
  24604. new SingleStoreAlterTableAddColumnConvertor().convert({
  24605. tableName,
  24606. column: {
  24607. name: columnName,
  24608. type: statement.newDataType,
  24609. notNull: statement.columnNotNull,
  24610. default: statement.columnDefault,
  24611. onUpdate: statement.columnOnUpdate,
  24612. autoincrement: statement.columnAutoIncrement,
  24613. primaryKey: statement.columnPk,
  24614. generated: statement.columnGenerated
  24615. },
  24616. schema: statement.schema,
  24617. type: "alter_table_add_column"
  24618. })
  24619. ];
  24620. }
  24621. } else {
  24622. columnType = ` ${statement.newDataType}`;
  24623. columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
  24624. columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
  24625. columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
  24626. columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
  24627. columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${(_f = statement.columnGenerated) == null ? void 0 : _f.as}) ${(_g = statement.columnGenerated) == null ? void 0 : _g.type.toUpperCase()}` : "";
  24628. }
  24629. columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
  24630. return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnNotNull}${columnDefault}${columnOnUpdate}${columnGenerated};`;
  24631. }
  24632. };
  24633. PgAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
  24634. can(statement, dialect6) {
  24635. return statement.type === "create_composite_pk" && dialect6 === "postgresql";
  24636. }
  24637. convert(statement) {
  24638. const { name, columns } = PgSquasher.unsquashPK(statement.data);
  24639. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  24640. return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.constraintName}" PRIMARY KEY("${columns.join('","')}");`;
  24641. }
  24642. };
  24643. PgAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
  24644. can(statement, dialect6) {
  24645. return statement.type === "delete_composite_pk" && dialect6 === "postgresql";
  24646. }
  24647. convert(statement) {
  24648. const { name, columns } = PgSquasher.unsquashPK(statement.data);
  24649. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  24650. return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
  24651. }
  24652. };
  24653. PgAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
  24654. can(statement, dialect6) {
  24655. return statement.type === "alter_composite_pk" && dialect6 === "postgresql";
  24656. }
  24657. convert(statement) {
  24658. const { name, columns } = PgSquasher.unsquashPK(statement.old);
  24659. const { name: newName, columns: newColumns } = PgSquasher.unsquashPK(
  24660. statement.new
  24661. );
  24662. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  24663. return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.oldConstraintName}";
  24664. ${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.newConstraintName}" PRIMARY KEY("${newColumns.join('","')}");`;
  24665. }
  24666. };
  24667. MySqlAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
  24668. can(statement, dialect6) {
  24669. return statement.type === "create_composite_pk" && dialect6 === "mysql";
  24670. }
  24671. convert(statement) {
  24672. const { name, columns } = MySqlSquasher.unsquashPK(statement.data);
  24673. return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY(\`${columns.join("`,`")}\`);`;
  24674. }
  24675. };
  24676. MySqlAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
  24677. can(statement, dialect6) {
  24678. return statement.type === "delete_composite_pk" && dialect6 === "mysql";
  24679. }
  24680. convert(statement) {
  24681. const { name, columns } = MySqlSquasher.unsquashPK(statement.data);
  24682. return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY;`;
  24683. }
  24684. };
  24685. MySqlAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
  24686. can(statement, dialect6) {
  24687. return statement.type === "alter_composite_pk" && dialect6 === "mysql";
  24688. }
  24689. convert(statement) {
  24690. const { name, columns } = MySqlSquasher.unsquashPK(statement.old);
  24691. const { name: newName, columns: newColumns } = MySqlSquasher.unsquashPK(
  24692. statement.new
  24693. );
  24694. return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY, ADD PRIMARY KEY(\`${newColumns.join("`,`")}\`);`;
  24695. }
  24696. };
  24697. PgAlterTableAlterColumnSetPrimaryKeyConvertor = class extends Convertor {
  24698. can(statement, dialect6) {
  24699. return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "postgresql";
  24700. }
  24701. convert(statement) {
  24702. const { tableName, columnName } = statement;
  24703. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  24704. return `ALTER TABLE ${tableNameWithSchema} ADD PRIMARY KEY ("${columnName}");`;
  24705. }
  24706. };
  24707. PgAlterTableAlterColumnDropPrimaryKeyConvertor = class extends Convertor {
  24708. can(statement, dialect6) {
  24709. return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "postgresql";
  24710. }
  24711. convert(statement) {
  24712. const { tableName, columnName, schema: schema6 } = statement;
  24713. return `/*
  24714. Unfortunately in current drizzle-kit version we can't automatically get name for primary key.
  24715. We are working on making it available!
  24716. Meanwhile you can:
  24717. 1. Check pk name in your database, by running
  24718. SELECT constraint_name FROM information_schema.table_constraints
  24719. WHERE table_schema = '${typeof schema6 === "undefined" || schema6 === "" ? "public" : schema6}'
  24720. AND table_name = '${tableName}'
  24721. AND constraint_type = 'PRIMARY KEY';
  24722. 2. Uncomment code below and paste pk name manually
  24723. Hope to release this update as soon as possible
  24724. */
  24725. -- ALTER TABLE "${tableName}" DROP CONSTRAINT "<constraint_name>";`;
  24726. }
  24727. };
  24728. PgAlterTableAlterColumnSetNotNullConvertor = class extends Convertor {
  24729. can(statement, dialect6) {
  24730. return statement.type === "alter_table_alter_column_set_notnull" && dialect6 === "postgresql";
  24731. }
  24732. convert(statement) {
  24733. const { tableName, columnName } = statement;
  24734. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  24735. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET NOT NULL;`;
  24736. }
  24737. };
  24738. PgAlterTableAlterColumnDropNotNullConvertor = class extends Convertor {
  24739. can(statement, dialect6) {
  24740. return statement.type === "alter_table_alter_column_drop_notnull" && dialect6 === "postgresql";
  24741. }
  24742. convert(statement) {
  24743. const { tableName, columnName } = statement;
  24744. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  24745. return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP NOT NULL;`;
  24746. }
  24747. };
  24748. PgCreateForeignKeyConvertor = class extends Convertor {
  24749. can(statement, dialect6) {
  24750. return statement.type === "create_reference" && dialect6 === "postgresql";
  24751. }
  24752. convert(statement) {
  24753. const {
  24754. name,
  24755. tableFrom,
  24756. tableTo,
  24757. columnsFrom,
  24758. columnsTo,
  24759. onDelete,
  24760. onUpdate,
  24761. schemaTo
  24762. } = PgSquasher.unsquashFK(statement.data);
  24763. const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
  24764. const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
  24765. const fromColumnsString = columnsFrom.map((it) => `"${it}"`).join(",");
  24766. const toColumnsString = columnsTo.map((it) => `"${it}"`).join(",");
  24767. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
  24768. const tableToNameWithSchema = schemaTo ? `"${schemaTo}"."${tableTo}"` : `"${tableTo}"`;
  24769. const alterStatement = `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
  24770. return alterStatement;
  24771. }
  24772. };
  24773. LibSQLCreateForeignKeyConvertor = class extends Convertor {
  24774. can(statement, dialect6) {
  24775. return statement.type === "create_reference" && dialect6 === "turso";
  24776. }
  24777. convert(statement, json2, action) {
  24778. const { columnsFrom, columnsTo, tableFrom, onDelete, onUpdate, tableTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
  24779. const { columnDefault, columnNotNull, columnType } = statement;
  24780. const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
  24781. const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
  24782. const columnsDefaultValue = columnDefault ? ` DEFAULT ${columnDefault}` : "";
  24783. const columnNotNullValue = columnNotNull ? ` NOT NULL` : "";
  24784. const columnTypeValue = columnType ? ` ${columnType}` : "";
  24785. const columnFrom = columnsFrom[0];
  24786. const columnTo = columnsTo[0];
  24787. return `ALTER TABLE \`${tableFrom}\` ALTER COLUMN "${columnFrom}" TO "${columnFrom}"${columnTypeValue}${columnNotNullValue}${columnsDefaultValue} REFERENCES ${tableTo}(${columnTo})${onDeleteStatement}${onUpdateStatement};`;
  24788. }
  24789. };
  24790. MySqlCreateForeignKeyConvertor = class extends Convertor {
  24791. can(statement, dialect6) {
  24792. return statement.type === "create_reference" && dialect6 === "mysql";
  24793. }
  24794. convert(statement) {
  24795. const {
  24796. name,
  24797. tableFrom,
  24798. tableTo,
  24799. columnsFrom,
  24800. columnsTo,
  24801. onDelete,
  24802. onUpdate
  24803. } = MySqlSquasher.unsquashFK(statement.data);
  24804. const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
  24805. const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
  24806. const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(",");
  24807. const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(",");
  24808. return `ALTER TABLE \`${tableFrom}\` ADD CONSTRAINT \`${name}\` FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
  24809. }
  24810. };
  24811. PgAlterForeignKeyConvertor = class extends Convertor {
  24812. can(statement, dialect6) {
  24813. return statement.type === "alter_reference" && dialect6 === "postgresql";
  24814. }
  24815. convert(statement) {
  24816. const newFk = PgSquasher.unsquashFK(statement.data);
  24817. const oldFk = PgSquasher.unsquashFK(statement.oldFkey);
  24818. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`;
  24819. let sql = `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${oldFk.name}";
  24820. `;
  24821. const onDeleteStatement = newFk.onDelete ? ` ON DELETE ${newFk.onDelete}` : "";
  24822. const onUpdateStatement = newFk.onUpdate ? ` ON UPDATE ${newFk.onUpdate}` : "";
  24823. const fromColumnsString = newFk.columnsFrom.map((it) => `"${it}"`).join(",");
  24824. const toColumnsString = newFk.columnsTo.map((it) => `"${it}"`).join(",");
  24825. const tableFromNameWithSchema = oldFk.schemaTo ? `"${oldFk.schemaTo}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`;
  24826. const tableToNameWithSchema = newFk.schemaTo ? `"${newFk.schemaTo}"."${newFk.tableFrom}"` : `"${newFk.tableFrom}"`;
  24827. const alterStatement = `ALTER TABLE ${tableFromNameWithSchema} ADD CONSTRAINT "${newFk.name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
  24828. sql += alterStatement;
  24829. return sql;
  24830. }
  24831. };
  24832. PgDeleteForeignKeyConvertor = class extends Convertor {
  24833. can(statement, dialect6) {
  24834. return statement.type === "delete_reference" && dialect6 === "postgresql";
  24835. }
  24836. convert(statement) {
  24837. const tableFrom = statement.tableName;
  24838. const { name } = PgSquasher.unsquashFK(statement.data);
  24839. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
  24840. return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${name}";
  24841. `;
  24842. }
  24843. };
  24844. MySqlDeleteForeignKeyConvertor = class extends Convertor {
  24845. can(statement, dialect6) {
  24846. return statement.type === "delete_reference" && dialect6 === "mysql";
  24847. }
  24848. convert(statement) {
  24849. const tableFrom = statement.tableName;
  24850. const { name } = MySqlSquasher.unsquashFK(statement.data);
  24851. return `ALTER TABLE \`${tableFrom}\` DROP FOREIGN KEY \`${name}\`;
  24852. `;
  24853. }
  24854. };
  24855. CreatePgIndexConvertor = class extends Convertor {
  24856. can(statement, dialect6) {
  24857. return statement.type === "create_index_pg" && dialect6 === "postgresql";
  24858. }
  24859. convert(statement) {
  24860. const {
  24861. name,
  24862. columns,
  24863. isUnique,
  24864. concurrently,
  24865. with: withMap,
  24866. method,
  24867. where
  24868. } = statement.data;
  24869. const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
  24870. const value = columns.map(
  24871. (it) => `${it.isExpression ? it.expression : `"${it.expression}"`}${it.opclass ? ` ${it.opclass}` : it.asc ? "" : " DESC"}${it.asc && it.nulls && it.nulls === "last" || it.opclass ? "" : ` NULLS ${it.nulls.toUpperCase()}`}`
  24872. ).join(",");
  24873. const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
  24874. function reverseLogic(mappedWith) {
  24875. let reversedString = "";
  24876. for (const key in mappedWith) {
  24877. if (mappedWith.hasOwnProperty(key)) {
  24878. reversedString += `${key}=${mappedWith[key]},`;
  24879. }
  24880. }
  24881. reversedString = reversedString.slice(0, -1);
  24882. return reversedString;
  24883. }
  24884. return `CREATE ${indexPart}${concurrently ? " CONCURRENTLY" : ""} "${name}" ON ${tableNameWithSchema} USING ${method} (${value})${Object.keys(withMap).length !== 0 ? ` WITH (${reverseLogic(withMap)})` : ""}${where ? ` WHERE ${where}` : ""};`;
  24885. }
  24886. };
  24887. CreateMySqlIndexConvertor = class extends Convertor {
  24888. can(statement, dialect6) {
  24889. return statement.type === "create_index" && dialect6 === "mysql";
  24890. }
  24891. convert(statement) {
  24892. const { name, columns, isUnique } = MySqlSquasher.unsquashIdx(
  24893. statement.data
  24894. );
  24895. const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
  24896. const uniqueString = columns.map((it) => {
  24897. var _a2, _b, _c, _d;
  24898. return ((_a2 = statement.internal) == null ? void 0 : _a2.indexes) ? ((_d = (_c = (_b = statement.internal) == null ? void 0 : _b.indexes[name]) == null ? void 0 : _c.columns[it]) == null ? void 0 : _d.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
  24899. }).join(",");
  24900. return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString});`;
  24901. }
  24902. };
  24903. CreateSingleStoreIndexConvertor = class extends Convertor {
  24904. can(statement, dialect6) {
  24905. return statement.type === "create_index" && dialect6 === "singlestore";
  24906. }
  24907. convert(statement) {
  24908. const { name, columns, isUnique } = SingleStoreSquasher.unsquashIdx(
  24909. statement.data
  24910. );
  24911. const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
  24912. const uniqueString = columns.map((it) => {
  24913. var _a2, _b, _c, _d;
  24914. return ((_a2 = statement.internal) == null ? void 0 : _a2.indexes) ? ((_d = (_c = (_b = statement.internal) == null ? void 0 : _b.indexes[name]) == null ? void 0 : _c.columns[it]) == null ? void 0 : _d.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
  24915. }).join(",");
  24916. return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString});`;
  24917. }
  24918. };
  24919. CreateSqliteIndexConvertor = class extends Convertor {
  24920. can(statement, dialect6) {
  24921. return statement.type === "create_index" && (dialect6 === "sqlite" || dialect6 === "turso");
  24922. }
  24923. convert(statement) {
  24924. const { name, columns, isUnique, where } = SQLiteSquasher.unsquashIdx(
  24925. statement.data
  24926. );
  24927. const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
  24928. const whereStatement = where ? ` WHERE ${where}` : "";
  24929. const uniqueString = columns.map((it) => {
  24930. var _a2, _b, _c, _d;
  24931. return ((_a2 = statement.internal) == null ? void 0 : _a2.indexes) ? ((_d = (_c = (_b = statement.internal) == null ? void 0 : _b.indexes[name]) == null ? void 0 : _c.columns[it]) == null ? void 0 : _d.isExpression) ? it : `\`${it}\`` : `\`${it}\``;
  24932. }).join(",");
  24933. return `CREATE ${indexPart} \`${name}\` ON \`${statement.tableName}\` (${uniqueString})${whereStatement};`;
  24934. }
  24935. };
  24936. PgDropIndexConvertor = class extends Convertor {
  24937. can(statement, dialect6) {
  24938. return statement.type === "drop_index" && dialect6 === "postgresql";
  24939. }
  24940. convert(statement) {
  24941. const { schema: schema6 } = statement;
  24942. const { name } = PgSquasher.unsquashIdx(statement.data);
  24943. const indexNameWithSchema = schema6 ? `"${schema6}"."${name}"` : `"${name}"`;
  24944. return `DROP INDEX ${indexNameWithSchema};`;
  24945. }
  24946. };
  24947. PgCreateSchemaConvertor = class extends Convertor {
  24948. can(statement, dialect6) {
  24949. return statement.type === "create_schema" && dialect6 === "postgresql";
  24950. }
  24951. convert(statement) {
  24952. const { name } = statement;
  24953. return `CREATE SCHEMA "${name}";
  24954. `;
  24955. }
  24956. };
  24957. PgRenameSchemaConvertor = class extends Convertor {
  24958. can(statement, dialect6) {
  24959. return statement.type === "rename_schema" && dialect6 === "postgresql";
  24960. }
  24961. convert(statement) {
  24962. const { from, to } = statement;
  24963. return `ALTER SCHEMA "${from}" RENAME TO "${to}";
  24964. `;
  24965. }
  24966. };
  24967. PgDropSchemaConvertor = class extends Convertor {
  24968. can(statement, dialect6) {
  24969. return statement.type === "drop_schema" && dialect6 === "postgresql";
  24970. }
  24971. convert(statement) {
  24972. const { name } = statement;
  24973. return `DROP SCHEMA "${name}";
  24974. `;
  24975. }
  24976. };
  24977. PgAlterTableSetSchemaConvertor = class extends Convertor {
  24978. can(statement, dialect6) {
  24979. return statement.type === "alter_table_set_schema" && dialect6 === "postgresql";
  24980. }
  24981. convert(statement) {
  24982. const { tableName, schemaFrom, schemaTo } = statement;
  24983. return `ALTER TABLE "${schemaFrom}"."${tableName}" SET SCHEMA "${schemaTo}";
  24984. `;
  24985. }
  24986. };
  24987. PgAlterTableSetNewSchemaConvertor = class extends Convertor {
  24988. can(statement, dialect6) {
  24989. return statement.type === "alter_table_set_new_schema" && dialect6 === "postgresql";
  24990. }
  24991. convert(statement) {
  24992. const { tableName, to, from } = statement;
  24993. const tableNameWithSchema = from ? `"${from}"."${tableName}"` : `"${tableName}"`;
  24994. return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA "${to}";
  24995. `;
  24996. }
  24997. };
  24998. PgAlterTableRemoveFromSchemaConvertor = class extends Convertor {
  24999. can(statement, dialect6) {
  25000. return statement.type === "alter_table_remove_from_schema" && dialect6 === "postgresql";
  25001. }
  25002. convert(statement) {
  25003. const { tableName, schema: schema6 } = statement;
  25004. const tableNameWithSchema = schema6 ? `"${schema6}"."${tableName}"` : `"${tableName}"`;
  25005. return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA public;
  25006. `;
  25007. }
  25008. };
  25009. SqliteDropIndexConvertor = class extends Convertor {
  25010. can(statement, dialect6) {
  25011. return statement.type === "drop_index" && (dialect6 === "sqlite" || dialect6 === "turso");
  25012. }
  25013. convert(statement) {
  25014. const { name } = PgSquasher.unsquashIdx(statement.data);
  25015. return `DROP INDEX \`${name}\`;`;
  25016. }
  25017. };
  25018. MySqlDropIndexConvertor = class extends Convertor {
  25019. can(statement, dialect6) {
  25020. return statement.type === "drop_index" && dialect6 === "mysql";
  25021. }
  25022. convert(statement) {
  25023. const { name } = MySqlSquasher.unsquashIdx(statement.data);
  25024. return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`;
  25025. }
  25026. };
  25027. SingleStoreDropIndexConvertor = class extends Convertor {
  25028. can(statement, dialect6) {
  25029. return statement.type === "drop_index" && dialect6 === "singlestore";
  25030. }
  25031. convert(statement) {
  25032. const { name } = SingleStoreSquasher.unsquashIdx(statement.data);
  25033. return `DROP INDEX \`${name}\` ON \`${statement.tableName}\`;`;
  25034. }
  25035. };
  25036. SQLiteRecreateTableConvertor = class extends Convertor {
  25037. can(statement, dialect6) {
  25038. return statement.type === "recreate_table" && dialect6 === "sqlite";
  25039. }
  25040. convert(statement) {
  25041. const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
  25042. const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
  25043. const newTableName = `__new_${tableName}`;
  25044. const sqlStatements = [];
  25045. sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
  25046. const mappedCheckConstraints = checkConstraints.map(
  25047. (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `'${newTableName}'.`)
  25048. );
  25049. sqlStatements.push(
  25050. new SQLiteCreateTableConvertor().convert({
  25051. type: "sqlite_create_table",
  25052. tableName: newTableName,
  25053. columns,
  25054. referenceData,
  25055. compositePKs,
  25056. checkConstraints: mappedCheckConstraints
  25057. })
  25058. );
  25059. sqlStatements.push(
  25060. `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
  25061. );
  25062. sqlStatements.push(
  25063. new SQLiteDropTableConvertor().convert({
  25064. type: "drop_table",
  25065. tableName,
  25066. schema: ""
  25067. })
  25068. );
  25069. sqlStatements.push(
  25070. new SqliteRenameTableConvertor().convert({
  25071. fromSchema: "",
  25072. tableNameFrom: newTableName,
  25073. tableNameTo: tableName,
  25074. toSchema: "",
  25075. type: "rename_table"
  25076. })
  25077. );
  25078. sqlStatements.push(`PRAGMA foreign_keys=ON;`);
  25079. return sqlStatements;
  25080. }
  25081. };
  25082. LibSQLRecreateTableConvertor = class extends Convertor {
  25083. can(statement, dialect6) {
  25084. return statement.type === "recreate_table" && dialect6 === "turso";
  25085. }
  25086. convert(statement) {
  25087. const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
  25088. const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
  25089. const newTableName = `__new_${tableName}`;
  25090. const sqlStatements = [];
  25091. const mappedCheckConstraints = checkConstraints.map(
  25092. (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
  25093. );
  25094. sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
  25095. sqlStatements.push(
  25096. new SQLiteCreateTableConvertor().convert({
  25097. type: "sqlite_create_table",
  25098. tableName: newTableName,
  25099. columns,
  25100. referenceData,
  25101. compositePKs,
  25102. checkConstraints: mappedCheckConstraints
  25103. })
  25104. );
  25105. sqlStatements.push(
  25106. `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
  25107. );
  25108. sqlStatements.push(
  25109. new SQLiteDropTableConvertor().convert({
  25110. type: "drop_table",
  25111. tableName,
  25112. schema: ""
  25113. })
  25114. );
  25115. sqlStatements.push(
  25116. new SqliteRenameTableConvertor().convert({
  25117. fromSchema: "",
  25118. tableNameFrom: newTableName,
  25119. tableNameTo: tableName,
  25120. toSchema: "",
  25121. type: "rename_table"
  25122. })
  25123. );
  25124. sqlStatements.push(`PRAGMA foreign_keys=ON;`);
  25125. return sqlStatements;
  25126. }
  25127. };
  25128. SingleStoreRecreateTableConvertor = class extends Convertor {
  25129. can(statement, dialect6) {
  25130. return statement.type === "singlestore_recreate_table" && dialect6 === "singlestore";
  25131. }
  25132. convert(statement) {
  25133. const { tableName, columns, compositePKs, uniqueConstraints } = statement;
  25134. const columnNames = columns.map((it) => `\`${it.name}\``).join(", ");
  25135. const newTableName = `__new_${tableName}`;
  25136. const sqlStatements = [];
  25137. sqlStatements.push(
  25138. new SingleStoreCreateTableConvertor().convert({
  25139. type: "create_table",
  25140. tableName: newTableName,
  25141. columns,
  25142. compositePKs,
  25143. uniqueConstraints,
  25144. schema: ""
  25145. })
  25146. );
  25147. sqlStatements.push(
  25148. `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
  25149. );
  25150. sqlStatements.push(
  25151. new SingleStoreDropTableConvertor().convert({
  25152. type: "drop_table",
  25153. tableName,
  25154. schema: ""
  25155. })
  25156. );
  25157. sqlStatements.push(
  25158. new SingleStoreRenameTableConvertor().convert({
  25159. fromSchema: "",
  25160. tableNameFrom: newTableName,
  25161. tableNameTo: tableName,
  25162. toSchema: "",
  25163. type: "rename_table"
  25164. })
  25165. );
  25166. return sqlStatements;
  25167. }
  25168. };
  25169. convertors = [];
  25170. convertors.push(new PgCreateTableConvertor());
  25171. convertors.push(new MySqlCreateTableConvertor());
  25172. convertors.push(new SingleStoreCreateTableConvertor());
  25173. convertors.push(new SingleStoreRecreateTableConvertor());
  25174. convertors.push(new SQLiteCreateTableConvertor());
  25175. convertors.push(new SQLiteRecreateTableConvertor());
  25176. convertors.push(new LibSQLRecreateTableConvertor());
  25177. convertors.push(new PgCreateViewConvertor());
  25178. convertors.push(new PgDropViewConvertor());
  25179. convertors.push(new PgRenameViewConvertor());
  25180. convertors.push(new PgAlterViewSchemaConvertor());
  25181. convertors.push(new PgAlterViewAddWithOptionConvertor());
  25182. convertors.push(new PgAlterViewDropWithOptionConvertor());
  25183. convertors.push(new PgAlterViewAlterTablespaceConvertor());
  25184. convertors.push(new PgAlterViewAlterUsingConvertor());
  25185. convertors.push(new MySqlCreateViewConvertor());
  25186. convertors.push(new MySqlDropViewConvertor());
  25187. convertors.push(new MySqlRenameViewConvertor());
  25188. convertors.push(new MySqlAlterViewConvertor());
  25189. convertors.push(new SqliteCreateViewConvertor());
  25190. convertors.push(new SqliteDropViewConvertor());
  25191. convertors.push(new CreateTypeEnumConvertor());
  25192. convertors.push(new DropTypeEnumConvertor());
  25193. convertors.push(new AlterTypeAddValueConvertor());
  25194. convertors.push(new AlterTypeSetSchemaConvertor());
  25195. convertors.push(new AlterRenameTypeConvertor());
  25196. convertors.push(new AlterTypeDropValueConvertor());
  25197. convertors.push(new CreatePgSequenceConvertor());
  25198. convertors.push(new DropPgSequenceConvertor());
  25199. convertors.push(new RenamePgSequenceConvertor());
  25200. convertors.push(new MovePgSequenceConvertor());
  25201. convertors.push(new AlterPgSequenceConvertor());
  25202. convertors.push(new PgDropTableConvertor());
  25203. convertors.push(new MySQLDropTableConvertor());
  25204. convertors.push(new SingleStoreDropTableConvertor());
  25205. convertors.push(new SQLiteDropTableConvertor());
  25206. convertors.push(new PgRenameTableConvertor());
  25207. convertors.push(new MySqlRenameTableConvertor());
  25208. convertors.push(new SingleStoreRenameTableConvertor());
  25209. convertors.push(new SqliteRenameTableConvertor());
  25210. convertors.push(new PgAlterTableRenameColumnConvertor());
  25211. convertors.push(new MySqlAlterTableRenameColumnConvertor());
  25212. convertors.push(new SingleStoreAlterTableRenameColumnConvertor());
  25213. convertors.push(new SQLiteAlterTableRenameColumnConvertor());
  25214. convertors.push(new PgAlterTableDropColumnConvertor());
  25215. convertors.push(new MySqlAlterTableDropColumnConvertor());
  25216. convertors.push(new SingleStoreAlterTableDropColumnConvertor());
  25217. convertors.push(new SQLiteAlterTableDropColumnConvertor());
  25218. convertors.push(new PgAlterTableAddColumnConvertor());
  25219. convertors.push(new MySqlAlterTableAddColumnConvertor());
  25220. convertors.push(new SingleStoreAlterTableAddColumnConvertor());
  25221. convertors.push(new SQLiteAlterTableAddColumnConvertor());
  25222. convertors.push(new PgAlterTableAlterColumnSetTypeConvertor());
  25223. convertors.push(new PgAlterTableAddUniqueConstraintConvertor());
  25224. convertors.push(new PgAlterTableDropUniqueConstraintConvertor());
  25225. convertors.push(new PgAlterTableAddCheckConstraintConvertor());
  25226. convertors.push(new PgAlterTableDeleteCheckConstraintConvertor());
  25227. convertors.push(new MySqlAlterTableAddCheckConstraintConvertor());
  25228. convertors.push(new MySqlAlterTableDeleteCheckConstraintConvertor());
  25229. convertors.push(new MySQLAlterTableAddUniqueConstraintConvertor());
  25230. convertors.push(new MySQLAlterTableDropUniqueConstraintConvertor());
  25231. convertors.push(new SingleStoreAlterTableAddUniqueConstraintConvertor());
  25232. convertors.push(new SingleStoreAlterTableDropUniqueConstraintConvertor());
  25233. convertors.push(new CreatePgIndexConvertor());
  25234. convertors.push(new CreateMySqlIndexConvertor());
  25235. convertors.push(new CreateSingleStoreIndexConvertor());
  25236. convertors.push(new CreateSqliteIndexConvertor());
  25237. convertors.push(new PgDropIndexConvertor());
  25238. convertors.push(new SqliteDropIndexConvertor());
  25239. convertors.push(new MySqlDropIndexConvertor());
  25240. convertors.push(new SingleStoreDropIndexConvertor());
  25241. convertors.push(new PgAlterTableAlterColumnSetPrimaryKeyConvertor());
  25242. convertors.push(new PgAlterTableAlterColumnDropPrimaryKeyConvertor());
  25243. convertors.push(new PgAlterTableAlterColumnSetNotNullConvertor());
  25244. convertors.push(new PgAlterTableAlterColumnDropNotNullConvertor());
  25245. convertors.push(new PgAlterTableAlterColumnSetDefaultConvertor());
  25246. convertors.push(new PgAlterTableAlterColumnDropDefaultConvertor());
  25247. convertors.push(new PgAlterPolicyConvertor());
  25248. convertors.push(new PgCreatePolicyConvertor());
  25249. convertors.push(new PgDropPolicyConvertor());
  25250. convertors.push(new PgRenamePolicyConvertor());
  25251. convertors.push(new PgAlterIndPolicyConvertor());
  25252. convertors.push(new PgCreateIndPolicyConvertor());
  25253. convertors.push(new PgDropIndPolicyConvertor());
  25254. convertors.push(new PgRenameIndPolicyConvertor());
  25255. convertors.push(new PgEnableRlsConvertor());
  25256. convertors.push(new PgDisableRlsConvertor());
  25257. convertors.push(new PgDropRoleConvertor());
  25258. convertors.push(new PgAlterRoleConvertor());
  25259. convertors.push(new PgCreateRoleConvertor());
  25260. convertors.push(new PgRenameRoleConvertor());
  25261. convertors.push(new PgAlterTableAlterColumnSetExpressionConvertor());
  25262. convertors.push(new PgAlterTableAlterColumnDropGeneratedConvertor());
  25263. convertors.push(new PgAlterTableAlterColumnAlterrGeneratedConvertor());
  25264. convertors.push(new MySqlAlterTableAlterColumnAlterrGeneratedConvertor());
  25265. convertors.push(new SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor());
  25266. convertors.push(new SqliteAlterTableAlterColumnDropGeneratedConvertor());
  25267. convertors.push(new SqliteAlterTableAlterColumnAlterGeneratedConvertor());
  25268. convertors.push(new SqliteAlterTableAlterColumnSetExpressionConvertor());
  25269. convertors.push(new MySqlModifyColumn());
  25270. convertors.push(new LibSQLModifyColumn());
  25271. convertors.push(new SingleStoreModifyColumn());
  25272. convertors.push(new PgCreateForeignKeyConvertor());
  25273. convertors.push(new MySqlCreateForeignKeyConvertor());
  25274. convertors.push(new PgAlterForeignKeyConvertor());
  25275. convertors.push(new PgDeleteForeignKeyConvertor());
  25276. convertors.push(new MySqlDeleteForeignKeyConvertor());
  25277. convertors.push(new PgCreateSchemaConvertor());
  25278. convertors.push(new PgRenameSchemaConvertor());
  25279. convertors.push(new PgDropSchemaConvertor());
  25280. convertors.push(new PgAlterTableSetSchemaConvertor());
  25281. convertors.push(new PgAlterTableSetNewSchemaConvertor());
  25282. convertors.push(new PgAlterTableRemoveFromSchemaConvertor());
  25283. convertors.push(new LibSQLCreateForeignKeyConvertor());
  25284. convertors.push(new PgAlterTableAlterColumnDropGenerated());
  25285. convertors.push(new PgAlterTableAlterColumnSetGenerated());
  25286. convertors.push(new PgAlterTableAlterColumnAlterGenerated());
  25287. convertors.push(new PgAlterTableCreateCompositePrimaryKeyConvertor());
  25288. convertors.push(new PgAlterTableDeleteCompositePrimaryKeyConvertor());
  25289. convertors.push(new PgAlterTableAlterCompositePrimaryKeyConvertor());
  25290. convertors.push(new MySqlAlterTableDeleteCompositePrimaryKeyConvertor());
  25291. convertors.push(new MySqlAlterTableDropPk());
  25292. convertors.push(new MySqlAlterTableCreateCompositePrimaryKeyConvertor());
  25293. convertors.push(new MySqlAlterTableAddPk());
  25294. convertors.push(new MySqlAlterTableAlterCompositePrimaryKeyConvertor());
  25295. convertors.push(new SingleStoreAlterTableDropPk());
  25296. convertors.push(new SingleStoreAlterTableAddPk());
  25297. https: `
  25298. create table users (
  25299. id int,
  25300. name character varying(128)
  25301. );
  25302. create type venum as enum('one', 'two', 'three');
  25303. alter table users add column typed venum;
  25304. insert into users(id, name, typed) values (1, 'name1', 'one');
  25305. insert into users(id, name, typed) values (2, 'name2', 'two');
  25306. insert into users(id, name, typed) values (3, 'name3', 'three');
  25307. alter type venum rename to __venum;
  25308. create type venum as enum ('one', 'two', 'three', 'four', 'five');
  25309. ALTER TABLE users ALTER COLUMN typed TYPE venum USING typed::text::venum;
  25310. insert into users(id, name, typed) values (4, 'name4', 'four');
  25311. insert into users(id, name, typed) values (5, 'name5', 'five');
  25312. drop type __venum;
  25313. `;
  25314. }
  25315. });
  25316. // src/cli/commands/sqlitePushUtils.ts
  25317. var _moveDataStatements, getOldTableName, getNewTableName, logSuggestionsAndReturn;
  25318. var init_sqlitePushUtils = __esm({
  25319. "src/cli/commands/sqlitePushUtils.ts"() {
  25320. "use strict";
  25321. init_source();
  25322. init_sqliteSchema();
  25323. init_sqlgenerator();
  25324. init_utils2();
  25325. _moveDataStatements = (tableName, json, dataLoss = false) => {
  25326. const statements = [];
  25327. const newTableName = `__new_${tableName}`;
  25328. const tableColumns = Object.values(json.tables[tableName].columns);
  25329. const referenceData = Object.values(json.tables[tableName].foreignKeys);
  25330. const compositePKs = Object.values(
  25331. json.tables[tableName].compositePrimaryKeys
  25332. ).map((it) => SQLiteSquasher.unsquashPK(it));
  25333. const checkConstraints = Object.values(json.tables[tableName].checkConstraints);
  25334. const mappedCheckConstraints = checkConstraints.map(
  25335. (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
  25336. );
  25337. const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
  25338. statements.push(
  25339. new SQLiteCreateTableConvertor().convert({
  25340. type: "sqlite_create_table",
  25341. tableName: newTableName,
  25342. columns: tableColumns,
  25343. referenceData: fks,
  25344. compositePKs,
  25345. checkConstraints: mappedCheckConstraints
  25346. })
  25347. );
  25348. if (!dataLoss) {
  25349. const columns = Object.keys(json.tables[tableName].columns).map(
  25350. (c3) => `"${c3}"`
  25351. );
  25352. statements.push(
  25353. `INSERT INTO \`${newTableName}\`(${columns.join(
  25354. ", "
  25355. )}) SELECT ${columns.join(", ")} FROM \`${tableName}\`;`
  25356. );
  25357. }
  25358. statements.push(
  25359. new SQLiteDropTableConvertor().convert({
  25360. type: "drop_table",
  25361. tableName,
  25362. schema: ""
  25363. })
  25364. );
  25365. statements.push(
  25366. new SqliteRenameTableConvertor().convert({
  25367. fromSchema: "",
  25368. tableNameFrom: newTableName,
  25369. tableNameTo: tableName,
  25370. toSchema: "",
  25371. type: "rename_table"
  25372. })
  25373. );
  25374. for (const idx of Object.values(json.tables[tableName].indexes)) {
  25375. statements.push(
  25376. new CreateSqliteIndexConvertor().convert({
  25377. type: "create_index",
  25378. tableName,
  25379. schema: "",
  25380. data: idx
  25381. })
  25382. );
  25383. }
  25384. return statements;
  25385. };
  25386. getOldTableName = (tableName, meta) => {
  25387. for (const key of Object.keys(meta.tables)) {
  25388. const value = meta.tables[key];
  25389. if (`"${tableName}"` === value) {
  25390. return key.substring(1, key.length - 1);
  25391. }
  25392. }
  25393. return tableName;
  25394. };
  25395. getNewTableName = (tableName, meta) => {
  25396. if (typeof meta.tables[`"${tableName}"`] !== "undefined") {
  25397. return meta.tables[`"${tableName}"`].substring(
  25398. 1,
  25399. meta.tables[`"${tableName}"`].length - 1
  25400. );
  25401. }
  25402. return tableName;
  25403. };
  25404. logSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => {
  25405. let shouldAskForApprove = false;
  25406. const statementsToExecute = [];
  25407. const infoToPrint = [];
  25408. const tablesToRemove = [];
  25409. const columnsToRemove = [];
  25410. const schemasToRemove = [];
  25411. const tablesToTruncate = [];
  25412. for (const statement of statements) {
  25413. if (statement.type === "drop_table") {
  25414. const res = await connection.query(
  25415. `select count(*) as count from \`${statement.tableName}\``
  25416. );
  25417. const count = Number(res[0].count);
  25418. if (count > 0) {
  25419. infoToPrint.push(
  25420. `\xB7 You're about to delete ${source_default.underline(
  25421. statement.tableName
  25422. )} table with ${count} items`
  25423. );
  25424. tablesToRemove.push(statement.tableName);
  25425. shouldAskForApprove = true;
  25426. }
  25427. const fromJsonStatement = fromJson([statement], "sqlite", "push");
  25428. statementsToExecute.push(
  25429. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  25430. );
  25431. } else if (statement.type === "alter_table_drop_column") {
  25432. const tableName = statement.tableName;
  25433. const columnName = statement.columnName;
  25434. const res = await connection.query(
  25435. `select count(\`${tableName}\`.\`${columnName}\`) as count from \`${tableName}\``
  25436. );
  25437. const count = Number(res[0].count);
  25438. if (count > 0) {
  25439. infoToPrint.push(
  25440. `\xB7 You're about to delete ${source_default.underline(
  25441. columnName
  25442. )} column in ${tableName} table with ${count} items`
  25443. );
  25444. columnsToRemove.push(`${tableName}_${statement.columnName}`);
  25445. shouldAskForApprove = true;
  25446. }
  25447. const fromJsonStatement = fromJson([statement], "sqlite", "push");
  25448. statementsToExecute.push(
  25449. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  25450. );
  25451. } else if (statement.type === "sqlite_alter_table_add_column" && (statement.column.notNull && !statement.column.default)) {
  25452. const tableName = statement.tableName;
  25453. const columnName = statement.column.name;
  25454. const res = await connection.query(
  25455. `select count(*) as count from \`${tableName}\``
  25456. );
  25457. const count = Number(res[0].count);
  25458. if (count > 0) {
  25459. infoToPrint.push(
  25460. `\xB7 You're about to add not-null ${source_default.underline(
  25461. columnName
  25462. )} column without default value, which contains ${count} items`
  25463. );
  25464. tablesToTruncate.push(tableName);
  25465. statementsToExecute.push(`delete from ${tableName};`);
  25466. shouldAskForApprove = true;
  25467. }
  25468. const fromJsonStatement = fromJson([statement], "sqlite", "push");
  25469. statementsToExecute.push(
  25470. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  25471. );
  25472. } else if (statement.type === "recreate_table") {
  25473. const tableName = statement.tableName;
  25474. const oldTableName = getOldTableName(tableName, meta);
  25475. let dataLoss = false;
  25476. const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
  25477. const currentColumnNames = Object.keys(json2.tables[tableName].columns);
  25478. const { removedColumns, addedColumns } = findAddedAndRemoved(
  25479. prevColumnNames,
  25480. currentColumnNames
  25481. );
  25482. if (removedColumns.length) {
  25483. for (const removedColumn of removedColumns) {
  25484. const res = await connection.query(
  25485. `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
  25486. );
  25487. const count = Number(res[0].count);
  25488. if (count > 0) {
  25489. infoToPrint.push(
  25490. `\xB7 You're about to delete ${source_default.underline(
  25491. removedColumn
  25492. )} column in ${tableName} table with ${count} items`
  25493. );
  25494. columnsToRemove.push(removedColumn);
  25495. shouldAskForApprove = true;
  25496. }
  25497. }
  25498. }
  25499. if (addedColumns.length) {
  25500. for (const addedColumn of addedColumns) {
  25501. const [res] = await connection.query(
  25502. `select count(*) as count from \`${tableName}\``
  25503. );
  25504. const columnConf = json2.tables[tableName].columns[addedColumn];
  25505. const count = Number(res.count);
  25506. if (count > 0 && columnConf.notNull && !columnConf.default) {
  25507. dataLoss = true;
  25508. infoToPrint.push(
  25509. `\xB7 You're about to add not-null ${source_default.underline(
  25510. addedColumn
  25511. )} column without default value to table, which contains ${count} items`
  25512. );
  25513. shouldAskForApprove = true;
  25514. tablesToTruncate.push(tableName);
  25515. statementsToExecute.push(`DELETE FROM \`${tableName}\`;`);
  25516. }
  25517. }
  25518. }
  25519. const tablesReferencingCurrent = [];
  25520. for (const table6 of Object.values(json2.tables)) {
  25521. const tablesRefs = Object.values(json2.tables[table6.name].foreignKeys).filter((t4) => SQLiteSquasher.unsquashPushFK(t4).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
  25522. tablesReferencingCurrent.push(...tablesRefs);
  25523. }
  25524. if (!tablesReferencingCurrent.length) {
  25525. statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss));
  25526. continue;
  25527. }
  25528. const [{ foreign_keys: pragmaState }] = await connection.query(`PRAGMA foreign_keys;`);
  25529. if (pragmaState) {
  25530. statementsToExecute.push(`PRAGMA foreign_keys=OFF;`);
  25531. }
  25532. statementsToExecute.push(..._moveDataStatements(tableName, json2, dataLoss));
  25533. if (pragmaState) {
  25534. statementsToExecute.push(`PRAGMA foreign_keys=ON;`);
  25535. }
  25536. } else {
  25537. const fromJsonStatement = fromJson([statement], "sqlite", "push");
  25538. statementsToExecute.push(
  25539. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  25540. );
  25541. }
  25542. }
  25543. return {
  25544. statementsToExecute,
  25545. shouldAskForApprove,
  25546. infoToPrint,
  25547. columnsToRemove: [...new Set(columnsToRemove)],
  25548. schemasToRemove: [...new Set(schemasToRemove)],
  25549. tablesToTruncate: [...new Set(tablesToTruncate)],
  25550. tablesToRemove: [...new Set(tablesToRemove)]
  25551. };
  25552. };
  25553. }
  25554. });
  25555. // src/jsonStatements.ts
  25556. var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSingleStoreCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateRoleJson, prepareAlterRoleJson, prepareDropRoleJson, prepareRenameRoleJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, prepareRenamePolicyJsons, prepareRenameIndPolicyJsons, prepareCreatePolicyJsons, prepareCreateIndPolicyJsons, prepareDropPolicyJsons, prepareDropIndPolicyJsons, prepareAlterPolicyJson, prepareAlterIndPolicyJson, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCheckConstraint, prepareDeleteCheckConstraint, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView;
  25557. var init_jsonStatements = __esm({
  25558. "src/jsonStatements.ts"() {
  25559. "use strict";
  25560. init_source();
  25561. init_sqlitePushUtils();
  25562. init_views();
  25563. init_mysqlSchema();
  25564. init_pgSchema();
  25565. init_singlestoreSchema();
  25566. init_sqliteSchema();
  25567. preparePgCreateTableJson = (table6, json2) => {
  25568. const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = table6;
  25569. const tableKey2 = `${schema6 || "public"}.${name}`;
  25570. const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json2.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : "";
  25571. return {
  25572. type: "create_table",
  25573. tableName: name,
  25574. schema: schema6,
  25575. columns: Object.values(columns),
  25576. compositePKs: Object.values(compositePrimaryKeys),
  25577. compositePkName,
  25578. uniqueConstraints: Object.values(uniqueConstraints),
  25579. policies: Object.values(policies),
  25580. checkConstraints: Object.values(checkConstraints),
  25581. isRLSEnabled: isRLSEnabled ?? false
  25582. };
  25583. };
  25584. prepareMySqlCreateTableJson = (table6, json2, internals) => {
  25585. const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table6;
  25586. return {
  25587. type: "create_table",
  25588. tableName: name,
  25589. schema: schema6,
  25590. columns: Object.values(columns),
  25591. compositePKs: Object.values(compositePrimaryKeys),
  25592. compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[MySqlSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
  25593. uniqueConstraints: Object.values(uniqueConstraints),
  25594. internals,
  25595. checkConstraints: Object.values(checkConstraints)
  25596. };
  25597. };
  25598. prepareSingleStoreCreateTableJson = (table6, json2, internals) => {
  25599. const { name, schema: schema6, columns, compositePrimaryKeys, uniqueConstraints } = table6;
  25600. return {
  25601. type: "create_table",
  25602. tableName: name,
  25603. schema: schema6,
  25604. columns: Object.values(columns),
  25605. compositePKs: Object.values(compositePrimaryKeys),
  25606. compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json2.tables[name].compositePrimaryKeys[SingleStoreSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
  25607. uniqueConstraints: Object.values(uniqueConstraints),
  25608. internals
  25609. };
  25610. };
  25611. prepareSQLiteCreateTable = (table6, action) => {
  25612. const { name, columns, uniqueConstraints, checkConstraints } = table6;
  25613. const references2 = Object.values(table6.foreignKeys);
  25614. const composites = Object.values(table6.compositePrimaryKeys).map(
  25615. (it) => SQLiteSquasher.unsquashPK(it)
  25616. );
  25617. const fks = references2.map(
  25618. (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
  25619. );
  25620. return {
  25621. type: "sqlite_create_table",
  25622. tableName: name,
  25623. columns: Object.values(columns),
  25624. referenceData: fks,
  25625. compositePKs: composites,
  25626. uniqueConstraints: Object.values(uniqueConstraints),
  25627. checkConstraints: Object.values(checkConstraints)
  25628. };
  25629. };
  25630. prepareDropTableJson = (table6) => {
  25631. return {
  25632. type: "drop_table",
  25633. tableName: table6.name,
  25634. schema: table6.schema,
  25635. policies: table6.policies ? Object.values(table6.policies) : []
  25636. };
  25637. };
  25638. prepareRenameTableJson = (tableFrom, tableTo) => {
  25639. return {
  25640. type: "rename_table",
  25641. fromSchema: tableTo.schema,
  25642. toSchema: tableTo.schema,
  25643. tableNameFrom: tableFrom.name,
  25644. tableNameTo: tableTo.name
  25645. };
  25646. };
  25647. prepareCreateEnumJson = (name, schema6, values) => {
  25648. return {
  25649. type: "create_type_enum",
  25650. name,
  25651. schema: schema6,
  25652. values
  25653. };
  25654. };
  25655. prepareAddValuesToEnumJson = (name, schema6, values) => {
  25656. return values.map((it) => {
  25657. return {
  25658. type: "alter_type_add_value",
  25659. name,
  25660. schema: schema6,
  25661. value: it.value,
  25662. before: it.before
  25663. };
  25664. });
  25665. };
  25666. prepareDropEnumValues = (name, schema6, removedValues, json2) => {
  25667. if (!removedValues.length) return [];
  25668. const affectedColumns = [];
  25669. for (const tableKey2 in json2.tables) {
  25670. const table6 = json2.tables[tableKey2];
  25671. for (const columnKey in table6.columns) {
  25672. const column11 = table6.columns[columnKey];
  25673. const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
  25674. const parsedColumnType = column11.type.replace(arrayDefinitionRegex, "");
  25675. if (parsedColumnType === name && column11.typeSchema === schema6) {
  25676. affectedColumns.push({
  25677. tableSchema: table6.schema,
  25678. table: table6.name,
  25679. column: column11.name,
  25680. columnType: column11.type,
  25681. default: column11.default
  25682. });
  25683. }
  25684. }
  25685. }
  25686. return [{
  25687. type: "alter_type_drop_value",
  25688. name,
  25689. enumSchema: schema6,
  25690. deletedValues: removedValues,
  25691. newValues: json2.enums[`${schema6}.${name}`].values,
  25692. columnsWithEnum: affectedColumns
  25693. }];
  25694. };
  25695. prepareDropEnumJson = (name, schema6) => {
  25696. return {
  25697. type: "drop_type_enum",
  25698. name,
  25699. schema: schema6
  25700. };
  25701. };
  25702. prepareMoveEnumJson = (name, schemaFrom, schemaTo) => {
  25703. return {
  25704. type: "move_type_enum",
  25705. name,
  25706. schemaFrom,
  25707. schemaTo
  25708. };
  25709. };
  25710. prepareRenameEnumJson = (nameFrom, nameTo, schema6) => {
  25711. return {
  25712. type: "rename_type_enum",
  25713. nameFrom,
  25714. nameTo,
  25715. schema: schema6
  25716. };
  25717. };
  25718. prepareCreateSequenceJson = (seq) => {
  25719. const values = PgSquasher.unsquashSequence(seq.values);
  25720. return {
  25721. type: "create_sequence",
  25722. name: seq.name,
  25723. schema: seq.schema,
  25724. values
  25725. };
  25726. };
  25727. prepareAlterSequenceJson = (seq) => {
  25728. const values = PgSquasher.unsquashSequence(seq.values);
  25729. return [
  25730. {
  25731. type: "alter_sequence",
  25732. schema: seq.schema,
  25733. name: seq.name,
  25734. values
  25735. }
  25736. ];
  25737. };
  25738. prepareDropSequenceJson = (name, schema6) => {
  25739. return {
  25740. type: "drop_sequence",
  25741. name,
  25742. schema: schema6
  25743. };
  25744. };
  25745. prepareMoveSequenceJson = (name, schemaFrom, schemaTo) => {
  25746. return {
  25747. type: "move_sequence",
  25748. name,
  25749. schemaFrom,
  25750. schemaTo
  25751. };
  25752. };
  25753. prepareRenameSequenceJson = (nameFrom, nameTo, schema6) => {
  25754. return {
  25755. type: "rename_sequence",
  25756. nameFrom,
  25757. nameTo,
  25758. schema: schema6
  25759. };
  25760. };
  25761. prepareCreateRoleJson = (role) => {
  25762. return {
  25763. type: "create_role",
  25764. name: role.name,
  25765. values: {
  25766. createDb: role.createDb,
  25767. createRole: role.createRole,
  25768. inherit: role.inherit
  25769. }
  25770. };
  25771. };
  25772. prepareAlterRoleJson = (role) => {
  25773. return {
  25774. type: "alter_role",
  25775. name: role.name,
  25776. values: {
  25777. createDb: role.createDb,
  25778. createRole: role.createRole,
  25779. inherit: role.inherit
  25780. }
  25781. };
  25782. };
  25783. prepareDropRoleJson = (name) => {
  25784. return {
  25785. type: "drop_role",
  25786. name
  25787. };
  25788. };
  25789. prepareRenameRoleJson = (nameFrom, nameTo) => {
  25790. return {
  25791. type: "rename_role",
  25792. nameFrom,
  25793. nameTo
  25794. };
  25795. };
  25796. prepareCreateSchemasJson = (values) => {
  25797. return values.map((it) => {
  25798. return {
  25799. type: "create_schema",
  25800. name: it
  25801. };
  25802. });
  25803. };
  25804. prepareRenameSchemasJson = (values) => {
  25805. return values.map((it) => {
  25806. return {
  25807. type: "rename_schema",
  25808. from: it.from,
  25809. to: it.to
  25810. };
  25811. });
  25812. };
  25813. prepareDeleteSchemasJson = (values) => {
  25814. return values.map((it) => {
  25815. return {
  25816. type: "drop_schema",
  25817. name: it
  25818. };
  25819. });
  25820. };
  25821. prepareRenameColumns = (tableName, schema6, pairs) => {
  25822. return pairs.map((it) => {
  25823. return {
  25824. type: "alter_table_rename_column",
  25825. tableName,
  25826. oldColumnName: it.from.name,
  25827. newColumnName: it.to.name,
  25828. schema: schema6
  25829. };
  25830. });
  25831. };
  25832. _prepareDropColumns = (taleName, schema6, columns) => {
  25833. return columns.map((it) => {
  25834. return {
  25835. type: "alter_table_drop_column",
  25836. tableName: taleName,
  25837. columnName: it.name,
  25838. schema: schema6
  25839. };
  25840. });
  25841. };
  25842. _prepareAddColumns = (tableName, schema6, columns) => {
  25843. return columns.map((it) => {
  25844. return {
  25845. type: "alter_table_add_column",
  25846. tableName,
  25847. column: it,
  25848. schema: schema6
  25849. };
  25850. });
  25851. };
  25852. _prepareSqliteAddColumns = (tableName, columns, referenceData) => {
  25853. const unsquashed = referenceData.map((addedFkValue) => SQLiteSquasher.unsquashFK(addedFkValue));
  25854. return columns.map((it) => {
  25855. var _a2;
  25856. const columnsWithReference = unsquashed.find((t4) => t4.columnsFrom.includes(it.name));
  25857. if (((_a2 = it.generated) == null ? void 0 : _a2.type) === "stored") {
  25858. warning(
  25859. `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
  25860. );
  25861. return void 0;
  25862. }
  25863. return {
  25864. type: "sqlite_alter_table_add_column",
  25865. tableName,
  25866. column: it,
  25867. referenceData: columnsWithReference ? SQLiteSquasher.squashFK(columnsWithReference) : void 0
  25868. };
  25869. }).filter(Boolean);
  25870. };
  25871. prepareAlterColumnsMysql = (tableName, schema6, columns, json1, json2, action) => {
  25872. var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o, _p, _q, _r, _s;
  25873. let statements = [];
  25874. let dropPkStatements = [];
  25875. let setPkStatements = [];
  25876. for (const column11 of columns) {
  25877. const columnName = typeof column11.name !== "string" ? column11.name.new : column11.name;
  25878. const table6 = json2.tables[tableName];
  25879. const snapshotColumn = table6.columns[columnName];
  25880. const columnType = snapshotColumn.type;
  25881. const columnDefault = snapshotColumn.default;
  25882. const columnOnUpdate = "onUpdate" in snapshotColumn ? snapshotColumn.onUpdate : void 0;
  25883. const columnNotNull = table6.columns[columnName].notNull;
  25884. const columnAutoIncrement = "autoincrement" in snapshotColumn ? snapshotColumn.autoincrement ?? false : false;
  25885. const columnPk = table6.columns[columnName].primaryKey;
  25886. if (((_a2 = column11.autoincrement) == null ? void 0 : _a2.type) === "added") {
  25887. statements.push({
  25888. type: "alter_table_alter_column_set_autoincrement",
  25889. tableName,
  25890. columnName,
  25891. schema: schema6,
  25892. newDataType: columnType,
  25893. columnDefault,
  25894. columnOnUpdate,
  25895. columnNotNull,
  25896. columnAutoIncrement,
  25897. columnPk
  25898. });
  25899. }
  25900. if (((_b = column11.autoincrement) == null ? void 0 : _b.type) === "changed") {
  25901. const type = column11.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
  25902. statements.push({
  25903. type,
  25904. tableName,
  25905. columnName,
  25906. schema: schema6,
  25907. newDataType: columnType,
  25908. columnDefault,
  25909. columnOnUpdate,
  25910. columnNotNull,
  25911. columnAutoIncrement,
  25912. columnPk
  25913. });
  25914. }
  25915. if (((_c = column11.autoincrement) == null ? void 0 : _c.type) === "deleted") {
  25916. statements.push({
  25917. type: "alter_table_alter_column_drop_autoincrement",
  25918. tableName,
  25919. columnName,
  25920. schema: schema6,
  25921. newDataType: columnType,
  25922. columnDefault,
  25923. columnOnUpdate,
  25924. columnNotNull,
  25925. columnAutoIncrement,
  25926. columnPk
  25927. });
  25928. }
  25929. }
  25930. for (const column11 of columns) {
  25931. const columnName = typeof column11.name !== "string" ? column11.name.new : column11.name;
  25932. const columnType = json2.tables[tableName].columns[columnName].type;
  25933. const columnDefault = json2.tables[tableName].columns[columnName].default;
  25934. const columnGenerated = json2.tables[tableName].columns[columnName].generated;
  25935. const columnOnUpdate = json2.tables[tableName].columns[columnName].onUpdate;
  25936. const columnNotNull = json2.tables[tableName].columns[columnName].notNull;
  25937. const columnAutoIncrement = json2.tables[tableName].columns[columnName].autoincrement;
  25938. const columnPk = json2.tables[tableName].columns[columnName].primaryKey;
  25939. const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
  25940. if (typeof column11.name !== "string") {
  25941. statements.push({
  25942. type: "alter_table_rename_column",
  25943. tableName,
  25944. oldColumnName: column11.name.old,
  25945. newColumnName: column11.name.new,
  25946. schema: schema6
  25947. });
  25948. }
  25949. if (((_d = column11.type) == null ? void 0 : _d.type) === "changed") {
  25950. statements.push({
  25951. type: "alter_table_alter_column_set_type",
  25952. tableName,
  25953. columnName,
  25954. newDataType: column11.type.new,
  25955. oldDataType: column11.type.old,
  25956. schema: schema6,
  25957. columnDefault,
  25958. columnOnUpdate,
  25959. columnNotNull,
  25960. columnAutoIncrement,
  25961. columnPk,
  25962. columnGenerated
  25963. });
  25964. }
  25965. if (((_e = column11.primaryKey) == null ? void 0 : _e.type) === "deleted" || ((_f = column11.primaryKey) == null ? void 0 : _f.type) === "changed" && !column11.primaryKey.new && typeof compositePk === "undefined") {
  25966. dropPkStatements.push({
  25967. ////
  25968. type: "alter_table_alter_column_drop_pk",
  25969. tableName,
  25970. columnName,
  25971. schema: schema6
  25972. });
  25973. }
  25974. if (((_g = column11.default) == null ? void 0 : _g.type) === "added") {
  25975. statements.push({
  25976. type: "alter_table_alter_column_set_default",
  25977. tableName,
  25978. columnName,
  25979. newDefaultValue: column11.default.value,
  25980. schema: schema6,
  25981. columnOnUpdate,
  25982. columnNotNull,
  25983. columnAutoIncrement,
  25984. newDataType: columnType,
  25985. columnPk
  25986. });
  25987. }
  25988. if (((_h = column11.default) == null ? void 0 : _h.type) === "changed") {
  25989. statements.push({
  25990. type: "alter_table_alter_column_set_default",
  25991. tableName,
  25992. columnName,
  25993. newDefaultValue: column11.default.new,
  25994. oldDefaultValue: column11.default.old,
  25995. schema: schema6,
  25996. columnOnUpdate,
  25997. columnNotNull,
  25998. columnAutoIncrement,
  25999. newDataType: columnType,
  26000. columnPk
  26001. });
  26002. }
  26003. if (((_i = column11.default) == null ? void 0 : _i.type) === "deleted") {
  26004. statements.push({
  26005. type: "alter_table_alter_column_drop_default",
  26006. tableName,
  26007. columnName,
  26008. schema: schema6,
  26009. columnDefault,
  26010. columnOnUpdate,
  26011. columnNotNull,
  26012. columnAutoIncrement,
  26013. newDataType: columnType,
  26014. columnPk
  26015. });
  26016. }
  26017. if (((_j = column11.notNull) == null ? void 0 : _j.type) === "added") {
  26018. statements.push({
  26019. type: "alter_table_alter_column_set_notnull",
  26020. tableName,
  26021. columnName,
  26022. schema: schema6,
  26023. newDataType: columnType,
  26024. columnDefault,
  26025. columnOnUpdate,
  26026. columnNotNull,
  26027. columnAutoIncrement,
  26028. columnPk
  26029. });
  26030. }
  26031. if (((_k = column11.notNull) == null ? void 0 : _k.type) === "changed") {
  26032. const type = column11.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
  26033. statements.push({
  26034. type,
  26035. tableName,
  26036. columnName,
  26037. schema: schema6,
  26038. newDataType: columnType,
  26039. columnDefault,
  26040. columnOnUpdate,
  26041. columnNotNull,
  26042. columnAutoIncrement,
  26043. columnPk
  26044. });
  26045. }
  26046. if (((_l = column11.notNull) == null ? void 0 : _l.type) === "deleted") {
  26047. statements.push({
  26048. type: "alter_table_alter_column_drop_notnull",
  26049. tableName,
  26050. columnName,
  26051. schema: schema6,
  26052. newDataType: columnType,
  26053. columnDefault,
  26054. columnOnUpdate,
  26055. columnNotNull,
  26056. columnAutoIncrement,
  26057. columnPk
  26058. });
  26059. }
  26060. if (((_m2 = column11.generated) == null ? void 0 : _m2.type) === "added") {
  26061. if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
  26062. warning(
  26063. `You are trying to add virtual generated constraint to ${source_default.blue(
  26064. columnName
  26065. )} column. As MySQL docs mention: "Nongenerated columns can be altered to stored but not virtual generated columns". We will drop an existing column and add it with a virtual generated statement. This means that the data previously stored in this column will be wiped, and new data will be generated on each read for this column
  26066. `
  26067. );
  26068. }
  26069. statements.push({
  26070. type: "alter_table_alter_column_set_generated",
  26071. tableName,
  26072. columnName,
  26073. schema: schema6,
  26074. newDataType: columnType,
  26075. columnDefault,
  26076. columnOnUpdate,
  26077. columnNotNull,
  26078. columnAutoIncrement,
  26079. columnPk,
  26080. columnGenerated
  26081. });
  26082. }
  26083. if (((_n = column11.generated) == null ? void 0 : _n.type) === "changed" && action !== "push") {
  26084. statements.push({
  26085. type: "alter_table_alter_column_alter_generated",
  26086. tableName,
  26087. columnName,
  26088. schema: schema6,
  26089. newDataType: columnType,
  26090. columnDefault,
  26091. columnOnUpdate,
  26092. columnNotNull,
  26093. columnAutoIncrement,
  26094. columnPk,
  26095. columnGenerated
  26096. });
  26097. }
  26098. if (((_o = column11.generated) == null ? void 0 : _o.type) === "deleted") {
  26099. if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
  26100. warning(
  26101. `You are trying to remove virtual generated constraint from ${source_default.blue(
  26102. columnName
  26103. )} column. As MySQL docs mention: "Stored but not virtual generated columns can be altered to nongenerated columns. The stored generated values become the values of the nongenerated column". We will drop an existing column and add it without a virtual generated statement. This means that this column will have no data after migration
  26104. `
  26105. );
  26106. }
  26107. statements.push({
  26108. type: "alter_table_alter_column_drop_generated",
  26109. tableName,
  26110. columnName,
  26111. schema: schema6,
  26112. newDataType: columnType,
  26113. columnDefault,
  26114. columnOnUpdate,
  26115. columnNotNull,
  26116. columnAutoIncrement,
  26117. columnPk,
  26118. columnGenerated,
  26119. oldColumn: json1.tables[tableName].columns[columnName]
  26120. });
  26121. }
  26122. if (((_p = column11.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column11.primaryKey) == null ? void 0 : _q.type) === "changed" && column11.primaryKey.new) {
  26123. const wasAutoincrement = statements.filter(
  26124. (it) => it.type === "alter_table_alter_column_set_autoincrement"
  26125. );
  26126. if (wasAutoincrement.length === 0) {
  26127. setPkStatements.push({
  26128. type: "alter_table_alter_column_set_pk",
  26129. tableName,
  26130. schema: schema6,
  26131. columnName
  26132. });
  26133. }
  26134. }
  26135. if (((_r = column11.onUpdate) == null ? void 0 : _r.type) === "added") {
  26136. statements.push({
  26137. type: "alter_table_alter_column_set_on_update",
  26138. tableName,
  26139. columnName,
  26140. schema: schema6,
  26141. newDataType: columnType,
  26142. columnDefault,
  26143. columnOnUpdate,
  26144. columnNotNull,
  26145. columnAutoIncrement,
  26146. columnPk
  26147. });
  26148. }
  26149. if (((_s = column11.onUpdate) == null ? void 0 : _s.type) === "deleted") {
  26150. statements.push({
  26151. type: "alter_table_alter_column_drop_on_update",
  26152. tableName,
  26153. columnName,
  26154. schema: schema6,
  26155. newDataType: columnType,
  26156. columnDefault,
  26157. columnOnUpdate,
  26158. columnNotNull,
  26159. columnAutoIncrement,
  26160. columnPk
  26161. });
  26162. }
  26163. }
  26164. return [...dropPkStatements, ...setPkStatements, ...statements];
  26165. };
  26166. preparePgAlterColumns = (_tableName, schema6, columns, json2, json1, action) => {
  26167. var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o, _p, _q, _r, _s;
  26168. const tableKey2 = `${schema6 || "public"}.${_tableName}`;
  26169. let statements = [];
  26170. let dropPkStatements = [];
  26171. let setPkStatements = [];
  26172. for (const column11 of columns) {
  26173. const columnName = typeof column11.name !== "string" ? column11.name.new : column11.name;
  26174. const tableName = json2.tables[tableKey2].name;
  26175. const columnType = json2.tables[tableKey2].columns[columnName].type;
  26176. const columnDefault = json2.tables[tableKey2].columns[columnName].default;
  26177. const columnGenerated = json2.tables[tableKey2].columns[columnName].generated;
  26178. const columnOnUpdate = json2.tables[tableKey2].columns[columnName].onUpdate;
  26179. const columnNotNull = json2.tables[tableKey2].columns[columnName].notNull;
  26180. const columnAutoIncrement = json2.tables[tableKey2].columns[columnName].autoincrement;
  26181. const columnPk = json2.tables[tableKey2].columns[columnName].primaryKey;
  26182. const typeSchema = json2.tables[tableKey2].columns[columnName].typeSchema;
  26183. const json1ColumnTypeSchema = json1.tables[tableKey2].columns[columnName].typeSchema;
  26184. const compositePk = json2.tables[tableKey2].compositePrimaryKeys[`${tableName}_${columnName}`];
  26185. if (typeof column11.name !== "string") {
  26186. statements.push({
  26187. type: "alter_table_rename_column",
  26188. tableName,
  26189. oldColumnName: column11.name.old,
  26190. newColumnName: column11.name.new,
  26191. schema: schema6
  26192. });
  26193. }
  26194. if (((_a2 = column11.type) == null ? void 0 : _a2.type) === "changed") {
  26195. const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
  26196. const parsedNewColumnType = column11.type.new.replace(arrayDefinitionRegex, "");
  26197. const parsedOldColumnType = column11.type.old.replace(arrayDefinitionRegex, "");
  26198. const isNewTypeIsEnum = json2.enums[`${typeSchema}.${parsedNewColumnType}`];
  26199. const isOldTypeIsEnum = json1.enums[`${json1ColumnTypeSchema}.${parsedOldColumnType}`];
  26200. statements.push({
  26201. type: "pg_alter_table_alter_column_set_type",
  26202. tableName,
  26203. columnName,
  26204. typeSchema,
  26205. newDataType: {
  26206. name: column11.type.new,
  26207. isEnum: isNewTypeIsEnum ? true : false
  26208. },
  26209. oldDataType: {
  26210. name: column11.type.old,
  26211. isEnum: isOldTypeIsEnum ? true : false
  26212. },
  26213. schema: schema6,
  26214. columnDefault,
  26215. columnOnUpdate,
  26216. columnNotNull,
  26217. columnAutoIncrement,
  26218. columnPk
  26219. });
  26220. }
  26221. if (((_b = column11.primaryKey) == null ? void 0 : _b.type) === "deleted" || ((_c = column11.primaryKey) == null ? void 0 : _c.type) === "changed" && !column11.primaryKey.new && typeof compositePk === "undefined") {
  26222. dropPkStatements.push({
  26223. ////
  26224. type: "alter_table_alter_column_drop_pk",
  26225. tableName,
  26226. columnName,
  26227. schema: schema6
  26228. });
  26229. }
  26230. if (((_d = column11.default) == null ? void 0 : _d.type) === "added") {
  26231. statements.push({
  26232. type: "alter_table_alter_column_set_default",
  26233. tableName,
  26234. columnName,
  26235. newDefaultValue: column11.default.value,
  26236. schema: schema6,
  26237. columnOnUpdate,
  26238. columnNotNull,
  26239. columnAutoIncrement,
  26240. newDataType: columnType,
  26241. columnPk
  26242. });
  26243. }
  26244. if (((_e = column11.default) == null ? void 0 : _e.type) === "changed") {
  26245. statements.push({
  26246. type: "alter_table_alter_column_set_default",
  26247. tableName,
  26248. columnName,
  26249. newDefaultValue: column11.default.new,
  26250. oldDefaultValue: column11.default.old,
  26251. schema: schema6,
  26252. columnOnUpdate,
  26253. columnNotNull,
  26254. columnAutoIncrement,
  26255. newDataType: columnType,
  26256. columnPk
  26257. });
  26258. }
  26259. if (((_f = column11.default) == null ? void 0 : _f.type) === "deleted") {
  26260. statements.push({
  26261. type: "alter_table_alter_column_drop_default",
  26262. tableName,
  26263. columnName,
  26264. schema: schema6,
  26265. columnDefault,
  26266. columnOnUpdate,
  26267. columnNotNull,
  26268. columnAutoIncrement,
  26269. newDataType: columnType,
  26270. columnPk
  26271. });
  26272. }
  26273. if (((_g = column11.notNull) == null ? void 0 : _g.type) === "added") {
  26274. statements.push({
  26275. type: "alter_table_alter_column_set_notnull",
  26276. tableName,
  26277. columnName,
  26278. schema: schema6,
  26279. newDataType: columnType,
  26280. columnDefault,
  26281. columnOnUpdate,
  26282. columnNotNull,
  26283. columnAutoIncrement,
  26284. columnPk
  26285. });
  26286. }
  26287. if (((_h = column11.notNull) == null ? void 0 : _h.type) === "changed") {
  26288. const type = column11.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
  26289. statements.push({
  26290. type,
  26291. tableName,
  26292. columnName,
  26293. schema: schema6,
  26294. newDataType: columnType,
  26295. columnDefault,
  26296. columnOnUpdate,
  26297. columnNotNull,
  26298. columnAutoIncrement,
  26299. columnPk
  26300. });
  26301. }
  26302. if (((_i = column11.notNull) == null ? void 0 : _i.type) === "deleted") {
  26303. statements.push({
  26304. type: "alter_table_alter_column_drop_notnull",
  26305. tableName,
  26306. columnName,
  26307. schema: schema6,
  26308. newDataType: columnType,
  26309. columnDefault,
  26310. columnOnUpdate,
  26311. columnNotNull,
  26312. columnAutoIncrement,
  26313. columnPk
  26314. });
  26315. }
  26316. if (((_j = column11.identity) == null ? void 0 : _j.type) === "added") {
  26317. statements.push({
  26318. type: "alter_table_alter_column_set_identity",
  26319. tableName,
  26320. columnName,
  26321. schema: schema6,
  26322. identity: column11.identity.value
  26323. });
  26324. }
  26325. if (((_k = column11.identity) == null ? void 0 : _k.type) === "changed") {
  26326. statements.push({
  26327. type: "alter_table_alter_column_change_identity",
  26328. tableName,
  26329. columnName,
  26330. schema: schema6,
  26331. identity: column11.identity.new,
  26332. oldIdentity: column11.identity.old
  26333. });
  26334. }
  26335. if (((_l = column11.identity) == null ? void 0 : _l.type) === "deleted") {
  26336. statements.push({
  26337. type: "alter_table_alter_column_drop_identity",
  26338. tableName,
  26339. columnName,
  26340. schema: schema6
  26341. });
  26342. }
  26343. if (((_m2 = column11.generated) == null ? void 0 : _m2.type) === "added") {
  26344. statements.push({
  26345. type: "alter_table_alter_column_set_generated",
  26346. tableName,
  26347. columnName,
  26348. schema: schema6,
  26349. newDataType: columnType,
  26350. columnDefault,
  26351. columnOnUpdate,
  26352. columnNotNull,
  26353. columnAutoIncrement,
  26354. columnPk,
  26355. columnGenerated
  26356. });
  26357. }
  26358. if (((_n = column11.generated) == null ? void 0 : _n.type) === "changed" && action !== "push") {
  26359. statements.push({
  26360. type: "alter_table_alter_column_alter_generated",
  26361. tableName,
  26362. columnName,
  26363. schema: schema6,
  26364. newDataType: columnType,
  26365. columnDefault,
  26366. columnOnUpdate,
  26367. columnNotNull,
  26368. columnAutoIncrement,
  26369. columnPk,
  26370. columnGenerated
  26371. });
  26372. }
  26373. if (((_o = column11.generated) == null ? void 0 : _o.type) === "deleted") {
  26374. statements.push({
  26375. type: "alter_table_alter_column_drop_generated",
  26376. tableName,
  26377. columnName,
  26378. schema: schema6,
  26379. newDataType: columnType,
  26380. columnDefault,
  26381. columnOnUpdate,
  26382. columnNotNull,
  26383. columnAutoIncrement,
  26384. columnPk,
  26385. columnGenerated
  26386. });
  26387. }
  26388. if (((_p = column11.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column11.primaryKey) == null ? void 0 : _q.type) === "changed" && column11.primaryKey.new) {
  26389. const wasAutoincrement = statements.filter(
  26390. (it) => it.type === "alter_table_alter_column_set_autoincrement"
  26391. );
  26392. if (wasAutoincrement.length === 0) {
  26393. setPkStatements.push({
  26394. type: "alter_table_alter_column_set_pk",
  26395. tableName,
  26396. schema: schema6,
  26397. columnName
  26398. });
  26399. }
  26400. }
  26401. if (((_r = column11.onUpdate) == null ? void 0 : _r.type) === "added") {
  26402. statements.push({
  26403. type: "alter_table_alter_column_set_on_update",
  26404. tableName,
  26405. columnName,
  26406. schema: schema6,
  26407. newDataType: columnType,
  26408. columnDefault,
  26409. columnOnUpdate,
  26410. columnNotNull,
  26411. columnAutoIncrement,
  26412. columnPk
  26413. });
  26414. }
  26415. if (((_s = column11.onUpdate) == null ? void 0 : _s.type) === "deleted") {
  26416. statements.push({
  26417. type: "alter_table_alter_column_drop_on_update",
  26418. tableName,
  26419. columnName,
  26420. schema: schema6,
  26421. newDataType: columnType,
  26422. columnDefault,
  26423. columnOnUpdate,
  26424. columnNotNull,
  26425. columnAutoIncrement,
  26426. columnPk
  26427. });
  26428. }
  26429. }
  26430. return [...dropPkStatements, ...setPkStatements, ...statements];
  26431. };
  26432. prepareSqliteAlterColumns = (tableName, schema6, columns, json2) => {
  26433. var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m2, _n, _o, _p, _q, _r, _s;
  26434. let statements = [];
  26435. let dropPkStatements = [];
  26436. let setPkStatements = [];
  26437. for (const column11 of columns) {
  26438. const columnName = typeof column11.name !== "string" ? column11.name.new : column11.name;
  26439. const columnType = json2.tables[tableName].columns[columnName].type;
  26440. const columnDefault = json2.tables[tableName].columns[columnName].default;
  26441. const columnOnUpdate = json2.tables[tableName].columns[columnName].onUpdate;
  26442. const columnNotNull = json2.tables[tableName].columns[columnName].notNull;
  26443. const columnAutoIncrement = json2.tables[tableName].columns[columnName].autoincrement;
  26444. const columnPk = json2.tables[tableName].columns[columnName].primaryKey;
  26445. const columnGenerated = json2.tables[tableName].columns[columnName].generated;
  26446. const compositePk = json2.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
  26447. if (((_a2 = column11.autoincrement) == null ? void 0 : _a2.type) === "added") {
  26448. statements.push({
  26449. type: "alter_table_alter_column_set_autoincrement",
  26450. tableName,
  26451. columnName,
  26452. schema: schema6,
  26453. newDataType: columnType,
  26454. columnDefault,
  26455. columnOnUpdate,
  26456. columnNotNull,
  26457. columnAutoIncrement,
  26458. columnPk
  26459. });
  26460. }
  26461. if (((_b = column11.autoincrement) == null ? void 0 : _b.type) === "changed") {
  26462. const type = column11.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
  26463. statements.push({
  26464. type,
  26465. tableName,
  26466. columnName,
  26467. schema: schema6,
  26468. newDataType: columnType,
  26469. columnDefault,
  26470. columnOnUpdate,
  26471. columnNotNull,
  26472. columnAutoIncrement,
  26473. columnPk
  26474. });
  26475. }
  26476. if (((_c = column11.autoincrement) == null ? void 0 : _c.type) === "deleted") {
  26477. statements.push({
  26478. type: "alter_table_alter_column_drop_autoincrement",
  26479. tableName,
  26480. columnName,
  26481. schema: schema6,
  26482. newDataType: columnType,
  26483. columnDefault,
  26484. columnOnUpdate,
  26485. columnNotNull,
  26486. columnAutoIncrement,
  26487. columnPk
  26488. });
  26489. }
  26490. if (typeof column11.name !== "string") {
  26491. statements.push({
  26492. type: "alter_table_rename_column",
  26493. tableName,
  26494. oldColumnName: column11.name.old,
  26495. newColumnName: column11.name.new,
  26496. schema: schema6
  26497. });
  26498. }
  26499. if (((_d = column11.type) == null ? void 0 : _d.type) === "changed") {
  26500. statements.push({
  26501. type: "alter_table_alter_column_set_type",
  26502. tableName,
  26503. columnName,
  26504. newDataType: column11.type.new,
  26505. oldDataType: column11.type.old,
  26506. schema: schema6,
  26507. columnDefault,
  26508. columnOnUpdate,
  26509. columnNotNull,
  26510. columnAutoIncrement,
  26511. columnPk
  26512. });
  26513. }
  26514. if (((_e = column11.primaryKey) == null ? void 0 : _e.type) === "deleted" || ((_f = column11.primaryKey) == null ? void 0 : _f.type) === "changed" && !column11.primaryKey.new && typeof compositePk === "undefined") {
  26515. dropPkStatements.push({
  26516. ////
  26517. type: "alter_table_alter_column_drop_pk",
  26518. tableName,
  26519. columnName,
  26520. schema: schema6
  26521. });
  26522. }
  26523. if (((_g = column11.default) == null ? void 0 : _g.type) === "added") {
  26524. statements.push({
  26525. type: "alter_table_alter_column_set_default",
  26526. tableName,
  26527. columnName,
  26528. newDefaultValue: column11.default.value,
  26529. schema: schema6,
  26530. columnOnUpdate,
  26531. columnNotNull,
  26532. columnAutoIncrement,
  26533. newDataType: columnType,
  26534. columnPk
  26535. });
  26536. }
  26537. if (((_h = column11.default) == null ? void 0 : _h.type) === "changed") {
  26538. statements.push({
  26539. type: "alter_table_alter_column_set_default",
  26540. tableName,
  26541. columnName,
  26542. newDefaultValue: column11.default.new,
  26543. oldDefaultValue: column11.default.old,
  26544. schema: schema6,
  26545. columnOnUpdate,
  26546. columnNotNull,
  26547. columnAutoIncrement,
  26548. newDataType: columnType,
  26549. columnPk
  26550. });
  26551. }
  26552. if (((_i = column11.default) == null ? void 0 : _i.type) === "deleted") {
  26553. statements.push({
  26554. type: "alter_table_alter_column_drop_default",
  26555. tableName,
  26556. columnName,
  26557. schema: schema6,
  26558. columnDefault,
  26559. columnOnUpdate,
  26560. columnNotNull,
  26561. columnAutoIncrement,
  26562. newDataType: columnType,
  26563. columnPk
  26564. });
  26565. }
  26566. if (((_j = column11.notNull) == null ? void 0 : _j.type) === "added") {
  26567. statements.push({
  26568. type: "alter_table_alter_column_set_notnull",
  26569. tableName,
  26570. columnName,
  26571. schema: schema6,
  26572. newDataType: columnType,
  26573. columnDefault,
  26574. columnOnUpdate,
  26575. columnNotNull,
  26576. columnAutoIncrement,
  26577. columnPk
  26578. });
  26579. }
  26580. if (((_k = column11.notNull) == null ? void 0 : _k.type) === "changed") {
  26581. const type = column11.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
  26582. statements.push({
  26583. type,
  26584. tableName,
  26585. columnName,
  26586. schema: schema6,
  26587. newDataType: columnType,
  26588. columnDefault,
  26589. columnOnUpdate,
  26590. columnNotNull,
  26591. columnAutoIncrement,
  26592. columnPk
  26593. });
  26594. }
  26595. if (((_l = column11.notNull) == null ? void 0 : _l.type) === "deleted") {
  26596. statements.push({
  26597. type: "alter_table_alter_column_drop_notnull",
  26598. tableName,
  26599. columnName,
  26600. schema: schema6,
  26601. newDataType: columnType,
  26602. columnDefault,
  26603. columnOnUpdate,
  26604. columnNotNull,
  26605. columnAutoIncrement,
  26606. columnPk
  26607. });
  26608. }
  26609. if (((_m2 = column11.generated) == null ? void 0 : _m2.type) === "added") {
  26610. if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
  26611. statements.push({
  26612. type: "alter_table_alter_column_set_generated",
  26613. tableName,
  26614. columnName,
  26615. schema: schema6,
  26616. newDataType: columnType,
  26617. columnDefault,
  26618. columnOnUpdate,
  26619. columnNotNull,
  26620. columnAutoIncrement,
  26621. columnPk,
  26622. columnGenerated
  26623. });
  26624. } else {
  26625. warning(
  26626. `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
  26627. );
  26628. }
  26629. }
  26630. if (((_n = column11.generated) == null ? void 0 : _n.type) === "changed") {
  26631. if ((columnGenerated == null ? void 0 : columnGenerated.type) === "virtual") {
  26632. statements.push({
  26633. type: "alter_table_alter_column_alter_generated",
  26634. tableName,
  26635. columnName,
  26636. schema: schema6,
  26637. newDataType: columnType,
  26638. columnDefault,
  26639. columnOnUpdate,
  26640. columnNotNull,
  26641. columnAutoIncrement,
  26642. columnPk,
  26643. columnGenerated
  26644. });
  26645. } else {
  26646. warning(
  26647. `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
  26648. );
  26649. }
  26650. }
  26651. if (((_o = column11.generated) == null ? void 0 : _o.type) === "deleted") {
  26652. statements.push({
  26653. type: "alter_table_alter_column_drop_generated",
  26654. tableName,
  26655. columnName,
  26656. schema: schema6,
  26657. newDataType: columnType,
  26658. columnDefault,
  26659. columnOnUpdate,
  26660. columnNotNull,
  26661. columnAutoIncrement,
  26662. columnPk,
  26663. columnGenerated
  26664. });
  26665. }
  26666. if (((_p = column11.primaryKey) == null ? void 0 : _p.type) === "added" || ((_q = column11.primaryKey) == null ? void 0 : _q.type) === "changed" && column11.primaryKey.new) {
  26667. const wasAutoincrement = statements.filter(
  26668. (it) => it.type === "alter_table_alter_column_set_autoincrement"
  26669. );
  26670. if (wasAutoincrement.length === 0) {
  26671. setPkStatements.push({
  26672. type: "alter_table_alter_column_set_pk",
  26673. tableName,
  26674. schema: schema6,
  26675. columnName
  26676. });
  26677. }
  26678. }
  26679. if (((_r = column11.onUpdate) == null ? void 0 : _r.type) === "added") {
  26680. statements.push({
  26681. type: "alter_table_alter_column_set_on_update",
  26682. tableName,
  26683. columnName,
  26684. schema: schema6,
  26685. newDataType: columnType,
  26686. columnDefault,
  26687. columnOnUpdate,
  26688. columnNotNull,
  26689. columnAutoIncrement,
  26690. columnPk
  26691. });
  26692. }
  26693. if (((_s = column11.onUpdate) == null ? void 0 : _s.type) === "deleted") {
  26694. statements.push({
  26695. type: "alter_table_alter_column_drop_on_update",
  26696. tableName,
  26697. columnName,
  26698. schema: schema6,
  26699. newDataType: columnType,
  26700. columnDefault,
  26701. columnOnUpdate,
  26702. columnNotNull,
  26703. columnAutoIncrement,
  26704. columnPk
  26705. });
  26706. }
  26707. }
  26708. return [...dropPkStatements, ...setPkStatements, ...statements];
  26709. };
  26710. prepareRenamePolicyJsons = (tableName, schema6, renames) => {
  26711. return renames.map((it) => {
  26712. return {
  26713. type: "rename_policy",
  26714. tableName,
  26715. oldName: it.from.name,
  26716. newName: it.to.name,
  26717. schema: schema6
  26718. };
  26719. });
  26720. };
  26721. prepareRenameIndPolicyJsons = (renames) => {
  26722. return renames.map((it) => {
  26723. return {
  26724. type: "rename_ind_policy",
  26725. tableKey: it.from.on,
  26726. oldName: it.from.name,
  26727. newName: it.to.name
  26728. };
  26729. });
  26730. };
  26731. prepareCreatePolicyJsons = (tableName, schema6, policies) => {
  26732. return policies.map((it) => {
  26733. return {
  26734. type: "create_policy",
  26735. tableName,
  26736. data: it,
  26737. schema: schema6
  26738. };
  26739. });
  26740. };
  26741. prepareCreateIndPolicyJsons = (policies) => {
  26742. return policies.map((it) => {
  26743. return {
  26744. type: "create_ind_policy",
  26745. tableName: it.on,
  26746. data: it
  26747. };
  26748. });
  26749. };
  26750. prepareDropPolicyJsons = (tableName, schema6, policies) => {
  26751. return policies.map((it) => {
  26752. return {
  26753. type: "drop_policy",
  26754. tableName,
  26755. data: it,
  26756. schema: schema6
  26757. };
  26758. });
  26759. };
  26760. prepareDropIndPolicyJsons = (policies) => {
  26761. return policies.map((it) => {
  26762. return {
  26763. type: "drop_ind_policy",
  26764. tableName: it.on,
  26765. data: it
  26766. };
  26767. });
  26768. };
  26769. prepareAlterPolicyJson = (tableName, schema6, oldPolicy, newPolicy) => {
  26770. return {
  26771. type: "alter_policy",
  26772. tableName,
  26773. oldData: oldPolicy,
  26774. newData: newPolicy,
  26775. schema: schema6
  26776. };
  26777. };
  26778. prepareAlterIndPolicyJson = (oldPolicy, newPolicy) => {
  26779. return {
  26780. type: "alter_ind_policy",
  26781. oldData: oldPolicy,
  26782. newData: newPolicy
  26783. };
  26784. };
  26785. preparePgCreateIndexesJson = (tableName, schema6, indexes, fullSchema, action) => {
  26786. if (action === "push") {
  26787. return Object.values(indexes).map((indexData) => {
  26788. const unsquashedIndex = PgSquasher.unsquashIdxPush(indexData);
  26789. const data = fullSchema.tables[`${schema6 === "" ? "public" : schema6}.${tableName}`].indexes[unsquashedIndex.name];
  26790. return {
  26791. type: "create_index_pg",
  26792. tableName,
  26793. data,
  26794. schema: schema6
  26795. };
  26796. });
  26797. }
  26798. return Object.values(indexes).map((indexData) => {
  26799. return {
  26800. type: "create_index_pg",
  26801. tableName,
  26802. data: PgSquasher.unsquashIdx(indexData),
  26803. schema: schema6
  26804. };
  26805. });
  26806. };
  26807. prepareCreateIndexesJson = (tableName, schema6, indexes, internal) => {
  26808. return Object.values(indexes).map((indexData) => {
  26809. return {
  26810. type: "create_index",
  26811. tableName,
  26812. data: indexData,
  26813. schema: schema6,
  26814. internal
  26815. };
  26816. });
  26817. };
  26818. prepareCreateReferencesJson = (tableName, schema6, foreignKeys) => {
  26819. return Object.values(foreignKeys).map((fkData) => {
  26820. return {
  26821. type: "create_reference",
  26822. tableName,
  26823. data: fkData,
  26824. schema: schema6
  26825. };
  26826. });
  26827. };
  26828. prepareLibSQLCreateReferencesJson = (tableName, schema6, foreignKeys, json2, action) => {
  26829. return Object.values(foreignKeys).map((fkData) => {
  26830. const { columnsFrom, tableFrom, columnsTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
  26831. let isMulticolumn = false;
  26832. if (columnsFrom.length > 1 || columnsTo.length > 1) {
  26833. isMulticolumn = true;
  26834. return {
  26835. type: "create_reference",
  26836. tableName,
  26837. data: fkData,
  26838. schema: schema6,
  26839. isMulticolumn
  26840. };
  26841. }
  26842. const columnFrom = columnsFrom[0];
  26843. const {
  26844. notNull: columnNotNull,
  26845. default: columnDefault,
  26846. type: columnType
  26847. } = json2.tables[tableFrom].columns[columnFrom];
  26848. return {
  26849. type: "create_reference",
  26850. tableName,
  26851. data: fkData,
  26852. schema: schema6,
  26853. columnNotNull,
  26854. columnDefault,
  26855. columnType
  26856. };
  26857. });
  26858. };
  26859. prepareDropReferencesJson = (tableName, schema6, foreignKeys) => {
  26860. return Object.values(foreignKeys).map((fkData) => {
  26861. return {
  26862. type: "delete_reference",
  26863. tableName,
  26864. data: fkData,
  26865. schema: schema6
  26866. };
  26867. });
  26868. };
  26869. prepareLibSQLDropReferencesJson = (tableName, schema6, foreignKeys, json2, meta, action) => {
  26870. const statements = Object.values(foreignKeys).map((fkData) => {
  26871. const { columnsFrom, tableFrom, columnsTo, name, tableTo, onDelete, onUpdate } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
  26872. const keys = Object.keys(json2.tables[tableName].columns);
  26873. const filtered = columnsFrom.filter((it) => keys.includes(it));
  26874. const fullDrop = filtered.length === 0;
  26875. if (fullDrop) return;
  26876. let isMulticolumn = false;
  26877. if (columnsFrom.length > 1 || columnsTo.length > 1) {
  26878. isMulticolumn = true;
  26879. return {
  26880. type: "delete_reference",
  26881. tableName,
  26882. data: fkData,
  26883. schema: schema6,
  26884. isMulticolumn
  26885. };
  26886. }
  26887. const columnFrom = columnsFrom[0];
  26888. const newTableName = getNewTableName(tableFrom, meta);
  26889. const {
  26890. notNull: columnNotNull,
  26891. default: columnDefault,
  26892. type: columnType
  26893. } = json2.tables[newTableName].columns[columnFrom];
  26894. const fkToSquash = {
  26895. columnsFrom,
  26896. columnsTo,
  26897. name,
  26898. tableFrom: newTableName,
  26899. tableTo,
  26900. onDelete,
  26901. onUpdate
  26902. };
  26903. const foreignKey = action === "push" ? SQLiteSquasher.squashPushFK(fkToSquash) : SQLiteSquasher.squashFK(fkToSquash);
  26904. return {
  26905. type: "delete_reference",
  26906. tableName,
  26907. data: foreignKey,
  26908. schema: schema6,
  26909. columnNotNull,
  26910. columnDefault,
  26911. columnType
  26912. };
  26913. });
  26914. return statements.filter((it) => it);
  26915. };
  26916. prepareAlterReferencesJson = (tableName, schema6, foreignKeys) => {
  26917. const stmts = [];
  26918. Object.values(foreignKeys).map((val2) => {
  26919. stmts.push({
  26920. type: "delete_reference",
  26921. tableName,
  26922. schema: schema6,
  26923. data: val2.__old
  26924. });
  26925. stmts.push({
  26926. type: "create_reference",
  26927. tableName,
  26928. schema: schema6,
  26929. data: val2.__new
  26930. });
  26931. });
  26932. return stmts;
  26933. };
  26934. prepareDropIndexesJson = (tableName, schema6, indexes) => {
  26935. return Object.values(indexes).map((indexData) => {
  26936. return {
  26937. type: "drop_index",
  26938. tableName,
  26939. data: indexData,
  26940. schema: schema6
  26941. };
  26942. });
  26943. };
  26944. prepareAddCompositePrimaryKeySqlite = (tableName, pks) => {
  26945. return Object.values(pks).map((it) => {
  26946. return {
  26947. type: "create_composite_pk",
  26948. tableName,
  26949. data: it
  26950. };
  26951. });
  26952. };
  26953. prepareDeleteCompositePrimaryKeySqlite = (tableName, pks) => {
  26954. return Object.values(pks).map((it) => {
  26955. return {
  26956. type: "delete_composite_pk",
  26957. tableName,
  26958. data: it
  26959. };
  26960. });
  26961. };
  26962. prepareAlterCompositePrimaryKeySqlite = (tableName, pks) => {
  26963. return Object.values(pks).map((it) => {
  26964. return {
  26965. type: "alter_composite_pk",
  26966. tableName,
  26967. old: it.__old,
  26968. new: it.__new
  26969. };
  26970. });
  26971. };
  26972. prepareAddCompositePrimaryKeyPg = (tableName, schema6, pks, json2) => {
  26973. return Object.values(pks).map((it) => {
  26974. const unsquashed = PgSquasher.unsquashPK(it);
  26975. return {
  26976. type: "create_composite_pk",
  26977. tableName,
  26978. data: it,
  26979. schema: schema6,
  26980. constraintName: PgSquasher.unsquashPK(it).name
  26981. };
  26982. });
  26983. };
  26984. prepareDeleteCompositePrimaryKeyPg = (tableName, schema6, pks, json1) => {
  26985. return Object.values(pks).map((it) => {
  26986. return {
  26987. type: "delete_composite_pk",
  26988. tableName,
  26989. data: it,
  26990. schema: schema6,
  26991. constraintName: PgSquasher.unsquashPK(it).name
  26992. };
  26993. });
  26994. };
  26995. prepareAlterCompositePrimaryKeyPg = (tableName, schema6, pks, json1, json2) => {
  26996. return Object.values(pks).map((it) => {
  26997. return {
  26998. type: "alter_composite_pk",
  26999. tableName,
  27000. old: it.__old,
  27001. new: it.__new,
  27002. schema: schema6,
  27003. oldConstraintName: PgSquasher.unsquashPK(it.__old).name,
  27004. newConstraintName: PgSquasher.unsquashPK(it.__new).name
  27005. };
  27006. });
  27007. };
  27008. prepareAddUniqueConstraintPg = (tableName, schema6, unqs) => {
  27009. return Object.values(unqs).map((it) => {
  27010. return {
  27011. type: "create_unique_constraint",
  27012. tableName,
  27013. data: it,
  27014. schema: schema6
  27015. };
  27016. });
  27017. };
  27018. prepareDeleteUniqueConstraintPg = (tableName, schema6, unqs) => {
  27019. return Object.values(unqs).map((it) => {
  27020. return {
  27021. type: "delete_unique_constraint",
  27022. tableName,
  27023. data: it,
  27024. schema: schema6
  27025. };
  27026. });
  27027. };
  27028. prepareAddCheckConstraint = (tableName, schema6, check2) => {
  27029. return Object.values(check2).map((it) => {
  27030. return {
  27031. type: "create_check_constraint",
  27032. tableName,
  27033. data: it,
  27034. schema: schema6
  27035. };
  27036. });
  27037. };
  27038. prepareDeleteCheckConstraint = (tableName, schema6, check2) => {
  27039. return Object.values(check2).map((it) => {
  27040. return {
  27041. type: "delete_check_constraint",
  27042. tableName,
  27043. constraintName: PgSquasher.unsquashCheck(it).name,
  27044. schema: schema6
  27045. };
  27046. });
  27047. };
  27048. prepareAddCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => {
  27049. var _a2, _b;
  27050. const res = [];
  27051. for (const it of Object.values(pks)) {
  27052. const unsquashed = MySqlSquasher.unsquashPK(it);
  27053. if (unsquashed.columns.length === 1 && ((_b = (_a2 = json1.tables[tableName]) == null ? void 0 : _a2.columns[unsquashed.columns[0]]) == null ? void 0 : _b.primaryKey)) {
  27054. continue;
  27055. }
  27056. res.push({
  27057. type: "create_composite_pk",
  27058. tableName,
  27059. data: it,
  27060. constraintName: unsquashed.name
  27061. });
  27062. }
  27063. return res;
  27064. };
  27065. prepareDeleteCompositePrimaryKeyMySql = (tableName, pks, json1) => {
  27066. return Object.values(pks).map((it) => {
  27067. const unsquashed = MySqlSquasher.unsquashPK(it);
  27068. return {
  27069. type: "delete_composite_pk",
  27070. tableName,
  27071. data: it
  27072. };
  27073. });
  27074. };
  27075. prepareAlterCompositePrimaryKeyMySql = (tableName, pks, json1, json2) => {
  27076. return Object.values(pks).map((it) => {
  27077. return {
  27078. type: "alter_composite_pk",
  27079. tableName,
  27080. old: it.__old,
  27081. new: it.__new,
  27082. oldConstraintName: json1.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__old).name].name,
  27083. newConstraintName: json2.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__new).name].name
  27084. };
  27085. });
  27086. };
  27087. preparePgCreateViewJson = (name, schema6, definition, materialized, withNoData = false, withOption, using, tablespace) => {
  27088. return {
  27089. type: "create_view",
  27090. name,
  27091. schema: schema6,
  27092. definition,
  27093. with: withOption,
  27094. materialized,
  27095. withNoData,
  27096. using,
  27097. tablespace
  27098. };
  27099. };
  27100. prepareMySqlCreateViewJson = (name, definition, meta, replace = false) => {
  27101. const { algorithm, sqlSecurity, withCheckOption } = MySqlSquasher.unsquashView(meta);
  27102. return {
  27103. type: "mysql_create_view",
  27104. name,
  27105. definition,
  27106. algorithm,
  27107. sqlSecurity,
  27108. withCheckOption,
  27109. replace
  27110. };
  27111. };
  27112. prepareSqliteCreateViewJson = (name, definition) => {
  27113. return {
  27114. type: "sqlite_create_view",
  27115. name,
  27116. definition
  27117. };
  27118. };
  27119. prepareDropViewJson = (name, schema6, materialized) => {
  27120. const resObject = { name, type: "drop_view" };
  27121. if (schema6) resObject["schema"] = schema6;
  27122. if (materialized) resObject["materialized"] = materialized;
  27123. return resObject;
  27124. };
  27125. prepareRenameViewJson = (to, from, schema6, materialized) => {
  27126. const resObject = {
  27127. type: "rename_view",
  27128. nameTo: to,
  27129. nameFrom: from
  27130. };
  27131. if (schema6) resObject["schema"] = schema6;
  27132. if (materialized) resObject["materialized"] = materialized;
  27133. return resObject;
  27134. };
  27135. preparePgAlterViewAlterSchemaJson = (to, from, name, materialized) => {
  27136. const returnObject = {
  27137. type: "alter_view_alter_schema",
  27138. fromSchema: from,
  27139. toSchema: to,
  27140. name
  27141. };
  27142. if (materialized) returnObject["materialized"] = materialized;
  27143. return returnObject;
  27144. };
  27145. preparePgAlterViewAddWithOptionJson = (name, schema6, materialized, withOption) => {
  27146. return {
  27147. type: "alter_view_add_with_option",
  27148. name,
  27149. schema: schema6,
  27150. materialized,
  27151. with: withOption
  27152. };
  27153. };
  27154. preparePgAlterViewDropWithOptionJson = (name, schema6, materialized, withOption) => {
  27155. return {
  27156. type: "alter_view_drop_with_option",
  27157. name,
  27158. schema: schema6,
  27159. materialized,
  27160. with: withOption
  27161. };
  27162. };
  27163. preparePgAlterViewAlterTablespaceJson = (name, schema6, materialized, to) => {
  27164. return {
  27165. type: "alter_view_alter_tablespace",
  27166. name,
  27167. schema: schema6,
  27168. materialized,
  27169. toTablespace: to
  27170. };
  27171. };
  27172. preparePgAlterViewAlterUsingJson = (name, schema6, materialized, to) => {
  27173. return {
  27174. type: "alter_view_alter_using",
  27175. name,
  27176. schema: schema6,
  27177. materialized,
  27178. toUsing: to
  27179. };
  27180. };
  27181. prepareMySqlAlterView = (view5) => {
  27182. return { type: "alter_mysql_view", ...view5 };
  27183. };
  27184. }
  27185. });
  27186. // src/statementCombiner.ts
  27187. var prepareLibSQLRecreateTable, prepareSQLiteRecreateTable, libSQLCombineStatements, sqliteCombineStatements, prepareSingleStoreRecreateTable, singleStoreCombineStatements;
  27188. var init_statementCombiner = __esm({
  27189. "src/statementCombiner.ts"() {
  27190. "use strict";
  27191. init_jsonStatements();
  27192. init_sqliteSchema();
  27193. prepareLibSQLRecreateTable = (table6, action) => {
  27194. const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6;
  27195. const composites = Object.values(table6.compositePrimaryKeys).map(
  27196. (it) => SQLiteSquasher.unsquashPK(it)
  27197. );
  27198. const references2 = Object.values(table6.foreignKeys);
  27199. const fks = references2.map(
  27200. (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
  27201. );
  27202. const statements = [
  27203. {
  27204. type: "recreate_table",
  27205. tableName: name,
  27206. columns: Object.values(columns),
  27207. compositePKs: composites,
  27208. referenceData: fks,
  27209. uniqueConstraints: Object.values(uniqueConstraints),
  27210. checkConstraints: Object.values(checkConstraints)
  27211. }
  27212. ];
  27213. if (Object.keys(indexes).length) {
  27214. statements.push(...prepareCreateIndexesJson(name, "", indexes));
  27215. }
  27216. return statements;
  27217. };
  27218. prepareSQLiteRecreateTable = (table6, action) => {
  27219. const { name, columns, uniqueConstraints, indexes, checkConstraints } = table6;
  27220. const composites = Object.values(table6.compositePrimaryKeys).map(
  27221. (it) => SQLiteSquasher.unsquashPK(it)
  27222. );
  27223. const references2 = Object.values(table6.foreignKeys);
  27224. const fks = references2.map(
  27225. (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
  27226. );
  27227. const statements = [
  27228. {
  27229. type: "recreate_table",
  27230. tableName: name,
  27231. columns: Object.values(columns),
  27232. compositePKs: composites,
  27233. referenceData: fks,
  27234. uniqueConstraints: Object.values(uniqueConstraints),
  27235. checkConstraints: Object.values(checkConstraints)
  27236. }
  27237. ];
  27238. if (Object.keys(indexes).length) {
  27239. statements.push(...prepareCreateIndexesJson(name, "", indexes));
  27240. }
  27241. return statements;
  27242. };
  27243. libSQLCombineStatements = (statements, json2, action) => {
  27244. const newStatements = {};
  27245. for (const statement of statements) {
  27246. if (statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
  27247. const tableName2 = statement.tableName;
  27248. const statementsForTable2 = newStatements[tableName2];
  27249. if (!statementsForTable2) {
  27250. newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  27251. continue;
  27252. }
  27253. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27254. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  27255. const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  27256. if (wasRename) {
  27257. newStatements[tableName2].push(...preparedStatements);
  27258. } else {
  27259. newStatements[tableName2] = preparedStatements;
  27260. }
  27261. continue;
  27262. }
  27263. continue;
  27264. }
  27265. if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default") {
  27266. const { tableName: tableName2, columnName, columnPk } = statement;
  27267. const columnIsPartOfForeignKey = Object.values(
  27268. json2.tables[tableName2].foreignKeys
  27269. ).some((it) => {
  27270. const unsquashFk = action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it);
  27271. return unsquashFk.columnsFrom.includes(columnName);
  27272. });
  27273. const statementsForTable2 = newStatements[tableName2];
  27274. if (!statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) {
  27275. newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  27276. continue;
  27277. }
  27278. if (statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) {
  27279. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27280. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  27281. const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  27282. if (wasRename) {
  27283. newStatements[tableName2].push(...preparedStatements);
  27284. } else {
  27285. newStatements[tableName2] = preparedStatements;
  27286. }
  27287. }
  27288. continue;
  27289. }
  27290. if (statementsForTable2 && !(columnIsPartOfForeignKey || columnPk)) {
  27291. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27292. newStatements[tableName2].push(statement);
  27293. }
  27294. continue;
  27295. }
  27296. newStatements[tableName2] = [statement];
  27297. continue;
  27298. }
  27299. if (statement.type === "create_reference") {
  27300. const tableName2 = statement.tableName;
  27301. const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
  27302. const statementsForTable2 = newStatements[tableName2];
  27303. if (!statementsForTable2) {
  27304. newStatements[tableName2] = statement.isMulticolumn ? prepareLibSQLRecreateTable(json2.tables[tableName2], action) : [statement];
  27305. continue;
  27306. }
  27307. if (!statement.isMulticolumn && statementsForTable2.some(
  27308. (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
  27309. )) {
  27310. continue;
  27311. }
  27312. if (statement.isMulticolumn) {
  27313. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27314. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  27315. const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  27316. if (wasRename) {
  27317. newStatements[tableName2].push(...preparedStatements);
  27318. } else {
  27319. newStatements[tableName2] = preparedStatements;
  27320. }
  27321. continue;
  27322. }
  27323. continue;
  27324. }
  27325. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27326. newStatements[tableName2].push(statement);
  27327. }
  27328. continue;
  27329. }
  27330. if (statement.type === "delete_reference") {
  27331. const tableName2 = statement.tableName;
  27332. const statementsForTable2 = newStatements[tableName2];
  27333. if (!statementsForTable2) {
  27334. newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  27335. continue;
  27336. }
  27337. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27338. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  27339. const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  27340. if (wasRename) {
  27341. newStatements[tableName2].push(...preparedStatements);
  27342. } else {
  27343. newStatements[tableName2] = preparedStatements;
  27344. }
  27345. continue;
  27346. }
  27347. continue;
  27348. }
  27349. if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
  27350. const tableName2 = statement.tableName;
  27351. const statementsForTable2 = newStatements[tableName2];
  27352. if (!statementsForTable2) {
  27353. newStatements[tableName2] = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  27354. continue;
  27355. }
  27356. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27357. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  27358. const preparedStatements = prepareLibSQLRecreateTable(json2.tables[tableName2], action);
  27359. if (wasRename) {
  27360. newStatements[tableName2].push(...preparedStatements);
  27361. } else {
  27362. newStatements[tableName2] = preparedStatements;
  27363. }
  27364. continue;
  27365. }
  27366. continue;
  27367. }
  27368. const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
  27369. const statementsForTable = newStatements[tableName];
  27370. if (!statementsForTable) {
  27371. newStatements[tableName] = [statement];
  27372. continue;
  27373. }
  27374. if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
  27375. newStatements[tableName].push(statement);
  27376. }
  27377. }
  27378. const combinedStatements = Object.values(newStatements).flat();
  27379. const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
  27380. const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
  27381. const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
  27382. return [...renamedTables, ...renamedColumns, ...rest];
  27383. };
  27384. sqliteCombineStatements = (statements, json2, action) => {
  27385. const newStatements = {};
  27386. for (const statement of statements) {
  27387. if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "delete_reference" || statement.type === "alter_reference" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_unique_constraint" || statement.type === "delete_unique_constraint" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
  27388. const tableName2 = statement.tableName;
  27389. const statementsForTable2 = newStatements[tableName2];
  27390. if (!statementsForTable2) {
  27391. newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  27392. continue;
  27393. }
  27394. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27395. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  27396. const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  27397. if (wasRename) {
  27398. newStatements[tableName2].push(...preparedStatements);
  27399. } else {
  27400. newStatements[tableName2] = preparedStatements;
  27401. }
  27402. continue;
  27403. }
  27404. continue;
  27405. }
  27406. if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
  27407. const tableName2 = statement.tableName;
  27408. const statementsForTable2 = newStatements[tableName2];
  27409. if (!statementsForTable2) {
  27410. newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  27411. continue;
  27412. }
  27413. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27414. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  27415. const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  27416. if (wasRename) {
  27417. newStatements[tableName2].push(...preparedStatements);
  27418. } else {
  27419. newStatements[tableName2] = preparedStatements;
  27420. }
  27421. continue;
  27422. }
  27423. continue;
  27424. }
  27425. if (statement.type === "create_reference") {
  27426. const tableName2 = statement.tableName;
  27427. const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
  27428. const statementsForTable2 = newStatements[tableName2];
  27429. if (!statementsForTable2) {
  27430. newStatements[tableName2] = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  27431. continue;
  27432. }
  27433. if (data.columnsFrom.length === 1 && statementsForTable2.some(
  27434. (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
  27435. )) {
  27436. continue;
  27437. }
  27438. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27439. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  27440. const preparedStatements = prepareSQLiteRecreateTable(json2.tables[tableName2], action);
  27441. if (wasRename) {
  27442. newStatements[tableName2].push(...preparedStatements);
  27443. } else {
  27444. newStatements[tableName2] = preparedStatements;
  27445. }
  27446. continue;
  27447. }
  27448. continue;
  27449. }
  27450. const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
  27451. const statementsForTable = newStatements[tableName];
  27452. if (!statementsForTable) {
  27453. newStatements[tableName] = [statement];
  27454. continue;
  27455. }
  27456. if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
  27457. newStatements[tableName].push(statement);
  27458. }
  27459. }
  27460. const combinedStatements = Object.values(newStatements).flat();
  27461. const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
  27462. const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
  27463. const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
  27464. return [...renamedTables, ...renamedColumns, ...rest];
  27465. };
  27466. prepareSingleStoreRecreateTable = (table6) => {
  27467. const { name, columns, uniqueConstraints, indexes, compositePrimaryKeys } = table6;
  27468. const composites = Object.values(compositePrimaryKeys);
  27469. const statements = [
  27470. {
  27471. type: "singlestore_recreate_table",
  27472. tableName: name,
  27473. columns: Object.values(columns),
  27474. compositePKs: composites,
  27475. uniqueConstraints: Object.values(uniqueConstraints)
  27476. }
  27477. ];
  27478. if (Object.keys(indexes).length) {
  27479. statements.push(...prepareCreateIndexesJson(name, "", indexes));
  27480. }
  27481. return statements;
  27482. };
  27483. singleStoreCombineStatements = (statements, json2) => {
  27484. const newStatements = {};
  27485. for (const statement of statements) {
  27486. if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk") {
  27487. const tableName2 = statement.tableName;
  27488. const statementsForTable2 = newStatements[tableName2];
  27489. if (!statementsForTable2) {
  27490. newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  27491. continue;
  27492. }
  27493. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27494. const wasRename = statementsForTable2.some(
  27495. ({ type }) => type === "rename_table" || type === "alter_table_rename_column"
  27496. );
  27497. const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  27498. if (wasRename) {
  27499. newStatements[tableName2].push(...preparedStatements);
  27500. } else {
  27501. newStatements[tableName2] = preparedStatements;
  27502. }
  27503. continue;
  27504. }
  27505. continue;
  27506. }
  27507. if ((statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_default") && statement.columnNotNull) {
  27508. const tableName2 = statement.tableName;
  27509. const statementsForTable2 = newStatements[tableName2];
  27510. if (!statementsForTable2) {
  27511. newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  27512. continue;
  27513. }
  27514. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27515. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  27516. const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  27517. if (wasRename) {
  27518. newStatements[tableName2].push(...preparedStatements);
  27519. } else {
  27520. newStatements[tableName2] = preparedStatements;
  27521. }
  27522. continue;
  27523. }
  27524. continue;
  27525. }
  27526. if (statement.type === "alter_table_add_column" && statement.column.primaryKey) {
  27527. const tableName2 = statement.tableName;
  27528. const statementsForTable2 = newStatements[tableName2];
  27529. if (!statementsForTable2) {
  27530. newStatements[tableName2] = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  27531. continue;
  27532. }
  27533. if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
  27534. const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
  27535. const preparedStatements = prepareSingleStoreRecreateTable(json2.tables[tableName2]);
  27536. if (wasRename) {
  27537. newStatements[tableName2].push(...preparedStatements);
  27538. } else {
  27539. newStatements[tableName2] = preparedStatements;
  27540. }
  27541. continue;
  27542. }
  27543. continue;
  27544. }
  27545. const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
  27546. const statementsForTable = newStatements[tableName];
  27547. if (!statementsForTable) {
  27548. newStatements[tableName] = [statement];
  27549. continue;
  27550. }
  27551. if (!statementsForTable.some(({ type }) => type === "singlestore_recreate_table")) {
  27552. newStatements[tableName].push(statement);
  27553. }
  27554. }
  27555. const combinedStatements = Object.values(newStatements).flat();
  27556. const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
  27557. const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
  27558. const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
  27559. return [...renamedTables, ...renamedColumns, ...rest];
  27560. };
  27561. }
  27562. });
  27563. // src/snapshotsDiffer.ts
  27564. var makeChanged, makeSelfOrChanged, makePatched, columnSchema, alteredColumnSchema, enumSchema3, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewCommon, alteredPgViewSchema, alteredMySqlViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSingleStore, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySingleStoreSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
  27565. var init_snapshotsDiffer = __esm({
  27566. "src/snapshotsDiffer.ts"() {
  27567. "use strict";
  27568. init_esm();
  27569. init_jsonDiffer();
  27570. init_sqlgenerator();
  27571. init_jsonStatements();
  27572. init_global();
  27573. init_mysqlSchema();
  27574. init_pgSchema();
  27575. init_singlestoreSchema();
  27576. init_sqliteSchema();
  27577. init_statementCombiner();
  27578. init_utils2();
  27579. makeChanged = (schema6) => {
  27580. return objectType({
  27581. type: enumType(["changed"]),
  27582. old: schema6,
  27583. new: schema6
  27584. });
  27585. };
  27586. makeSelfOrChanged = (schema6) => {
  27587. return unionType([
  27588. schema6,
  27589. objectType({
  27590. type: enumType(["changed"]),
  27591. old: schema6,
  27592. new: schema6
  27593. })
  27594. ]);
  27595. };
  27596. makePatched = (schema6) => {
  27597. return unionType([
  27598. objectType({
  27599. type: literalType("added"),
  27600. value: schema6
  27601. }),
  27602. objectType({
  27603. type: literalType("deleted"),
  27604. value: schema6
  27605. }),
  27606. objectType({
  27607. type: literalType("changed"),
  27608. old: schema6,
  27609. new: schema6
  27610. })
  27611. ]);
  27612. };
  27613. columnSchema = objectType({
  27614. name: stringType(),
  27615. type: stringType(),
  27616. typeSchema: stringType().optional(),
  27617. primaryKey: booleanType().optional(),
  27618. default: anyType().optional(),
  27619. notNull: booleanType().optional(),
  27620. // should it be optional? should if be here?
  27621. autoincrement: booleanType().optional(),
  27622. onUpdate: booleanType().optional(),
  27623. isUnique: anyType().optional(),
  27624. uniqueName: stringType().optional(),
  27625. nullsNotDistinct: booleanType().optional(),
  27626. generated: objectType({
  27627. as: stringType(),
  27628. type: enumType(["stored", "virtual"]).default("stored")
  27629. }).optional(),
  27630. identity: stringType().optional()
  27631. }).strict();
  27632. alteredColumnSchema = objectType({
  27633. name: makeSelfOrChanged(stringType()),
  27634. type: makeChanged(stringType()).optional(),
  27635. default: makePatched(anyType()).optional(),
  27636. primaryKey: makePatched(booleanType()).optional(),
  27637. notNull: makePatched(booleanType()).optional(),
  27638. typeSchema: makePatched(stringType()).optional(),
  27639. onUpdate: makePatched(booleanType()).optional(),
  27640. autoincrement: makePatched(booleanType()).optional(),
  27641. generated: makePatched(
  27642. objectType({
  27643. as: stringType(),
  27644. type: enumType(["stored", "virtual"]).default("stored")
  27645. })
  27646. ).optional(),
  27647. identity: makePatched(stringType()).optional()
  27648. }).strict();
  27649. enumSchema3 = objectType({
  27650. name: stringType(),
  27651. schema: stringType(),
  27652. values: arrayType(stringType())
  27653. }).strict();
  27654. changedEnumSchema = objectType({
  27655. name: stringType(),
  27656. schema: stringType(),
  27657. addedValues: objectType({
  27658. before: stringType(),
  27659. value: stringType()
  27660. }).array(),
  27661. deletedValues: arrayType(stringType())
  27662. }).strict();
  27663. tableScheme = objectType({
  27664. name: stringType(),
  27665. schema: stringType().default(""),
  27666. columns: recordType(stringType(), columnSchema),
  27667. indexes: recordType(stringType(), stringType()),
  27668. foreignKeys: recordType(stringType(), stringType()),
  27669. compositePrimaryKeys: recordType(stringType(), stringType()).default({}),
  27670. uniqueConstraints: recordType(stringType(), stringType()).default({}),
  27671. policies: recordType(stringType(), stringType()).default({}),
  27672. checkConstraints: recordType(stringType(), stringType()).default({}),
  27673. isRLSEnabled: booleanType().default(false)
  27674. }).strict();
  27675. alteredTableScheme = objectType({
  27676. name: stringType(),
  27677. schema: stringType(),
  27678. altered: alteredColumnSchema.array(),
  27679. addedIndexes: recordType(stringType(), stringType()),
  27680. deletedIndexes: recordType(stringType(), stringType()),
  27681. alteredIndexes: recordType(
  27682. stringType(),
  27683. objectType({
  27684. __new: stringType(),
  27685. __old: stringType()
  27686. }).strict()
  27687. ),
  27688. addedForeignKeys: recordType(stringType(), stringType()),
  27689. deletedForeignKeys: recordType(stringType(), stringType()),
  27690. alteredForeignKeys: recordType(
  27691. stringType(),
  27692. objectType({
  27693. __new: stringType(),
  27694. __old: stringType()
  27695. }).strict()
  27696. ),
  27697. addedCompositePKs: recordType(stringType(), stringType()),
  27698. deletedCompositePKs: recordType(stringType(), stringType()),
  27699. alteredCompositePKs: recordType(
  27700. stringType(),
  27701. objectType({
  27702. __new: stringType(),
  27703. __old: stringType()
  27704. })
  27705. ),
  27706. addedUniqueConstraints: recordType(stringType(), stringType()),
  27707. deletedUniqueConstraints: recordType(stringType(), stringType()),
  27708. alteredUniqueConstraints: recordType(
  27709. stringType(),
  27710. objectType({
  27711. __new: stringType(),
  27712. __old: stringType()
  27713. })
  27714. ),
  27715. addedPolicies: recordType(stringType(), stringType()),
  27716. deletedPolicies: recordType(stringType(), stringType()),
  27717. alteredPolicies: recordType(
  27718. stringType(),
  27719. objectType({
  27720. __new: stringType(),
  27721. __old: stringType()
  27722. })
  27723. ),
  27724. addedCheckConstraints: recordType(
  27725. stringType(),
  27726. stringType()
  27727. ),
  27728. deletedCheckConstraints: recordType(
  27729. stringType(),
  27730. stringType()
  27731. ),
  27732. alteredCheckConstraints: recordType(
  27733. stringType(),
  27734. objectType({
  27735. __new: stringType(),
  27736. __old: stringType()
  27737. })
  27738. )
  27739. }).strict();
  27740. alteredViewCommon = objectType({
  27741. name: stringType(),
  27742. alteredDefinition: objectType({
  27743. __old: stringType(),
  27744. __new: stringType()
  27745. }).strict().optional(),
  27746. alteredExisting: objectType({
  27747. __old: booleanType(),
  27748. __new: booleanType()
  27749. }).strict().optional()
  27750. });
  27751. alteredPgViewSchema = alteredViewCommon.merge(
  27752. objectType({
  27753. schema: stringType(),
  27754. deletedWithOption: mergedViewWithOption.optional(),
  27755. addedWithOption: mergedViewWithOption.optional(),
  27756. addedWith: mergedViewWithOption.optional(),
  27757. deletedWith: mergedViewWithOption.optional(),
  27758. alteredWith: mergedViewWithOption.optional(),
  27759. alteredSchema: objectType({
  27760. __old: stringType(),
  27761. __new: stringType()
  27762. }).strict().optional(),
  27763. alteredTablespace: objectType({
  27764. __old: stringType(),
  27765. __new: stringType()
  27766. }).strict().optional(),
  27767. alteredUsing: objectType({
  27768. __old: stringType(),
  27769. __new: stringType()
  27770. }).strict().optional()
  27771. }).strict()
  27772. );
  27773. alteredMySqlViewSchema = alteredViewCommon.merge(
  27774. objectType({
  27775. alteredMeta: objectType({
  27776. __old: stringType(),
  27777. __new: stringType()
  27778. }).strict().optional()
  27779. }).strict()
  27780. );
  27781. diffResultScheme = objectType({
  27782. alteredTablesWithColumns: alteredTableScheme.array(),
  27783. alteredEnums: changedEnumSchema.array(),
  27784. alteredSequences: sequenceSquashed.array(),
  27785. alteredRoles: roleSchema.array(),
  27786. alteredPolicies: policySquashed.array(),
  27787. alteredViews: alteredPgViewSchema.array()
  27788. }).strict();
  27789. diffResultSchemeMysql = objectType({
  27790. alteredTablesWithColumns: alteredTableScheme.array(),
  27791. alteredEnums: neverType().array(),
  27792. alteredViews: alteredMySqlViewSchema.array()
  27793. });
  27794. diffResultSchemeSingleStore = objectType({
  27795. alteredTablesWithColumns: alteredTableScheme.array(),
  27796. alteredEnums: neverType().array()
  27797. });
  27798. diffResultSchemeSQLite = objectType({
  27799. alteredTablesWithColumns: alteredTableScheme.array(),
  27800. alteredEnums: neverType().array(),
  27801. alteredViews: alteredViewCommon.array()
  27802. });
  27803. schemaChangeFor = (table6, renamedSchemas) => {
  27804. for (let ren of renamedSchemas) {
  27805. if (table6.schema === ren.from.name) {
  27806. return { key: `${ren.to.name}.${table6.name}`, schema: ren.to.name };
  27807. }
  27808. }
  27809. return {
  27810. key: `${table6.schema || "public"}.${table6.name}`,
  27811. schema: table6.schema
  27812. };
  27813. };
  27814. nameChangeFor = (table6, renamed) => {
  27815. for (let ren of renamed) {
  27816. if (table6.name === ren.from.name) {
  27817. return { name: ren.to.name };
  27818. }
  27819. }
  27820. return {
  27821. name: table6.name
  27822. };
  27823. };
  27824. nameSchemaChangeFor = (table6, renamedTables) => {
  27825. for (let ren of renamedTables) {
  27826. if (table6.name === ren.from.name && table6.schema === ren.from.schema) {
  27827. return {
  27828. key: `${ren.to.schema || "public"}.${ren.to.name}`,
  27829. name: ren.to.name,
  27830. schema: ren.to.schema
  27831. };
  27832. }
  27833. }
  27834. return {
  27835. key: `${table6.schema || "public"}.${table6.name}`,
  27836. name: table6.name,
  27837. schema: table6.schema
  27838. };
  27839. };
  27840. columnChangeFor = (column11, renamedColumns) => {
  27841. for (let ren of renamedColumns) {
  27842. if (column11 === ren.from.name) {
  27843. return ren.to.name;
  27844. }
  27845. }
  27846. return column11;
  27847. };
  27848. applyPgSnapshotsDiff = async (json1, json2, schemasResolver2, enumsResolver2, sequencesResolver2, policyResolver2, indPolicyResolver2, roleResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
  27849. const schemasDiff = diffSchemasOrTables(json1.schemas, json2.schemas);
  27850. const {
  27851. created: createdSchemas,
  27852. deleted: deletedSchemas,
  27853. renamed: renamedSchemas
  27854. } = await schemasResolver2({
  27855. created: schemasDiff.added.map((it) => ({ name: it })),
  27856. deleted: schemasDiff.deleted.map((it) => ({ name: it }))
  27857. });
  27858. const schemasPatchedSnap1 = copy(json1);
  27859. schemasPatchedSnap1.tables = mapEntries(
  27860. schemasPatchedSnap1.tables,
  27861. (_3, it) => {
  27862. const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
  27863. it.schema = schema6;
  27864. return [key, it];
  27865. }
  27866. );
  27867. schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => {
  27868. const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
  27869. it.schema = schema6;
  27870. return [key, it];
  27871. });
  27872. const enumsDiff = diffSchemasOrTables(schemasPatchedSnap1.enums, json2.enums);
  27873. const {
  27874. created: createdEnums,
  27875. deleted: deletedEnums,
  27876. renamed: renamedEnums,
  27877. moved: movedEnums
  27878. } = await enumsResolver2({
  27879. created: enumsDiff.added,
  27880. deleted: enumsDiff.deleted
  27881. });
  27882. schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_3, it) => {
  27883. const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedEnums);
  27884. it.name = name;
  27885. it.schema = schema6;
  27886. return [key, it];
  27887. });
  27888. const columnTypesChangeMap = renamedEnums.reduce(
  27889. (acc, it) => {
  27890. acc[`${it.from.schema}.${it.from.name}`] = {
  27891. nameFrom: it.from.name,
  27892. nameTo: it.to.name,
  27893. schemaFrom: it.from.schema,
  27894. schemaTo: it.to.schema
  27895. };
  27896. return acc;
  27897. },
  27898. {}
  27899. );
  27900. const columnTypesMovesMap = movedEnums.reduce(
  27901. (acc, it) => {
  27902. acc[`${it.schemaFrom}.${it.name}`] = {
  27903. nameFrom: it.name,
  27904. nameTo: it.name,
  27905. schemaFrom: it.schemaFrom,
  27906. schemaTo: it.schemaTo
  27907. };
  27908. return acc;
  27909. },
  27910. {}
  27911. );
  27912. schemasPatchedSnap1.tables = mapEntries(
  27913. schemasPatchedSnap1.tables,
  27914. (tableKey2, tableValue) => {
  27915. const patchedColumns = mapValues(tableValue.columns, (column11) => {
  27916. const key = `${column11.typeSchema || "public"}.${column11.type}`;
  27917. const change = columnTypesChangeMap[key] || columnTypesMovesMap[key];
  27918. if (change) {
  27919. column11.type = change.nameTo;
  27920. column11.typeSchema = change.schemaTo;
  27921. }
  27922. return column11;
  27923. });
  27924. tableValue.columns = patchedColumns;
  27925. return [tableKey2, tableValue];
  27926. }
  27927. );
  27928. schemasPatchedSnap1.sequences = mapEntries(
  27929. schemasPatchedSnap1.sequences,
  27930. (_3, it) => {
  27931. const { key, schema: schema6 } = schemaChangeFor(it, renamedSchemas);
  27932. it.schema = schema6;
  27933. return [key, it];
  27934. }
  27935. );
  27936. const sequencesDiff = diffSchemasOrTables(
  27937. schemasPatchedSnap1.sequences,
  27938. json2.sequences
  27939. );
  27940. const {
  27941. created: createdSequences,
  27942. deleted: deletedSequences,
  27943. renamed: renamedSequences,
  27944. moved: movedSequences
  27945. } = await sequencesResolver2({
  27946. created: sequencesDiff.added,
  27947. deleted: sequencesDiff.deleted
  27948. });
  27949. schemasPatchedSnap1.sequences = mapEntries(
  27950. schemasPatchedSnap1.sequences,
  27951. (_3, it) => {
  27952. const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedSequences);
  27953. it.name = name;
  27954. it.schema = schema6;
  27955. return [key, it];
  27956. }
  27957. );
  27958. const sequencesChangeMap = renamedSequences.reduce(
  27959. (acc, it) => {
  27960. acc[`${it.from.schema}.${it.from.name}`] = {
  27961. nameFrom: it.from.name,
  27962. nameTo: it.to.name,
  27963. schemaFrom: it.from.schema,
  27964. schemaTo: it.to.schema
  27965. };
  27966. return acc;
  27967. },
  27968. {}
  27969. );
  27970. const sequencesMovesMap = movedSequences.reduce(
  27971. (acc, it) => {
  27972. acc[`${it.schemaFrom}.${it.name}`] = {
  27973. nameFrom: it.name,
  27974. nameTo: it.name,
  27975. schemaFrom: it.schemaFrom,
  27976. schemaTo: it.schemaTo
  27977. };
  27978. return acc;
  27979. },
  27980. {}
  27981. );
  27982. schemasPatchedSnap1.tables = mapEntries(
  27983. schemasPatchedSnap1.tables,
  27984. (tableKey2, tableValue) => {
  27985. const patchedColumns = mapValues(tableValue.columns, (column11) => {
  27986. const key = `${column11.typeSchema || "public"}.${column11.type}`;
  27987. const change = sequencesChangeMap[key] || sequencesMovesMap[key];
  27988. if (change) {
  27989. column11.type = change.nameTo;
  27990. column11.typeSchema = change.schemaTo;
  27991. }
  27992. return column11;
  27993. });
  27994. tableValue.columns = patchedColumns;
  27995. return [tableKey2, tableValue];
  27996. }
  27997. );
  27998. const rolesDiff = diffSchemasOrTables(
  27999. schemasPatchedSnap1.roles,
  28000. json2.roles
  28001. );
  28002. const {
  28003. created: createdRoles,
  28004. deleted: deletedRoles,
  28005. renamed: renamedRoles
  28006. } = await roleResolver2({
  28007. created: rolesDiff.added,
  28008. deleted: rolesDiff.deleted
  28009. });
  28010. schemasPatchedSnap1.roles = mapEntries(
  28011. schemasPatchedSnap1.roles,
  28012. (_3, it) => {
  28013. const { name } = nameChangeFor(it, renamedRoles);
  28014. it.name = name;
  28015. return [name, it];
  28016. }
  28017. );
  28018. const rolesChangeMap = renamedRoles.reduce(
  28019. (acc, it) => {
  28020. acc[it.from.name] = {
  28021. nameFrom: it.from.name,
  28022. nameTo: it.to.name
  28023. };
  28024. return acc;
  28025. },
  28026. {}
  28027. );
  28028. schemasPatchedSnap1.roles = mapEntries(
  28029. schemasPatchedSnap1.roles,
  28030. (roleKey, roleValue) => {
  28031. const key = roleKey;
  28032. const change = rolesChangeMap[key];
  28033. if (change) {
  28034. roleValue.name = change.nameTo;
  28035. }
  28036. return [roleKey, roleValue];
  28037. }
  28038. );
  28039. const tablesDiff = diffSchemasOrTables(
  28040. schemasPatchedSnap1.tables,
  28041. json2.tables
  28042. );
  28043. const {
  28044. created: createdTables,
  28045. deleted: deletedTables,
  28046. moved: movedTables,
  28047. renamed: renamedTables
  28048. // renamed or moved
  28049. } = await tablesResolver2({
  28050. created: tablesDiff.added,
  28051. deleted: tablesDiff.deleted
  28052. });
  28053. const tablesPatchedSnap1 = copy(schemasPatchedSnap1);
  28054. tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
  28055. const { key, name, schema: schema6 } = nameSchemaChangeFor(it, renamedTables);
  28056. it.name = name;
  28057. it.schema = schema6;
  28058. return [key, it];
  28059. });
  28060. const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
  28061. const columnRenames = [];
  28062. const columnCreates = [];
  28063. const columnDeletes = [];
  28064. for (let entry of Object.values(res)) {
  28065. const { renamed, created: created2, deleted: deleted2 } = await columnsResolver2({
  28066. tableName: entry.name,
  28067. schema: entry.schema,
  28068. deleted: entry.columns.deleted,
  28069. created: entry.columns.added
  28070. });
  28071. if (created2.length > 0) {
  28072. columnCreates.push({
  28073. table: entry.name,
  28074. schema: entry.schema,
  28075. columns: created2
  28076. });
  28077. }
  28078. if (deleted2.length > 0) {
  28079. columnDeletes.push({
  28080. table: entry.name,
  28081. schema: entry.schema,
  28082. columns: deleted2
  28083. });
  28084. }
  28085. if (renamed.length > 0) {
  28086. columnRenames.push({
  28087. table: entry.name,
  28088. schema: entry.schema,
  28089. renames: renamed
  28090. });
  28091. }
  28092. }
  28093. const columnRenamesDict = columnRenames.reduce(
  28094. (acc, it) => {
  28095. acc[`${it.schema || "public"}.${it.table}`] = it.renames;
  28096. return acc;
  28097. },
  28098. {}
  28099. );
  28100. const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
  28101. columnsPatchedSnap1.tables = mapEntries(
  28102. columnsPatchedSnap1.tables,
  28103. (tableKey2, tableValue) => {
  28104. const patchedColumns = mapKeys(
  28105. tableValue.columns,
  28106. (columnKey, column11) => {
  28107. const rens = columnRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
  28108. const newName = columnChangeFor(columnKey, rens);
  28109. column11.name = newName;
  28110. return newName;
  28111. }
  28112. );
  28113. tableValue.columns = patchedColumns;
  28114. return [tableKey2, tableValue];
  28115. }
  28116. );
  28117. const policyRes = diffPolicies(tablesPatchedSnap1.tables, json2.tables);
  28118. const policyRenames = [];
  28119. const policyCreates = [];
  28120. const policyDeletes = [];
  28121. for (let entry of Object.values(policyRes)) {
  28122. const { renamed, created: created2, deleted: deleted2 } = await policyResolver2({
  28123. tableName: entry.name,
  28124. schema: entry.schema,
  28125. deleted: entry.policies.deleted.map(
  28126. action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy
  28127. ),
  28128. created: entry.policies.added.map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy)
  28129. });
  28130. if (created2.length > 0) {
  28131. policyCreates.push({
  28132. table: entry.name,
  28133. schema: entry.schema,
  28134. columns: created2
  28135. });
  28136. }
  28137. if (deleted2.length > 0) {
  28138. policyDeletes.push({
  28139. table: entry.name,
  28140. schema: entry.schema,
  28141. columns: deleted2
  28142. });
  28143. }
  28144. if (renamed.length > 0) {
  28145. policyRenames.push({
  28146. table: entry.name,
  28147. schema: entry.schema,
  28148. renames: renamed
  28149. });
  28150. }
  28151. }
  28152. const policyRenamesDict = columnRenames.reduce(
  28153. (acc, it) => {
  28154. acc[`${it.schema || "public"}.${it.table}`] = it.renames;
  28155. return acc;
  28156. },
  28157. {}
  28158. );
  28159. const policyPatchedSnap1 = copy(tablesPatchedSnap1);
  28160. policyPatchedSnap1.tables = mapEntries(
  28161. policyPatchedSnap1.tables,
  28162. (tableKey2, tableValue) => {
  28163. const patchedPolicies = mapKeys(
  28164. tableValue.policies,
  28165. (policyKey, policy5) => {
  28166. const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
  28167. const newName = columnChangeFor(policyKey, rens);
  28168. const unsquashedPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(policy5) : PgSquasher.unsquashPolicy(policy5);
  28169. unsquashedPolicy.name = newName;
  28170. policy5 = PgSquasher.squashPolicy(unsquashedPolicy);
  28171. return newName;
  28172. }
  28173. );
  28174. tableValue.policies = patchedPolicies;
  28175. return [tableKey2, tableValue];
  28176. }
  28177. );
  28178. const indPolicyRes = diffIndPolicies(policyPatchedSnap1.policies, json2.policies);
  28179. const indPolicyCreates = [];
  28180. const indPolicyDeletes = [];
  28181. const { renamed: indPolicyRenames, created, deleted } = await indPolicyResolver2({
  28182. deleted: indPolicyRes.deleted.map(
  28183. (t4) => action === "push" ? PgSquasher.unsquashPolicyPush(t4.values) : PgSquasher.unsquashPolicy(t4.values)
  28184. ),
  28185. created: indPolicyRes.added.map(
  28186. (t4) => action === "push" ? PgSquasher.unsquashPolicyPush(t4.values) : PgSquasher.unsquashPolicy(t4.values)
  28187. )
  28188. });
  28189. if (created.length > 0) {
  28190. indPolicyCreates.push({
  28191. policies: created
  28192. });
  28193. }
  28194. if (deleted.length > 0) {
  28195. indPolicyDeletes.push({
  28196. policies: deleted
  28197. });
  28198. }
  28199. const indPolicyRenamesDict = indPolicyRenames.reduce(
  28200. (acc, it) => {
  28201. acc[it.from.name] = {
  28202. nameFrom: it.from.name,
  28203. nameTo: it.to.name
  28204. };
  28205. return acc;
  28206. },
  28207. {}
  28208. );
  28209. const indPolicyPatchedSnap1 = copy(policyPatchedSnap1);
  28210. indPolicyPatchedSnap1.policies = mapEntries(
  28211. indPolicyPatchedSnap1.policies,
  28212. (policyKey, policyValue) => {
  28213. const key = policyKey;
  28214. const change = indPolicyRenamesDict[key];
  28215. if (change) {
  28216. policyValue.name = change.nameTo;
  28217. }
  28218. return [policyKey, policyValue];
  28219. }
  28220. );
  28221. const viewsDiff = diffSchemasOrTables(indPolicyPatchedSnap1.views, json2.views);
  28222. const {
  28223. created: createdViews,
  28224. deleted: deletedViews,
  28225. renamed: renamedViews,
  28226. moved: movedViews
  28227. } = await viewsResolver2({
  28228. created: viewsDiff.added,
  28229. deleted: viewsDiff.deleted
  28230. });
  28231. const renamesViewDic = {};
  28232. renamedViews.forEach((it) => {
  28233. renamesViewDic[`${it.from.schema}.${it.from.name}`] = { to: it.to.name, from: it.from.name };
  28234. });
  28235. const movedViewDic = {};
  28236. movedViews.forEach((it) => {
  28237. movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom };
  28238. });
  28239. const viewsPatchedSnap1 = copy(policyPatchedSnap1);
  28240. viewsPatchedSnap1.views = mapEntries(
  28241. viewsPatchedSnap1.views,
  28242. (viewKey, viewValue) => {
  28243. const rename = renamesViewDic[`${viewValue.schema}.${viewValue.name}`];
  28244. const moved = movedViewDic[`${viewValue.schema}.${viewValue.name}`];
  28245. if (rename) {
  28246. viewValue.name = rename.to;
  28247. viewKey = `${viewValue.schema}.${viewValue.name}`;
  28248. }
  28249. if (moved) viewKey = `${moved.to}.${viewValue.name}`;
  28250. return [viewKey, viewValue];
  28251. }
  28252. );
  28253. const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
  28254. const typedResult = diffResultScheme.parse(diffResult);
  28255. const jsonStatements = [];
  28256. const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
  28257. return preparePgCreateIndexesJson(
  28258. it.name,
  28259. it.schema,
  28260. it.indexes,
  28261. curFull,
  28262. action
  28263. );
  28264. }).flat();
  28265. const jsonDropTables = deletedTables.map((it) => {
  28266. return prepareDropTableJson(it);
  28267. });
  28268. const jsonRenameTables = renamedTables.map((it) => {
  28269. return prepareRenameTableJson(it.from, it.to);
  28270. });
  28271. const alteredTables = typedResult.alteredTablesWithColumns;
  28272. const jsonRenameColumnsStatements = [];
  28273. const jsonDropColumnsStatemets = [];
  28274. const jsonAddColumnsStatemets = [];
  28275. for (let it of columnRenames) {
  28276. jsonRenameColumnsStatements.push(
  28277. ...prepareRenameColumns(it.table, it.schema, it.renames)
  28278. );
  28279. }
  28280. for (let it of columnDeletes) {
  28281. jsonDropColumnsStatemets.push(
  28282. ..._prepareDropColumns(it.table, it.schema, it.columns)
  28283. );
  28284. }
  28285. for (let it of columnCreates) {
  28286. jsonAddColumnsStatemets.push(
  28287. ..._prepareAddColumns(it.table, it.schema, it.columns)
  28288. );
  28289. }
  28290. const jsonAddedCompositePKs = [];
  28291. const jsonDeletedCompositePKs = [];
  28292. const jsonAlteredCompositePKs = [];
  28293. const jsonAddedUniqueConstraints = [];
  28294. const jsonDeletedUniqueConstraints = [];
  28295. const jsonAlteredUniqueConstraints = [];
  28296. const jsonSetTableSchemas = [];
  28297. if (movedTables) {
  28298. for (let it of movedTables) {
  28299. jsonSetTableSchemas.push({
  28300. type: "alter_table_set_schema",
  28301. tableName: it.name,
  28302. schemaFrom: it.schemaFrom || "public",
  28303. schemaTo: it.schemaTo || "public"
  28304. });
  28305. }
  28306. }
  28307. const jsonDeletedCheckConstraints = [];
  28308. const jsonCreatedCheckConstraints = [];
  28309. for (let it of alteredTables) {
  28310. let addedColumns;
  28311. for (const addedPkName of Object.keys(it.addedCompositePKs)) {
  28312. const addedPkColumns = it.addedCompositePKs[addedPkName];
  28313. addedColumns = PgSquasher.unsquashPK(addedPkColumns);
  28314. }
  28315. let deletedColumns;
  28316. for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
  28317. const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
  28318. deletedColumns = PgSquasher.unsquashPK(deletedPkColumns);
  28319. }
  28320. const doPerformDeleteAndCreate = JSON.stringify(addedColumns ?? {}) !== JSON.stringify(deletedColumns ?? {});
  28321. let addedCompositePKs = [];
  28322. let deletedCompositePKs = [];
  28323. let alteredCompositePKs = [];
  28324. if (doPerformDeleteAndCreate) {
  28325. addedCompositePKs = prepareAddCompositePrimaryKeyPg(
  28326. it.name,
  28327. it.schema,
  28328. it.addedCompositePKs,
  28329. curFull
  28330. );
  28331. deletedCompositePKs = prepareDeleteCompositePrimaryKeyPg(
  28332. it.name,
  28333. it.schema,
  28334. it.deletedCompositePKs,
  28335. prevFull
  28336. );
  28337. }
  28338. alteredCompositePKs = prepareAlterCompositePrimaryKeyPg(
  28339. it.name,
  28340. it.schema,
  28341. it.alteredCompositePKs,
  28342. prevFull,
  28343. curFull
  28344. );
  28345. let addedUniqueConstraints = [];
  28346. let deletedUniqueConstraints = [];
  28347. let alteredUniqueConstraints = [];
  28348. let createCheckConstraints = [];
  28349. let deleteCheckConstraints = [];
  28350. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  28351. it.name,
  28352. it.schema,
  28353. it.addedUniqueConstraints
  28354. );
  28355. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  28356. it.name,
  28357. it.schema,
  28358. it.deletedUniqueConstraints
  28359. );
  28360. if (it.alteredUniqueConstraints) {
  28361. const added = {};
  28362. const deleted2 = {};
  28363. for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
  28364. added[k3] = it.alteredUniqueConstraints[k3].__new;
  28365. deleted2[k3] = it.alteredUniqueConstraints[k3].__old;
  28366. }
  28367. addedUniqueConstraints.push(
  28368. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  28369. );
  28370. deletedUniqueConstraints.push(
  28371. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted2)
  28372. );
  28373. }
  28374. createCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
  28375. deleteCheckConstraints = prepareDeleteCheckConstraint(
  28376. it.name,
  28377. it.schema,
  28378. it.deletedCheckConstraints
  28379. );
  28380. if (it.alteredCheckConstraints && action !== "push") {
  28381. const added = {};
  28382. const deleted2 = {};
  28383. for (const k3 of Object.keys(it.alteredCheckConstraints)) {
  28384. added[k3] = it.alteredCheckConstraints[k3].__new;
  28385. deleted2[k3] = it.alteredCheckConstraints[k3].__old;
  28386. }
  28387. createCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
  28388. deleteCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted2));
  28389. }
  28390. jsonCreatedCheckConstraints.push(...createCheckConstraints);
  28391. jsonDeletedCheckConstraints.push(...deleteCheckConstraints);
  28392. jsonAddedCompositePKs.push(...addedCompositePKs);
  28393. jsonDeletedCompositePKs.push(...deletedCompositePKs);
  28394. jsonAlteredCompositePKs.push(...alteredCompositePKs);
  28395. jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
  28396. jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
  28397. jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
  28398. }
  28399. const rColumns = jsonRenameColumnsStatements.map((it) => {
  28400. const tableName = it.tableName;
  28401. const schema6 = it.schema;
  28402. return {
  28403. from: { schema: schema6, table: tableName, column: it.oldColumnName },
  28404. to: { schema: schema6, table: tableName, column: it.newColumnName }
  28405. };
  28406. });
  28407. const jsonTableAlternations = alteredTables.map((it) => {
  28408. return preparePgAlterColumns(
  28409. it.name,
  28410. it.schema,
  28411. it.altered,
  28412. json2,
  28413. json1,
  28414. action
  28415. );
  28416. }).flat();
  28417. const jsonCreateIndexesFoAlteredTables = alteredTables.map((it) => {
  28418. return preparePgCreateIndexesJson(
  28419. it.name,
  28420. it.schema,
  28421. it.addedIndexes || {},
  28422. curFull,
  28423. action
  28424. );
  28425. }).flat();
  28426. const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
  28427. return prepareDropIndexesJson(
  28428. it.name,
  28429. it.schema,
  28430. it.deletedIndexes || {}
  28431. );
  28432. }).flat();
  28433. const jsonCreatePoliciesStatements = [];
  28434. const jsonDropPoliciesStatements = [];
  28435. const jsonAlterPoliciesStatements = [];
  28436. const jsonRenamePoliciesStatements = [];
  28437. const jsonRenameIndPoliciesStatements = [];
  28438. const jsonCreateIndPoliciesStatements = [];
  28439. const jsonDropIndPoliciesStatements = [];
  28440. const jsonAlterIndPoliciesStatements = [];
  28441. const jsonEnableRLSStatements = [];
  28442. const jsonDisableRLSStatements = [];
  28443. for (let it of indPolicyRenames) {
  28444. jsonRenameIndPoliciesStatements.push(
  28445. ...prepareRenameIndPolicyJsons([it])
  28446. );
  28447. }
  28448. for (const it of indPolicyCreates) {
  28449. jsonCreateIndPoliciesStatements.push(
  28450. ...prepareCreateIndPolicyJsons(
  28451. it.policies
  28452. )
  28453. );
  28454. }
  28455. for (const it of indPolicyDeletes) {
  28456. jsonDropIndPoliciesStatements.push(
  28457. ...prepareDropIndPolicyJsons(
  28458. it.policies
  28459. )
  28460. );
  28461. }
  28462. typedResult.alteredPolicies.forEach(({ values }) => {
  28463. const policy5 = action === "push" ? PgSquasher.unsquashPolicyPush(values) : PgSquasher.unsquashPolicy(values);
  28464. const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json2.policies[policy5.name].values);
  28465. const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json2.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json1.policies[policy5.name].values);
  28466. if (newPolicy.as !== oldPolicy.as) {
  28467. jsonDropIndPoliciesStatements.push(
  28468. ...prepareDropIndPolicyJsons(
  28469. [oldPolicy]
  28470. )
  28471. );
  28472. jsonCreateIndPoliciesStatements.push(
  28473. ...prepareCreateIndPolicyJsons(
  28474. [newPolicy]
  28475. )
  28476. );
  28477. return;
  28478. }
  28479. if (newPolicy.for !== oldPolicy.for) {
  28480. jsonDropIndPoliciesStatements.push(
  28481. ...prepareDropIndPolicyJsons(
  28482. [oldPolicy]
  28483. )
  28484. );
  28485. jsonCreateIndPoliciesStatements.push(
  28486. ...prepareCreateIndPolicyJsons(
  28487. [newPolicy]
  28488. )
  28489. );
  28490. return;
  28491. }
  28492. jsonAlterIndPoliciesStatements.push(
  28493. prepareAlterIndPolicyJson(
  28494. oldPolicy,
  28495. newPolicy
  28496. )
  28497. );
  28498. });
  28499. for (let it of policyRenames) {
  28500. jsonRenamePoliciesStatements.push(
  28501. ...prepareRenamePolicyJsons(it.table, it.schema, it.renames)
  28502. );
  28503. }
  28504. for (const it of policyCreates) {
  28505. jsonCreatePoliciesStatements.push(
  28506. ...prepareCreatePolicyJsons(
  28507. it.table,
  28508. it.schema,
  28509. it.columns
  28510. )
  28511. );
  28512. }
  28513. for (const it of policyDeletes) {
  28514. jsonDropPoliciesStatements.push(
  28515. ...prepareDropPolicyJsons(
  28516. it.table,
  28517. it.schema,
  28518. it.columns
  28519. )
  28520. );
  28521. }
  28522. alteredTables.forEach((it) => {
  28523. Object.keys(it.alteredPolicies).forEach((policyName) => {
  28524. const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__new) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__new);
  28525. const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__old) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__old);
  28526. if (newPolicy.as !== oldPolicy.as) {
  28527. jsonDropPoliciesStatements.push(
  28528. ...prepareDropPolicyJsons(
  28529. it.name,
  28530. it.schema,
  28531. [oldPolicy]
  28532. )
  28533. );
  28534. jsonCreatePoliciesStatements.push(
  28535. ...prepareCreatePolicyJsons(
  28536. it.name,
  28537. it.schema,
  28538. [newPolicy]
  28539. )
  28540. );
  28541. return;
  28542. }
  28543. if (newPolicy.for !== oldPolicy.for) {
  28544. jsonDropPoliciesStatements.push(
  28545. ...prepareDropPolicyJsons(
  28546. it.name,
  28547. it.schema,
  28548. [oldPolicy]
  28549. )
  28550. );
  28551. jsonCreatePoliciesStatements.push(
  28552. ...prepareCreatePolicyJsons(
  28553. it.name,
  28554. it.schema,
  28555. [newPolicy]
  28556. )
  28557. );
  28558. return;
  28559. }
  28560. jsonAlterPoliciesStatements.push(
  28561. prepareAlterPolicyJson(
  28562. it.name,
  28563. it.schema,
  28564. it.alteredPolicies[policyName].__old,
  28565. it.alteredPolicies[policyName].__new
  28566. )
  28567. );
  28568. });
  28569. for (const table6 of Object.values(json2.tables)) {
  28570. const policiesInCurrentState = Object.keys(table6.policies);
  28571. const tableInPreviousState = columnsPatchedSnap1.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`];
  28572. const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : [];
  28573. if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0 && !table6.isRLSEnabled) {
  28574. jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema });
  28575. }
  28576. if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0 && !table6.isRLSEnabled) {
  28577. jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
  28578. }
  28579. const wasRlsEnabled = tableInPreviousState ? tableInPreviousState.isRLSEnabled : false;
  28580. if (table6.isRLSEnabled !== wasRlsEnabled) {
  28581. if (table6.isRLSEnabled) {
  28582. jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema });
  28583. } else if (!table6.isRLSEnabled && policiesInCurrentState.length === 0) {
  28584. jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
  28585. }
  28586. }
  28587. }
  28588. for (const table6 of Object.values(columnsPatchedSnap1.tables)) {
  28589. const tableInCurrentState = json2.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`];
  28590. if (tableInCurrentState === void 0 && !table6.isRLSEnabled) {
  28591. jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
  28592. }
  28593. }
  28594. const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
  28595. (current, item) => {
  28596. current[item] = it.alteredIndexes[item].__old;
  28597. return current;
  28598. },
  28599. {}
  28600. );
  28601. const createdIndexes = Object.keys(it.alteredIndexes).reduce(
  28602. (current, item) => {
  28603. current[item] = it.alteredIndexes[item].__new;
  28604. return current;
  28605. },
  28606. {}
  28607. );
  28608. jsonCreateIndexesFoAlteredTables.push(
  28609. ...preparePgCreateIndexesJson(
  28610. it.name,
  28611. it.schema,
  28612. createdIndexes || {},
  28613. curFull,
  28614. action
  28615. )
  28616. );
  28617. jsonDropIndexesForAllAlteredTables.push(
  28618. ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
  28619. );
  28620. });
  28621. const jsonCreateReferencesForCreatedTables = createdTables.map((it) => {
  28622. return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys);
  28623. }).flat();
  28624. const jsonReferencesForAlteredTables = alteredTables.map((it) => {
  28625. const forAdded = prepareCreateReferencesJson(
  28626. it.name,
  28627. it.schema,
  28628. it.addedForeignKeys
  28629. );
  28630. const forAltered = prepareDropReferencesJson(
  28631. it.name,
  28632. it.schema,
  28633. it.deletedForeignKeys
  28634. );
  28635. const alteredFKs = prepareAlterReferencesJson(
  28636. it.name,
  28637. it.schema,
  28638. it.alteredForeignKeys
  28639. );
  28640. return [...forAdded, ...forAltered, ...alteredFKs];
  28641. }).flat();
  28642. const jsonCreatedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
  28643. (t4) => t4.type === "create_reference"
  28644. );
  28645. const jsonDroppedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
  28646. (t4) => t4.type === "delete_reference"
  28647. );
  28648. const createEnums = createdEnums.map((it) => {
  28649. return prepareCreateEnumJson(it.name, it.schema, it.values);
  28650. }) ?? [];
  28651. const dropEnums = deletedEnums.map((it) => {
  28652. return prepareDropEnumJson(it.name, it.schema);
  28653. });
  28654. const moveEnums = movedEnums.map((it) => {
  28655. return prepareMoveEnumJson(it.name, it.schemaFrom, it.schemaTo);
  28656. });
  28657. const renameEnums = renamedEnums.map((it) => {
  28658. return prepareRenameEnumJson(it.from.name, it.to.name, it.to.schema);
  28659. });
  28660. const jsonAlterEnumsWithAddedValues = typedResult.alteredEnums.map((it) => {
  28661. return prepareAddValuesToEnumJson(it.name, it.schema, it.addedValues);
  28662. }).flat() ?? [];
  28663. const jsonAlterEnumsWithDroppedValues = typedResult.alteredEnums.map((it) => {
  28664. return prepareDropEnumValues(it.name, it.schema, it.deletedValues, curFull);
  28665. }).flat() ?? [];
  28666. const createSequences = createdSequences.map((it) => {
  28667. return prepareCreateSequenceJson(it);
  28668. }) ?? [];
  28669. const dropSequences = deletedSequences.map((it) => {
  28670. return prepareDropSequenceJson(it.name, it.schema);
  28671. });
  28672. const moveSequences = movedSequences.map((it) => {
  28673. return prepareMoveSequenceJson(it.name, it.schemaFrom, it.schemaTo);
  28674. });
  28675. const renameSequences = renamedSequences.map((it) => {
  28676. return prepareRenameSequenceJson(it.from.name, it.to.name, it.to.schema);
  28677. });
  28678. const jsonAlterSequences = typedResult.alteredSequences.map((it) => {
  28679. return prepareAlterSequenceJson(it);
  28680. }).flat() ?? [];
  28681. const createRoles = createdRoles.map((it) => {
  28682. return prepareCreateRoleJson(it);
  28683. }) ?? [];
  28684. const dropRoles = deletedRoles.map((it) => {
  28685. return prepareDropRoleJson(it.name);
  28686. });
  28687. const renameRoles = renamedRoles.map((it) => {
  28688. return prepareRenameRoleJson(it.from.name, it.to.name);
  28689. });
  28690. const jsonAlterRoles = typedResult.alteredRoles.map((it) => {
  28691. return prepareAlterRoleJson(it);
  28692. }).flat() ?? [];
  28693. const createSchemas = prepareCreateSchemasJson(
  28694. createdSchemas.map((it) => it.name)
  28695. );
  28696. const renameSchemas = prepareRenameSchemasJson(
  28697. renamedSchemas.map((it) => ({ from: it.from.name, to: it.to.name }))
  28698. );
  28699. const dropSchemas = prepareDeleteSchemasJson(
  28700. deletedSchemas.map((it) => it.name)
  28701. );
  28702. const createTables = createdTables.map((it) => {
  28703. return preparePgCreateTableJson(it, curFull);
  28704. });
  28705. jsonCreatePoliciesStatements.push(...[].concat(
  28706. ...createdTables.map(
  28707. (it) => prepareCreatePolicyJsons(
  28708. it.name,
  28709. it.schema,
  28710. Object.values(it.policies).map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy)
  28711. )
  28712. )
  28713. ));
  28714. const createViews = [];
  28715. const dropViews = [];
  28716. const renameViews = [];
  28717. const alterViews = [];
  28718. createViews.push(
  28719. ...createdViews.filter((it) => !it.isExisting).map((it) => {
  28720. return preparePgCreateViewJson(
  28721. it.name,
  28722. it.schema,
  28723. it.definition,
  28724. it.materialized,
  28725. it.withNoData,
  28726. it.with,
  28727. it.using,
  28728. it.tablespace
  28729. );
  28730. })
  28731. );
  28732. dropViews.push(
  28733. ...deletedViews.filter((it) => !it.isExisting).map((it) => {
  28734. return prepareDropViewJson(it.name, it.schema, it.materialized);
  28735. })
  28736. );
  28737. renameViews.push(
  28738. ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => {
  28739. return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized);
  28740. })
  28741. );
  28742. alterViews.push(
  28743. ...movedViews.filter(
  28744. (it) => !json2.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting
  28745. ).map((it) => {
  28746. return preparePgAlterViewAlterSchemaJson(
  28747. it.schemaTo,
  28748. it.schemaFrom,
  28749. it.name,
  28750. json2.views[`${it.schemaTo}.${it.name}`].materialized
  28751. );
  28752. })
  28753. );
  28754. const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[`${it.schema}.${it.name}`].isExisting);
  28755. for (const alteredView of alteredViews) {
  28756. const viewKey = `${alteredView.schema}.${alteredView.name}`;
  28757. const { materialized, with: withOption, definition, withNoData, using, tablespace } = json2.views[viewKey];
  28758. if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
  28759. dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized));
  28760. createViews.push(
  28761. preparePgCreateViewJson(
  28762. alteredView.name,
  28763. alteredView.schema,
  28764. definition,
  28765. materialized,
  28766. withNoData,
  28767. withOption,
  28768. using,
  28769. tablespace
  28770. )
  28771. );
  28772. continue;
  28773. }
  28774. if (alteredView.addedWithOption) {
  28775. alterViews.push(
  28776. preparePgAlterViewAddWithOptionJson(
  28777. alteredView.name,
  28778. alteredView.schema,
  28779. materialized,
  28780. alteredView.addedWithOption
  28781. )
  28782. );
  28783. }
  28784. if (alteredView.deletedWithOption) {
  28785. alterViews.push(
  28786. preparePgAlterViewDropWithOptionJson(
  28787. alteredView.name,
  28788. alteredView.schema,
  28789. materialized,
  28790. alteredView.deletedWithOption
  28791. )
  28792. );
  28793. }
  28794. if (alteredView.addedWith) {
  28795. alterViews.push(
  28796. preparePgAlterViewAddWithOptionJson(
  28797. alteredView.name,
  28798. alteredView.schema,
  28799. materialized,
  28800. alteredView.addedWith
  28801. )
  28802. );
  28803. }
  28804. if (alteredView.deletedWith) {
  28805. alterViews.push(
  28806. preparePgAlterViewDropWithOptionJson(
  28807. alteredView.name,
  28808. alteredView.schema,
  28809. materialized,
  28810. alteredView.deletedWith
  28811. )
  28812. );
  28813. }
  28814. if (alteredView.alteredWith) {
  28815. alterViews.push(
  28816. preparePgAlterViewAddWithOptionJson(
  28817. alteredView.name,
  28818. alteredView.schema,
  28819. materialized,
  28820. alteredView.alteredWith
  28821. )
  28822. );
  28823. }
  28824. if (alteredView.alteredTablespace) {
  28825. alterViews.push(
  28826. preparePgAlterViewAlterTablespaceJson(
  28827. alteredView.name,
  28828. alteredView.schema,
  28829. materialized,
  28830. alteredView.alteredTablespace.__new
  28831. )
  28832. );
  28833. }
  28834. if (alteredView.alteredUsing) {
  28835. alterViews.push(
  28836. preparePgAlterViewAlterUsingJson(
  28837. alteredView.name,
  28838. alteredView.schema,
  28839. materialized,
  28840. alteredView.alteredUsing.__new
  28841. )
  28842. );
  28843. }
  28844. }
  28845. jsonStatements.push(...createSchemas);
  28846. jsonStatements.push(...renameSchemas);
  28847. jsonStatements.push(...createEnums);
  28848. jsonStatements.push(...moveEnums);
  28849. jsonStatements.push(...renameEnums);
  28850. jsonStatements.push(...jsonAlterEnumsWithAddedValues);
  28851. jsonStatements.push(...createSequences);
  28852. jsonStatements.push(...moveSequences);
  28853. jsonStatements.push(...renameSequences);
  28854. jsonStatements.push(...jsonAlterSequences);
  28855. jsonStatements.push(...renameRoles);
  28856. jsonStatements.push(...dropRoles);
  28857. jsonStatements.push(...createRoles);
  28858. jsonStatements.push(...jsonAlterRoles);
  28859. jsonStatements.push(...createTables);
  28860. jsonStatements.push(...jsonEnableRLSStatements);
  28861. jsonStatements.push(...jsonDisableRLSStatements);
  28862. jsonStatements.push(...dropViews);
  28863. jsonStatements.push(...renameViews);
  28864. jsonStatements.push(...alterViews);
  28865. jsonStatements.push(...jsonDropTables);
  28866. jsonStatements.push(...jsonSetTableSchemas);
  28867. jsonStatements.push(...jsonRenameTables);
  28868. jsonStatements.push(...jsonRenameColumnsStatements);
  28869. jsonStatements.push(...jsonDeletedUniqueConstraints);
  28870. jsonStatements.push(...jsonDeletedCheckConstraints);
  28871. jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
  28872. jsonStatements.push(...jsonAlterEnumsWithDroppedValues);
  28873. jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
  28874. jsonStatements.push(...jsonDeletedCompositePKs);
  28875. jsonStatements.push(...jsonTableAlternations);
  28876. jsonStatements.push(...jsonAddedCompositePKs);
  28877. jsonStatements.push(...jsonAddColumnsStatemets);
  28878. jsonStatements.push(...jsonCreateReferencesForCreatedTables);
  28879. jsonStatements.push(...jsonCreateIndexesForCreatedTables);
  28880. jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
  28881. jsonStatements.push(...jsonCreateIndexesFoAlteredTables);
  28882. jsonStatements.push(...jsonDropColumnsStatemets);
  28883. jsonStatements.push(...jsonAlteredCompositePKs);
  28884. jsonStatements.push(...jsonAddedUniqueConstraints);
  28885. jsonStatements.push(...jsonCreatedCheckConstraints);
  28886. jsonStatements.push(...jsonAlteredUniqueConstraints);
  28887. jsonStatements.push(...createViews);
  28888. jsonStatements.push(...jsonRenamePoliciesStatements);
  28889. jsonStatements.push(...jsonDropPoliciesStatements);
  28890. jsonStatements.push(...jsonCreatePoliciesStatements);
  28891. jsonStatements.push(...jsonAlterPoliciesStatements);
  28892. jsonStatements.push(...jsonRenameIndPoliciesStatements);
  28893. jsonStatements.push(...jsonDropIndPoliciesStatements);
  28894. jsonStatements.push(...jsonCreateIndPoliciesStatements);
  28895. jsonStatements.push(...jsonAlterIndPoliciesStatements);
  28896. jsonStatements.push(...dropEnums);
  28897. jsonStatements.push(...dropSequences);
  28898. jsonStatements.push(...dropSchemas);
  28899. const filteredJsonStatements = jsonStatements.filter((st) => {
  28900. if (st.type === "alter_table_alter_column_drop_notnull") {
  28901. if (jsonStatements.find(
  28902. (it) => it.type === "alter_table_alter_column_drop_identity" && it.tableName === st.tableName && it.schema === st.schema
  28903. )) {
  28904. return false;
  28905. }
  28906. }
  28907. if (st.type === "alter_table_alter_column_set_notnull") {
  28908. if (jsonStatements.find(
  28909. (it) => it.type === "alter_table_alter_column_set_identity" && it.tableName === st.tableName && it.schema === st.schema
  28910. )) {
  28911. return false;
  28912. }
  28913. }
  28914. return true;
  28915. });
  28916. const filteredEnumsJsonStatements = filteredJsonStatements.filter((st) => {
  28917. if (st.type === "alter_type_add_value") {
  28918. if (filteredJsonStatements.find(
  28919. (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.enumSchema === st.schema
  28920. )) {
  28921. return false;
  28922. }
  28923. }
  28924. return true;
  28925. });
  28926. const filteredEnums2JsonStatements = filteredEnumsJsonStatements.filter((st) => {
  28927. if (st.type === "alter_table_alter_column_set_default") {
  28928. if (filteredEnumsJsonStatements.find(
  28929. (it) => it.type === "pg_alter_table_alter_column_set_type" && it.columnDefault === st.newDefaultValue && it.columnName === st.columnName && it.tableName === st.tableName && it.schema === st.schema
  28930. )) {
  28931. return false;
  28932. }
  28933. if (filteredEnumsJsonStatements.find(
  28934. (it) => it.type === "alter_type_drop_value" && it.columnsWithEnum.find(
  28935. (column11) => column11.default === st.newDefaultValue && column11.column === st.columnName && column11.table === st.tableName && column11.tableSchema === st.schema
  28936. )
  28937. )) {
  28938. return false;
  28939. }
  28940. }
  28941. return true;
  28942. });
  28943. const sqlStatements = fromJson(filteredEnums2JsonStatements, "postgresql", action);
  28944. const uniqueSqlStatements = [];
  28945. sqlStatements.forEach((ss) => {
  28946. if (!uniqueSqlStatements.includes(ss)) {
  28947. uniqueSqlStatements.push(ss);
  28948. }
  28949. });
  28950. const rSchemas = renamedSchemas.map((it) => ({
  28951. from: it.from.name,
  28952. to: it.to.name
  28953. }));
  28954. const rTables = renamedTables.map((it) => {
  28955. return { from: it.from, to: it.to };
  28956. });
  28957. const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
  28958. return {
  28959. statements: filteredEnums2JsonStatements,
  28960. sqlStatements: uniqueSqlStatements,
  28961. _meta
  28962. };
  28963. };
  28964. applyMysqlSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
  28965. for (const tableName in json1.tables) {
  28966. const table6 = json1.tables[tableName];
  28967. for (const indexName6 in table6.indexes) {
  28968. const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName6]);
  28969. if (index6.isUnique) {
  28970. table6.uniqueConstraints[indexName6] = MySqlSquasher.squashUnique({
  28971. name: index6.name,
  28972. columns: index6.columns
  28973. });
  28974. delete json1.tables[tableName].indexes[index6.name];
  28975. }
  28976. }
  28977. }
  28978. for (const tableName in json2.tables) {
  28979. const table6 = json2.tables[tableName];
  28980. for (const indexName6 in table6.indexes) {
  28981. const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName6]);
  28982. if (index6.isUnique) {
  28983. table6.uniqueConstraints[indexName6] = MySqlSquasher.squashUnique({
  28984. name: index6.name,
  28985. columns: index6.columns
  28986. });
  28987. delete json2.tables[tableName].indexes[index6.name];
  28988. }
  28989. }
  28990. }
  28991. const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
  28992. const {
  28993. created: createdTables,
  28994. deleted: deletedTables,
  28995. renamed: renamedTables
  28996. // renamed or moved
  28997. } = await tablesResolver2({
  28998. created: tablesDiff.added,
  28999. deleted: tablesDiff.deleted
  29000. });
  29001. const tablesPatchedSnap1 = copy(json1);
  29002. tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
  29003. const { name } = nameChangeFor(it, renamedTables);
  29004. it.name = name;
  29005. return [name, it];
  29006. });
  29007. const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
  29008. const columnRenames = [];
  29009. const columnCreates = [];
  29010. const columnDeletes = [];
  29011. for (let entry of Object.values(res)) {
  29012. const { renamed, created, deleted } = await columnsResolver2({
  29013. tableName: entry.name,
  29014. schema: entry.schema,
  29015. deleted: entry.columns.deleted,
  29016. created: entry.columns.added
  29017. });
  29018. if (created.length > 0) {
  29019. columnCreates.push({
  29020. table: entry.name,
  29021. columns: created
  29022. });
  29023. }
  29024. if (deleted.length > 0) {
  29025. columnDeletes.push({
  29026. table: entry.name,
  29027. columns: deleted
  29028. });
  29029. }
  29030. if (renamed.length > 0) {
  29031. columnRenames.push({
  29032. table: entry.name,
  29033. renames: renamed
  29034. });
  29035. }
  29036. }
  29037. const columnRenamesDict = columnRenames.reduce(
  29038. (acc, it) => {
  29039. acc[it.table] = it.renames;
  29040. return acc;
  29041. },
  29042. {}
  29043. );
  29044. const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
  29045. columnsPatchedSnap1.tables = mapEntries(
  29046. columnsPatchedSnap1.tables,
  29047. (tableKey2, tableValue) => {
  29048. const patchedColumns = mapKeys(
  29049. tableValue.columns,
  29050. (columnKey, column11) => {
  29051. const rens = columnRenamesDict[tableValue.name] || [];
  29052. const newName = columnChangeFor(columnKey, rens);
  29053. column11.name = newName;
  29054. return newName;
  29055. }
  29056. );
  29057. tableValue.columns = patchedColumns;
  29058. return [tableKey2, tableValue];
  29059. }
  29060. );
  29061. const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
  29062. const {
  29063. created: createdViews,
  29064. deleted: deletedViews,
  29065. renamed: renamedViews
  29066. // renamed or moved
  29067. } = await viewsResolver2({
  29068. created: viewsDiff.added,
  29069. deleted: viewsDiff.deleted
  29070. });
  29071. const renamesViewDic = {};
  29072. renamedViews.forEach((it) => {
  29073. renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
  29074. });
  29075. const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
  29076. viewsPatchedSnap1.views = mapEntries(
  29077. viewsPatchedSnap1.views,
  29078. (viewKey, viewValue) => {
  29079. const rename = renamesViewDic[viewValue.name];
  29080. if (rename) {
  29081. viewValue.name = rename.to;
  29082. viewKey = rename.to;
  29083. }
  29084. return [viewKey, viewValue];
  29085. }
  29086. );
  29087. const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
  29088. const typedResult = diffResultSchemeMysql.parse(diffResult);
  29089. const jsonStatements = [];
  29090. const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
  29091. return prepareCreateIndexesJson(
  29092. it.name,
  29093. it.schema,
  29094. it.indexes,
  29095. curFull.internal
  29096. );
  29097. }).flat();
  29098. const jsonDropTables = deletedTables.map((it) => {
  29099. return prepareDropTableJson(it);
  29100. });
  29101. const jsonRenameTables = renamedTables.map((it) => {
  29102. return prepareRenameTableJson(it.from, it.to);
  29103. });
  29104. const alteredTables = typedResult.alteredTablesWithColumns;
  29105. const jsonAddedCompositePKs = [];
  29106. const jsonDeletedCompositePKs = [];
  29107. const jsonAlteredCompositePKs = [];
  29108. const jsonAddedUniqueConstraints = [];
  29109. const jsonDeletedUniqueConstraints = [];
  29110. const jsonAlteredUniqueConstraints = [];
  29111. const jsonCreatedCheckConstraints = [];
  29112. const jsonDeletedCheckConstraints = [];
  29113. const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
  29114. const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
  29115. const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
  29116. alteredTables.forEach((it) => {
  29117. let addedColumns = [];
  29118. for (const addedPkName of Object.keys(it.addedCompositePKs)) {
  29119. const addedPkColumns = it.addedCompositePKs[addedPkName];
  29120. addedColumns = MySqlSquasher.unsquashPK(addedPkColumns).columns;
  29121. }
  29122. let deletedColumns = [];
  29123. for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
  29124. const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
  29125. deletedColumns = MySqlSquasher.unsquashPK(deletedPkColumns).columns;
  29126. }
  29127. const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
  29128. let addedCompositePKs = [];
  29129. let deletedCompositePKs = [];
  29130. let alteredCompositePKs = [];
  29131. addedCompositePKs = prepareAddCompositePrimaryKeyMySql(
  29132. it.name,
  29133. it.addedCompositePKs,
  29134. prevFull,
  29135. curFull
  29136. );
  29137. deletedCompositePKs = prepareDeleteCompositePrimaryKeyMySql(
  29138. it.name,
  29139. it.deletedCompositePKs,
  29140. prevFull
  29141. );
  29142. alteredCompositePKs = prepareAlterCompositePrimaryKeyMySql(
  29143. it.name,
  29144. it.alteredCompositePKs,
  29145. prevFull,
  29146. curFull
  29147. );
  29148. let addedUniqueConstraints = [];
  29149. let deletedUniqueConstraints = [];
  29150. let alteredUniqueConstraints = [];
  29151. let createdCheckConstraints = [];
  29152. let deletedCheckConstraints = [];
  29153. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  29154. it.name,
  29155. it.schema,
  29156. it.addedUniqueConstraints
  29157. );
  29158. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  29159. it.name,
  29160. it.schema,
  29161. it.deletedUniqueConstraints
  29162. );
  29163. if (it.alteredUniqueConstraints) {
  29164. const added = {};
  29165. const deleted = {};
  29166. for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
  29167. added[k3] = it.alteredUniqueConstraints[k3].__new;
  29168. deleted[k3] = it.alteredUniqueConstraints[k3].__old;
  29169. }
  29170. addedUniqueConstraints.push(
  29171. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  29172. );
  29173. deletedUniqueConstraints.push(
  29174. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
  29175. );
  29176. }
  29177. createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
  29178. deletedCheckConstraints = prepareDeleteCheckConstraint(
  29179. it.name,
  29180. it.schema,
  29181. it.deletedCheckConstraints
  29182. );
  29183. if (it.alteredCheckConstraints && action !== "push") {
  29184. const added = {};
  29185. const deleted = {};
  29186. for (const k3 of Object.keys(it.alteredCheckConstraints)) {
  29187. added[k3] = it.alteredCheckConstraints[k3].__new;
  29188. deleted[k3] = it.alteredCheckConstraints[k3].__old;
  29189. }
  29190. createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
  29191. deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
  29192. }
  29193. jsonAddedCompositePKs.push(...addedCompositePKs);
  29194. jsonDeletedCompositePKs.push(...deletedCompositePKs);
  29195. jsonAlteredCompositePKs.push(...alteredCompositePKs);
  29196. jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
  29197. jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
  29198. jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
  29199. jsonCreatedCheckConstraints.push(...createdCheckConstraints);
  29200. jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
  29201. });
  29202. const rColumns = jsonRenameColumnsStatements.map((it) => {
  29203. const tableName = it.tableName;
  29204. const schema6 = it.schema;
  29205. return {
  29206. from: { schema: schema6, table: tableName, column: it.oldColumnName },
  29207. to: { schema: schema6, table: tableName, column: it.newColumnName }
  29208. };
  29209. });
  29210. const jsonTableAlternations = alteredTables.map((it) => {
  29211. return prepareAlterColumnsMysql(
  29212. it.name,
  29213. it.schema,
  29214. it.altered,
  29215. json1,
  29216. json2,
  29217. action
  29218. );
  29219. }).flat();
  29220. const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => {
  29221. return prepareCreateIndexesJson(
  29222. it.name,
  29223. it.schema,
  29224. it.addedIndexes || {},
  29225. curFull.internal
  29226. );
  29227. }).flat();
  29228. const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
  29229. return prepareDropIndexesJson(
  29230. it.name,
  29231. it.schema,
  29232. it.deletedIndexes || {}
  29233. );
  29234. }).flat();
  29235. alteredTables.forEach((it) => {
  29236. const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
  29237. (current, item) => {
  29238. current[item] = it.alteredIndexes[item].__old;
  29239. return current;
  29240. },
  29241. {}
  29242. );
  29243. const createdIndexes = Object.keys(it.alteredIndexes).reduce(
  29244. (current, item) => {
  29245. current[item] = it.alteredIndexes[item].__new;
  29246. return current;
  29247. },
  29248. {}
  29249. );
  29250. jsonCreateIndexesForAllAlteredTables.push(
  29251. ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {})
  29252. );
  29253. jsonDropIndexesForAllAlteredTables.push(
  29254. ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
  29255. );
  29256. });
  29257. const jsonCreateReferencesForCreatedTables = createdTables.map((it) => {
  29258. return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys);
  29259. }).flat();
  29260. const jsonReferencesForAllAlteredTables = alteredTables.map((it) => {
  29261. const forAdded = prepareCreateReferencesJson(
  29262. it.name,
  29263. it.schema,
  29264. it.addedForeignKeys
  29265. );
  29266. const forAltered = prepareDropReferencesJson(
  29267. it.name,
  29268. it.schema,
  29269. it.deletedForeignKeys
  29270. );
  29271. const alteredFKs = prepareAlterReferencesJson(
  29272. it.name,
  29273. it.schema,
  29274. it.alteredForeignKeys
  29275. );
  29276. return [...forAdded, ...forAltered, ...alteredFKs];
  29277. }).flat();
  29278. const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  29279. (t4) => t4.type === "create_reference"
  29280. );
  29281. const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  29282. (t4) => t4.type === "delete_reference"
  29283. );
  29284. const jsonMySqlCreateTables = createdTables.map((it) => {
  29285. return prepareMySqlCreateTableJson(
  29286. it,
  29287. curFull,
  29288. curFull.internal
  29289. );
  29290. });
  29291. const createViews = [];
  29292. const dropViews = [];
  29293. const renameViews = [];
  29294. const alterViews = [];
  29295. createViews.push(
  29296. ...createdViews.filter((it) => !it.isExisting).map((it) => {
  29297. return prepareMySqlCreateViewJson(
  29298. it.name,
  29299. it.definition,
  29300. it.meta
  29301. );
  29302. })
  29303. );
  29304. dropViews.push(
  29305. ...deletedViews.filter((it) => !it.isExisting).map((it) => {
  29306. return prepareDropViewJson(it.name);
  29307. })
  29308. );
  29309. renameViews.push(
  29310. ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => {
  29311. return prepareRenameViewJson(it.to.name, it.from.name);
  29312. })
  29313. );
  29314. const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
  29315. for (const alteredView of alteredViews) {
  29316. const { definition, meta } = json2.views[alteredView.name];
  29317. if (alteredView.alteredExisting) {
  29318. dropViews.push(prepareDropViewJson(alteredView.name));
  29319. createViews.push(
  29320. prepareMySqlCreateViewJson(
  29321. alteredView.name,
  29322. definition,
  29323. meta
  29324. )
  29325. );
  29326. continue;
  29327. }
  29328. if (alteredView.alteredDefinition && action !== "push") {
  29329. createViews.push(
  29330. prepareMySqlCreateViewJson(
  29331. alteredView.name,
  29332. definition,
  29333. meta,
  29334. true
  29335. )
  29336. );
  29337. continue;
  29338. }
  29339. if (alteredView.alteredMeta) {
  29340. const view5 = curFull["views"][alteredView.name];
  29341. alterViews.push(
  29342. prepareMySqlAlterView(view5)
  29343. );
  29344. }
  29345. }
  29346. jsonStatements.push(...jsonMySqlCreateTables);
  29347. jsonStatements.push(...jsonDropTables);
  29348. jsonStatements.push(...jsonRenameTables);
  29349. jsonStatements.push(...jsonRenameColumnsStatements);
  29350. jsonStatements.push(...dropViews);
  29351. jsonStatements.push(...renameViews);
  29352. jsonStatements.push(...alterViews);
  29353. jsonStatements.push(...jsonDeletedUniqueConstraints);
  29354. jsonStatements.push(...jsonDeletedCheckConstraints);
  29355. jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
  29356. jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
  29357. jsonStatements.push(...jsonDeletedCompositePKs);
  29358. jsonStatements.push(...jsonTableAlternations);
  29359. jsonStatements.push(...jsonAddedCompositePKs);
  29360. jsonStatements.push(...jsonAddColumnsStatemets);
  29361. jsonStatements.push(...jsonAddedUniqueConstraints);
  29362. jsonStatements.push(...jsonDeletedUniqueConstraints);
  29363. jsonStatements.push(...jsonCreateReferencesForCreatedTables);
  29364. jsonStatements.push(...jsonCreateIndexesForCreatedTables);
  29365. jsonStatements.push(...jsonCreatedCheckConstraints);
  29366. jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
  29367. jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
  29368. jsonStatements.push(...jsonDropColumnsStatemets);
  29369. jsonStatements.push(...jsonAlteredCompositePKs);
  29370. jsonStatements.push(...createViews);
  29371. jsonStatements.push(...jsonAlteredUniqueConstraints);
  29372. const sqlStatements = fromJson(jsonStatements, "mysql");
  29373. const uniqueSqlStatements = [];
  29374. sqlStatements.forEach((ss) => {
  29375. if (!uniqueSqlStatements.includes(ss)) {
  29376. uniqueSqlStatements.push(ss);
  29377. }
  29378. });
  29379. const rTables = renamedTables.map((it) => {
  29380. return { from: it.from, to: it.to };
  29381. });
  29382. const _meta = prepareMigrationMeta([], rTables, rColumns);
  29383. return {
  29384. statements: jsonStatements,
  29385. sqlStatements: uniqueSqlStatements,
  29386. _meta
  29387. };
  29388. };
  29389. applySingleStoreSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
  29390. for (const tableName in json1.tables) {
  29391. const table6 = json1.tables[tableName];
  29392. for (const indexName6 in table6.indexes) {
  29393. const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName6]);
  29394. if (index6.isUnique) {
  29395. table6.uniqueConstraints[indexName6] = SingleStoreSquasher.squashUnique({
  29396. name: index6.name,
  29397. columns: index6.columns
  29398. });
  29399. delete json1.tables[tableName].indexes[index6.name];
  29400. }
  29401. }
  29402. }
  29403. for (const tableName in json2.tables) {
  29404. const table6 = json2.tables[tableName];
  29405. for (const indexName6 in table6.indexes) {
  29406. const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName6]);
  29407. if (index6.isUnique) {
  29408. table6.uniqueConstraints[indexName6] = SingleStoreSquasher.squashUnique({
  29409. name: index6.name,
  29410. columns: index6.columns
  29411. });
  29412. delete json2.tables[tableName].indexes[index6.name];
  29413. }
  29414. }
  29415. }
  29416. const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
  29417. const {
  29418. created: createdTables,
  29419. deleted: deletedTables,
  29420. renamed: renamedTables
  29421. // renamed or moved
  29422. } = await tablesResolver2({
  29423. created: tablesDiff.added,
  29424. deleted: tablesDiff.deleted
  29425. });
  29426. const tablesPatchedSnap1 = copy(json1);
  29427. tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
  29428. const { name } = nameChangeFor(it, renamedTables);
  29429. it.name = name;
  29430. return [name, it];
  29431. });
  29432. const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
  29433. const columnRenames = [];
  29434. const columnCreates = [];
  29435. const columnDeletes = [];
  29436. for (let entry of Object.values(res)) {
  29437. const { renamed, created, deleted } = await columnsResolver2({
  29438. tableName: entry.name,
  29439. schema: entry.schema,
  29440. deleted: entry.columns.deleted,
  29441. created: entry.columns.added
  29442. });
  29443. if (created.length > 0) {
  29444. columnCreates.push({
  29445. table: entry.name,
  29446. columns: created
  29447. });
  29448. }
  29449. if (deleted.length > 0) {
  29450. columnDeletes.push({
  29451. table: entry.name,
  29452. columns: deleted
  29453. });
  29454. }
  29455. if (renamed.length > 0) {
  29456. columnRenames.push({
  29457. table: entry.name,
  29458. renames: renamed
  29459. });
  29460. }
  29461. }
  29462. const columnRenamesDict = columnRenames.reduce(
  29463. (acc, it) => {
  29464. acc[it.table] = it.renames;
  29465. return acc;
  29466. },
  29467. {}
  29468. );
  29469. const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
  29470. columnsPatchedSnap1.tables = mapEntries(
  29471. columnsPatchedSnap1.tables,
  29472. (tableKey2, tableValue) => {
  29473. const patchedColumns = mapKeys(
  29474. tableValue.columns,
  29475. (columnKey, column11) => {
  29476. const rens = columnRenamesDict[tableValue.name] || [];
  29477. const newName = columnChangeFor(columnKey, rens);
  29478. column11.name = newName;
  29479. return newName;
  29480. }
  29481. );
  29482. tableValue.columns = patchedColumns;
  29483. return [tableKey2, tableValue];
  29484. }
  29485. );
  29486. const diffResult = applyJsonDiff(columnsPatchedSnap1, json2);
  29487. const typedResult = diffResultSchemeSingleStore.parse(diffResult);
  29488. const jsonStatements = [];
  29489. const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
  29490. return prepareCreateIndexesJson(
  29491. it.name,
  29492. it.schema,
  29493. it.indexes,
  29494. curFull.internal
  29495. );
  29496. }).flat();
  29497. const jsonDropTables = deletedTables.map((it) => {
  29498. return prepareDropTableJson(it);
  29499. });
  29500. const jsonRenameTables = renamedTables.map((it) => {
  29501. return prepareRenameTableJson(it.from, it.to);
  29502. });
  29503. const alteredTables = typedResult.alteredTablesWithColumns;
  29504. const jsonAddedCompositePKs = [];
  29505. const jsonAddedUniqueConstraints = [];
  29506. const jsonDeletedUniqueConstraints = [];
  29507. const jsonAlteredUniqueConstraints = [];
  29508. const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
  29509. const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
  29510. const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
  29511. alteredTables.forEach((it) => {
  29512. let addedColumns = [];
  29513. for (const addedPkName of Object.keys(it.addedCompositePKs)) {
  29514. const addedPkColumns = it.addedCompositePKs[addedPkName];
  29515. addedColumns = SingleStoreSquasher.unsquashPK(addedPkColumns).columns;
  29516. }
  29517. let deletedColumns = [];
  29518. for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
  29519. const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
  29520. deletedColumns = SingleStoreSquasher.unsquashPK(deletedPkColumns).columns;
  29521. }
  29522. const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
  29523. let addedUniqueConstraints = [];
  29524. let deletedUniqueConstraints = [];
  29525. let alteredUniqueConstraints = [];
  29526. let createdCheckConstraints = [];
  29527. let deletedCheckConstraints = [];
  29528. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  29529. it.name,
  29530. it.schema,
  29531. it.addedUniqueConstraints
  29532. );
  29533. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  29534. it.name,
  29535. it.schema,
  29536. it.deletedUniqueConstraints
  29537. );
  29538. if (it.alteredUniqueConstraints) {
  29539. const added = {};
  29540. const deleted = {};
  29541. for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
  29542. added[k3] = it.alteredUniqueConstraints[k3].__new;
  29543. deleted[k3] = it.alteredUniqueConstraints[k3].__old;
  29544. }
  29545. addedUniqueConstraints.push(
  29546. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  29547. );
  29548. deletedUniqueConstraints.push(
  29549. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
  29550. );
  29551. }
  29552. createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
  29553. deletedCheckConstraints = prepareDeleteCheckConstraint(
  29554. it.name,
  29555. it.schema,
  29556. it.deletedCheckConstraints
  29557. );
  29558. if (it.alteredCheckConstraints && action !== "push") {
  29559. const added = {};
  29560. const deleted = {};
  29561. for (const k3 of Object.keys(it.alteredCheckConstraints)) {
  29562. added[k3] = it.alteredCheckConstraints[k3].__new;
  29563. deleted[k3] = it.alteredCheckConstraints[k3].__old;
  29564. }
  29565. createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
  29566. deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
  29567. }
  29568. jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
  29569. jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
  29570. jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
  29571. });
  29572. const rColumns = jsonRenameColumnsStatements.map((it) => {
  29573. const tableName = it.tableName;
  29574. const schema6 = it.schema;
  29575. return {
  29576. from: { schema: schema6, table: tableName, column: it.oldColumnName },
  29577. to: { schema: schema6, table: tableName, column: it.newColumnName }
  29578. };
  29579. });
  29580. const jsonTableAlternations = alteredTables.map((it) => {
  29581. return prepareAlterColumnsMysql(
  29582. it.name,
  29583. it.schema,
  29584. it.altered,
  29585. json1,
  29586. json2,
  29587. action
  29588. );
  29589. }).flat();
  29590. const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => {
  29591. return prepareCreateIndexesJson(
  29592. it.name,
  29593. it.schema,
  29594. it.addedIndexes || {},
  29595. curFull.internal
  29596. );
  29597. }).flat();
  29598. const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
  29599. return prepareDropIndexesJson(
  29600. it.name,
  29601. it.schema,
  29602. it.deletedIndexes || {}
  29603. );
  29604. }).flat();
  29605. alteredTables.forEach((it) => {
  29606. const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
  29607. (current, item) => {
  29608. current[item] = it.alteredIndexes[item].__old;
  29609. return current;
  29610. },
  29611. {}
  29612. );
  29613. const createdIndexes = Object.keys(it.alteredIndexes).reduce(
  29614. (current, item) => {
  29615. current[item] = it.alteredIndexes[item].__new;
  29616. return current;
  29617. },
  29618. {}
  29619. );
  29620. jsonCreateIndexesForAllAlteredTables.push(
  29621. ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {})
  29622. );
  29623. jsonDropIndexesForAllAlteredTables.push(
  29624. ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
  29625. );
  29626. });
  29627. const jsonSingleStoreCreateTables = createdTables.map((it) => {
  29628. return prepareSingleStoreCreateTableJson(
  29629. it,
  29630. curFull,
  29631. curFull.internal
  29632. );
  29633. });
  29634. jsonStatements.push(...jsonSingleStoreCreateTables);
  29635. jsonStatements.push(...jsonDropTables);
  29636. jsonStatements.push(...jsonRenameTables);
  29637. jsonStatements.push(...jsonRenameColumnsStatements);
  29638. jsonStatements.push(...jsonDeletedUniqueConstraints);
  29639. jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
  29640. jsonStatements.push(...jsonTableAlternations);
  29641. jsonStatements.push(...jsonAddedCompositePKs);
  29642. jsonStatements.push(...jsonAddedUniqueConstraints);
  29643. jsonStatements.push(...jsonDeletedUniqueConstraints);
  29644. jsonStatements.push(...jsonAddColumnsStatemets);
  29645. jsonStatements.push(...jsonCreateIndexesForCreatedTables);
  29646. jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
  29647. jsonStatements.push(...jsonDropColumnsStatemets);
  29648. jsonStatements.push(...jsonAddedCompositePKs);
  29649. jsonStatements.push(...jsonAlteredUniqueConstraints);
  29650. const combinedJsonStatements = singleStoreCombineStatements(jsonStatements, json2);
  29651. const sqlStatements = fromJson(combinedJsonStatements, "singlestore");
  29652. const uniqueSqlStatements = [];
  29653. sqlStatements.forEach((ss) => {
  29654. if (!uniqueSqlStatements.includes(ss)) {
  29655. uniqueSqlStatements.push(ss);
  29656. }
  29657. });
  29658. const rTables = renamedTables.map((it) => {
  29659. return { from: it.from, to: it.to };
  29660. });
  29661. const _meta = prepareMigrationMeta([], rTables, rColumns);
  29662. return {
  29663. statements: combinedJsonStatements,
  29664. sqlStatements: uniqueSqlStatements,
  29665. _meta
  29666. };
  29667. };
  29668. applySqliteSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
  29669. const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
  29670. const {
  29671. created: createdTables,
  29672. deleted: deletedTables,
  29673. renamed: renamedTables
  29674. } = await tablesResolver2({
  29675. created: tablesDiff.added,
  29676. deleted: tablesDiff.deleted
  29677. });
  29678. const tablesPatchedSnap1 = copy(json1);
  29679. tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
  29680. const { name } = nameChangeFor(it, renamedTables);
  29681. it.name = name;
  29682. return [name, it];
  29683. });
  29684. const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
  29685. const columnRenames = [];
  29686. const columnCreates = [];
  29687. const columnDeletes = [];
  29688. for (let entry of Object.values(res)) {
  29689. const { renamed, created, deleted } = await columnsResolver2({
  29690. tableName: entry.name,
  29691. schema: entry.schema,
  29692. deleted: entry.columns.deleted,
  29693. created: entry.columns.added
  29694. });
  29695. if (created.length > 0) {
  29696. columnCreates.push({
  29697. table: entry.name,
  29698. columns: created
  29699. });
  29700. }
  29701. if (deleted.length > 0) {
  29702. columnDeletes.push({
  29703. table: entry.name,
  29704. columns: deleted
  29705. });
  29706. }
  29707. if (renamed.length > 0) {
  29708. columnRenames.push({
  29709. table: entry.name,
  29710. renames: renamed
  29711. });
  29712. }
  29713. }
  29714. const columnRenamesDict = columnRenames.reduce(
  29715. (acc, it) => {
  29716. acc[it.table] = it.renames;
  29717. return acc;
  29718. },
  29719. {}
  29720. );
  29721. const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
  29722. columnsPatchedSnap1.tables = mapEntries(
  29723. columnsPatchedSnap1.tables,
  29724. (tableKey2, tableValue) => {
  29725. const patchedColumns = mapKeys(
  29726. tableValue.columns,
  29727. (columnKey, column11) => {
  29728. const rens = columnRenamesDict[tableValue.name] || [];
  29729. const newName = columnChangeFor(columnKey, rens);
  29730. column11.name = newName;
  29731. return newName;
  29732. }
  29733. );
  29734. tableValue.columns = patchedColumns;
  29735. return [tableKey2, tableValue];
  29736. }
  29737. );
  29738. const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
  29739. const {
  29740. created: createdViews,
  29741. deleted: deletedViews,
  29742. renamed: renamedViews
  29743. // renamed or moved
  29744. } = await viewsResolver2({
  29745. created: viewsDiff.added,
  29746. deleted: viewsDiff.deleted
  29747. });
  29748. const renamesViewDic = {};
  29749. renamedViews.forEach((it) => {
  29750. renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
  29751. });
  29752. const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
  29753. viewsPatchedSnap1.views = mapEntries(
  29754. viewsPatchedSnap1.views,
  29755. (viewKey, viewValue) => {
  29756. const rename = renamesViewDic[viewValue.name];
  29757. if (rename) {
  29758. viewValue.name = rename.to;
  29759. }
  29760. return [viewKey, viewValue];
  29761. }
  29762. );
  29763. const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
  29764. const typedResult = diffResultSchemeSQLite.parse(diffResult);
  29765. const tablesMap = {};
  29766. typedResult.alteredTablesWithColumns.forEach((obj) => {
  29767. tablesMap[obj.name] = obj;
  29768. });
  29769. const jsonCreateTables = createdTables.map((it) => {
  29770. return prepareSQLiteCreateTable(it, action);
  29771. });
  29772. const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
  29773. return prepareCreateIndexesJson(
  29774. it.name,
  29775. it.schema,
  29776. it.indexes,
  29777. curFull.internal
  29778. );
  29779. }).flat();
  29780. const jsonDropTables = deletedTables.map((it) => {
  29781. return prepareDropTableJson(it);
  29782. });
  29783. const jsonRenameTables = renamedTables.map((it) => {
  29784. return prepareRenameTableJson(it.from, it.to);
  29785. });
  29786. const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
  29787. const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
  29788. const jsonAddColumnsStatemets = columnCreates.map((it) => {
  29789. return _prepareSqliteAddColumns(
  29790. it.table,
  29791. it.columns,
  29792. tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
  29793. );
  29794. }).flat();
  29795. const allAltered = typedResult.alteredTablesWithColumns;
  29796. const jsonAddedCompositePKs = [];
  29797. const jsonDeletedCompositePKs = [];
  29798. const jsonAlteredCompositePKs = [];
  29799. const jsonAddedUniqueConstraints = [];
  29800. const jsonDeletedUniqueConstraints = [];
  29801. const jsonAlteredUniqueConstraints = [];
  29802. const jsonDeletedCheckConstraints = [];
  29803. const jsonCreatedCheckConstraints = [];
  29804. allAltered.forEach((it) => {
  29805. let addedColumns = [];
  29806. for (const addedPkName of Object.keys(it.addedCompositePKs)) {
  29807. const addedPkColumns = it.addedCompositePKs[addedPkName];
  29808. addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
  29809. }
  29810. let deletedColumns = [];
  29811. for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
  29812. const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
  29813. deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
  29814. }
  29815. const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
  29816. let addedCompositePKs = [];
  29817. let deletedCompositePKs = [];
  29818. let alteredCompositePKs = [];
  29819. if (doPerformDeleteAndCreate) {
  29820. addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
  29821. it.name,
  29822. it.addedCompositePKs
  29823. );
  29824. deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
  29825. it.name,
  29826. it.deletedCompositePKs
  29827. );
  29828. }
  29829. alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
  29830. it.name,
  29831. it.alteredCompositePKs
  29832. );
  29833. let addedUniqueConstraints = [];
  29834. let deletedUniqueConstraints = [];
  29835. let alteredUniqueConstraints = [];
  29836. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  29837. it.name,
  29838. it.schema,
  29839. it.addedUniqueConstraints
  29840. );
  29841. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  29842. it.name,
  29843. it.schema,
  29844. it.deletedUniqueConstraints
  29845. );
  29846. if (it.alteredUniqueConstraints) {
  29847. const added = {};
  29848. const deleted = {};
  29849. for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
  29850. added[k3] = it.alteredUniqueConstraints[k3].__new;
  29851. deleted[k3] = it.alteredUniqueConstraints[k3].__old;
  29852. }
  29853. addedUniqueConstraints.push(
  29854. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  29855. );
  29856. deletedUniqueConstraints.push(
  29857. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
  29858. );
  29859. }
  29860. let createdCheckConstraints = [];
  29861. let deletedCheckConstraints = [];
  29862. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  29863. it.name,
  29864. it.schema,
  29865. it.addedUniqueConstraints
  29866. );
  29867. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  29868. it.name,
  29869. it.schema,
  29870. it.deletedUniqueConstraints
  29871. );
  29872. if (it.alteredUniqueConstraints) {
  29873. const added = {};
  29874. const deleted = {};
  29875. for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
  29876. added[k3] = it.alteredUniqueConstraints[k3].__new;
  29877. deleted[k3] = it.alteredUniqueConstraints[k3].__old;
  29878. }
  29879. addedUniqueConstraints.push(
  29880. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  29881. );
  29882. deletedUniqueConstraints.push(
  29883. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
  29884. );
  29885. }
  29886. createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
  29887. deletedCheckConstraints = prepareDeleteCheckConstraint(
  29888. it.name,
  29889. it.schema,
  29890. it.deletedCheckConstraints
  29891. );
  29892. if (it.alteredCheckConstraints && action !== "push") {
  29893. const added = {};
  29894. const deleted = {};
  29895. for (const k3 of Object.keys(it.alteredCheckConstraints)) {
  29896. added[k3] = it.alteredCheckConstraints[k3].__new;
  29897. deleted[k3] = it.alteredCheckConstraints[k3].__old;
  29898. }
  29899. createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
  29900. deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
  29901. }
  29902. jsonAddedCompositePKs.push(...addedCompositePKs);
  29903. jsonDeletedCompositePKs.push(...deletedCompositePKs);
  29904. jsonAlteredCompositePKs.push(...alteredCompositePKs);
  29905. jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
  29906. jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
  29907. jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
  29908. jsonCreatedCheckConstraints.push(...createdCheckConstraints);
  29909. jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
  29910. });
  29911. const rColumns = jsonRenameColumnsStatements.map((it) => {
  29912. const tableName = it.tableName;
  29913. const schema6 = it.schema;
  29914. return {
  29915. from: { schema: schema6, table: tableName, column: it.oldColumnName },
  29916. to: { schema: schema6, table: tableName, column: it.newColumnName }
  29917. };
  29918. });
  29919. const jsonTableAlternations = allAltered.map((it) => {
  29920. return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
  29921. }).flat();
  29922. const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
  29923. return prepareCreateIndexesJson(
  29924. it.name,
  29925. it.schema,
  29926. it.addedIndexes || {},
  29927. curFull.internal
  29928. );
  29929. }).flat();
  29930. const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
  29931. return prepareDropIndexesJson(
  29932. it.name,
  29933. it.schema,
  29934. it.deletedIndexes || {}
  29935. );
  29936. }).flat();
  29937. allAltered.forEach((it) => {
  29938. const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
  29939. (current, item) => {
  29940. current[item] = it.alteredIndexes[item].__old;
  29941. return current;
  29942. },
  29943. {}
  29944. );
  29945. const createdIndexes = Object.keys(it.alteredIndexes).reduce(
  29946. (current, item) => {
  29947. current[item] = it.alteredIndexes[item].__new;
  29948. return current;
  29949. },
  29950. {}
  29951. );
  29952. jsonCreateIndexesForAllAlteredTables.push(
  29953. ...prepareCreateIndexesJson(
  29954. it.name,
  29955. it.schema,
  29956. createdIndexes || {},
  29957. curFull.internal
  29958. )
  29959. );
  29960. jsonDropIndexesForAllAlteredTables.push(
  29961. ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
  29962. );
  29963. });
  29964. const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
  29965. const forAdded = prepareCreateReferencesJson(
  29966. it.name,
  29967. it.schema,
  29968. it.addedForeignKeys
  29969. );
  29970. const forAltered = prepareDropReferencesJson(
  29971. it.name,
  29972. it.schema,
  29973. it.deletedForeignKeys
  29974. );
  29975. const alteredFKs = prepareAlterReferencesJson(
  29976. it.name,
  29977. it.schema,
  29978. it.alteredForeignKeys
  29979. );
  29980. return [...forAdded, ...forAltered, ...alteredFKs];
  29981. }).flat();
  29982. const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  29983. (t4) => t4.type === "create_reference"
  29984. );
  29985. const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  29986. (t4) => t4.type === "delete_reference"
  29987. );
  29988. const createViews = [];
  29989. const dropViews = [];
  29990. createViews.push(
  29991. ...createdViews.filter((it) => !it.isExisting).map((it) => {
  29992. return prepareSqliteCreateViewJson(
  29993. it.name,
  29994. it.definition
  29995. );
  29996. })
  29997. );
  29998. dropViews.push(
  29999. ...deletedViews.filter((it) => !it.isExisting).map((it) => {
  30000. return prepareDropViewJson(it.name);
  30001. })
  30002. );
  30003. dropViews.push(
  30004. ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
  30005. return prepareDropViewJson(it.from.name);
  30006. })
  30007. );
  30008. createViews.push(
  30009. ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
  30010. return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
  30011. })
  30012. );
  30013. const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
  30014. for (const alteredView of alteredViews) {
  30015. const { definition } = json2.views[alteredView.name];
  30016. if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
  30017. dropViews.push(prepareDropViewJson(alteredView.name));
  30018. createViews.push(
  30019. prepareSqliteCreateViewJson(
  30020. alteredView.name,
  30021. definition
  30022. )
  30023. );
  30024. }
  30025. }
  30026. const jsonStatements = [];
  30027. jsonStatements.push(...jsonCreateTables);
  30028. jsonStatements.push(...jsonDropTables);
  30029. jsonStatements.push(...jsonRenameTables);
  30030. jsonStatements.push(...jsonRenameColumnsStatements);
  30031. jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
  30032. jsonStatements.push(...jsonDeletedCheckConstraints);
  30033. jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
  30034. jsonStatements.push(...jsonDeletedCompositePKs);
  30035. jsonStatements.push(...jsonTableAlternations);
  30036. jsonStatements.push(...jsonAddedCompositePKs);
  30037. jsonStatements.push(...jsonAddColumnsStatemets);
  30038. jsonStatements.push(...jsonCreateIndexesForCreatedTables);
  30039. jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
  30040. jsonStatements.push(...jsonCreatedCheckConstraints);
  30041. jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
  30042. jsonStatements.push(...jsonDropColumnsStatemets);
  30043. jsonStatements.push(...jsonAlteredCompositePKs);
  30044. jsonStatements.push(...jsonAlteredUniqueConstraints);
  30045. jsonStatements.push(...dropViews);
  30046. jsonStatements.push(...createViews);
  30047. const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json2, action);
  30048. const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
  30049. const uniqueSqlStatements = [];
  30050. sqlStatements.forEach((ss) => {
  30051. if (!uniqueSqlStatements.includes(ss)) {
  30052. uniqueSqlStatements.push(ss);
  30053. }
  30054. });
  30055. const rTables = renamedTables.map((it) => {
  30056. return { from: it.from, to: it.to };
  30057. });
  30058. const _meta = prepareMigrationMeta([], rTables, rColumns);
  30059. return {
  30060. statements: combinedJsonStatements,
  30061. sqlStatements: uniqueSqlStatements,
  30062. _meta
  30063. };
  30064. };
  30065. applyLibSQLSnapshotsDiff = async (json1, json2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
  30066. const tablesDiff = diffSchemasOrTables(json1.tables, json2.tables);
  30067. const {
  30068. created: createdTables,
  30069. deleted: deletedTables,
  30070. renamed: renamedTables
  30071. } = await tablesResolver2({
  30072. created: tablesDiff.added,
  30073. deleted: tablesDiff.deleted
  30074. });
  30075. const tablesPatchedSnap1 = copy(json1);
  30076. tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_3, it) => {
  30077. const { name } = nameChangeFor(it, renamedTables);
  30078. it.name = name;
  30079. return [name, it];
  30080. });
  30081. const res = diffColumns(tablesPatchedSnap1.tables, json2.tables);
  30082. const columnRenames = [];
  30083. const columnCreates = [];
  30084. const columnDeletes = [];
  30085. for (let entry of Object.values(res)) {
  30086. const { renamed, created, deleted } = await columnsResolver2({
  30087. tableName: entry.name,
  30088. schema: entry.schema,
  30089. deleted: entry.columns.deleted,
  30090. created: entry.columns.added
  30091. });
  30092. if (created.length > 0) {
  30093. columnCreates.push({
  30094. table: entry.name,
  30095. columns: created
  30096. });
  30097. }
  30098. if (deleted.length > 0) {
  30099. columnDeletes.push({
  30100. table: entry.name,
  30101. columns: deleted
  30102. });
  30103. }
  30104. if (renamed.length > 0) {
  30105. columnRenames.push({
  30106. table: entry.name,
  30107. renames: renamed
  30108. });
  30109. }
  30110. }
  30111. const columnRenamesDict = columnRenames.reduce(
  30112. (acc, it) => {
  30113. acc[it.table] = it.renames;
  30114. return acc;
  30115. },
  30116. {}
  30117. );
  30118. const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
  30119. columnsPatchedSnap1.tables = mapEntries(
  30120. columnsPatchedSnap1.tables,
  30121. (tableKey2, tableValue) => {
  30122. const patchedColumns = mapKeys(
  30123. tableValue.columns,
  30124. (columnKey, column11) => {
  30125. const rens = columnRenamesDict[tableValue.name] || [];
  30126. const newName = columnChangeFor(columnKey, rens);
  30127. column11.name = newName;
  30128. return newName;
  30129. }
  30130. );
  30131. tableValue.columns = patchedColumns;
  30132. return [tableKey2, tableValue];
  30133. }
  30134. );
  30135. const viewsDiff = diffSchemasOrTables(json1.views, json2.views);
  30136. const {
  30137. created: createdViews,
  30138. deleted: deletedViews,
  30139. renamed: renamedViews
  30140. // renamed or moved
  30141. } = await viewsResolver2({
  30142. created: viewsDiff.added,
  30143. deleted: viewsDiff.deleted
  30144. });
  30145. const renamesViewDic = {};
  30146. renamedViews.forEach((it) => {
  30147. renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
  30148. });
  30149. const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
  30150. viewsPatchedSnap1.views = mapEntries(
  30151. viewsPatchedSnap1.views,
  30152. (viewKey, viewValue) => {
  30153. const rename = renamesViewDic[viewValue.name];
  30154. if (rename) {
  30155. viewValue.name = rename.to;
  30156. }
  30157. return [viewKey, viewValue];
  30158. }
  30159. );
  30160. const diffResult = applyJsonDiff(viewsPatchedSnap1, json2);
  30161. const typedResult = diffResultSchemeSQLite.parse(diffResult);
  30162. const tablesMap = {};
  30163. typedResult.alteredTablesWithColumns.forEach((obj) => {
  30164. tablesMap[obj.name] = obj;
  30165. });
  30166. const jsonCreateTables = createdTables.map((it) => {
  30167. return prepareSQLiteCreateTable(it, action);
  30168. });
  30169. const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
  30170. return prepareCreateIndexesJson(
  30171. it.name,
  30172. it.schema,
  30173. it.indexes,
  30174. curFull.internal
  30175. );
  30176. }).flat();
  30177. const jsonDropTables = deletedTables.map((it) => {
  30178. return prepareDropTableJson(it);
  30179. });
  30180. const jsonRenameTables = renamedTables.map((it) => {
  30181. return prepareRenameTableJson(it.from, it.to);
  30182. });
  30183. const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
  30184. const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
  30185. const jsonAddColumnsStatemets = columnCreates.map((it) => {
  30186. return _prepareSqliteAddColumns(
  30187. it.table,
  30188. it.columns,
  30189. tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
  30190. );
  30191. }).flat();
  30192. const rColumns = jsonRenameColumnsStatements.map((it) => {
  30193. const tableName = it.tableName;
  30194. const schema6 = it.schema;
  30195. return {
  30196. from: { schema: schema6, table: tableName, column: it.oldColumnName },
  30197. to: { schema: schema6, table: tableName, column: it.newColumnName }
  30198. };
  30199. });
  30200. const rTables = renamedTables.map((it) => {
  30201. return { from: it.from, to: it.to };
  30202. });
  30203. const _meta = prepareMigrationMeta([], rTables, rColumns);
  30204. const allAltered = typedResult.alteredTablesWithColumns;
  30205. const jsonAddedCompositePKs = [];
  30206. const jsonDeletedCompositePKs = [];
  30207. const jsonAlteredCompositePKs = [];
  30208. const jsonAddedUniqueConstraints = [];
  30209. const jsonDeletedUniqueConstraints = [];
  30210. const jsonAlteredUniqueConstraints = [];
  30211. const jsonDeletedCheckConstraints = [];
  30212. const jsonCreatedCheckConstraints = [];
  30213. allAltered.forEach((it) => {
  30214. let addedColumns = [];
  30215. for (const addedPkName of Object.keys(it.addedCompositePKs)) {
  30216. const addedPkColumns = it.addedCompositePKs[addedPkName];
  30217. addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
  30218. }
  30219. let deletedColumns = [];
  30220. for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
  30221. const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
  30222. deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
  30223. }
  30224. const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
  30225. let addedCompositePKs = [];
  30226. let deletedCompositePKs = [];
  30227. let alteredCompositePKs = [];
  30228. if (doPerformDeleteAndCreate) {
  30229. addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
  30230. it.name,
  30231. it.addedCompositePKs
  30232. );
  30233. deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
  30234. it.name,
  30235. it.deletedCompositePKs
  30236. );
  30237. }
  30238. alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
  30239. it.name,
  30240. it.alteredCompositePKs
  30241. );
  30242. let addedUniqueConstraints = [];
  30243. let deletedUniqueConstraints = [];
  30244. let alteredUniqueConstraints = [];
  30245. let createdCheckConstraints = [];
  30246. let deletedCheckConstraints = [];
  30247. addedUniqueConstraints = prepareAddUniqueConstraintPg(
  30248. it.name,
  30249. it.schema,
  30250. it.addedUniqueConstraints
  30251. );
  30252. deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
  30253. it.name,
  30254. it.schema,
  30255. it.deletedUniqueConstraints
  30256. );
  30257. if (it.alteredUniqueConstraints) {
  30258. const added = {};
  30259. const deleted = {};
  30260. for (const k3 of Object.keys(it.alteredUniqueConstraints)) {
  30261. added[k3] = it.alteredUniqueConstraints[k3].__new;
  30262. deleted[k3] = it.alteredUniqueConstraints[k3].__old;
  30263. }
  30264. addedUniqueConstraints.push(
  30265. ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
  30266. );
  30267. deletedUniqueConstraints.push(
  30268. ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
  30269. );
  30270. }
  30271. createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
  30272. deletedCheckConstraints = prepareDeleteCheckConstraint(
  30273. it.name,
  30274. it.schema,
  30275. it.deletedCheckConstraints
  30276. );
  30277. if (it.alteredCheckConstraints && action !== "push") {
  30278. const added = {};
  30279. const deleted = {};
  30280. for (const k3 of Object.keys(it.alteredCheckConstraints)) {
  30281. added[k3] = it.alteredCheckConstraints[k3].__new;
  30282. deleted[k3] = it.alteredCheckConstraints[k3].__old;
  30283. }
  30284. createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
  30285. deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
  30286. }
  30287. jsonAddedCompositePKs.push(...addedCompositePKs);
  30288. jsonDeletedCompositePKs.push(...deletedCompositePKs);
  30289. jsonAlteredCompositePKs.push(...alteredCompositePKs);
  30290. jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
  30291. jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
  30292. jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
  30293. jsonCreatedCheckConstraints.push(...createdCheckConstraints);
  30294. jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
  30295. });
  30296. const jsonTableAlternations = allAltered.map((it) => {
  30297. return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json2);
  30298. }).flat();
  30299. const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
  30300. return prepareCreateIndexesJson(
  30301. it.name,
  30302. it.schema,
  30303. it.addedIndexes || {},
  30304. curFull.internal
  30305. );
  30306. }).flat();
  30307. const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
  30308. return prepareDropIndexesJson(
  30309. it.name,
  30310. it.schema,
  30311. it.deletedIndexes || {}
  30312. );
  30313. }).flat();
  30314. allAltered.forEach((it) => {
  30315. const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
  30316. (current, item) => {
  30317. current[item] = it.alteredIndexes[item].__old;
  30318. return current;
  30319. },
  30320. {}
  30321. );
  30322. const createdIndexes = Object.keys(it.alteredIndexes).reduce(
  30323. (current, item) => {
  30324. current[item] = it.alteredIndexes[item].__new;
  30325. return current;
  30326. },
  30327. {}
  30328. );
  30329. jsonCreateIndexesForAllAlteredTables.push(
  30330. ...prepareCreateIndexesJson(
  30331. it.name,
  30332. it.schema,
  30333. createdIndexes || {},
  30334. curFull.internal
  30335. )
  30336. );
  30337. jsonDropIndexesForAllAlteredTables.push(
  30338. ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
  30339. );
  30340. });
  30341. const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
  30342. const forAdded = prepareLibSQLCreateReferencesJson(
  30343. it.name,
  30344. it.schema,
  30345. it.addedForeignKeys,
  30346. json2,
  30347. action
  30348. );
  30349. const forAltered = prepareLibSQLDropReferencesJson(
  30350. it.name,
  30351. it.schema,
  30352. it.deletedForeignKeys,
  30353. json2,
  30354. _meta,
  30355. action
  30356. );
  30357. const alteredFKs = prepareAlterReferencesJson(it.name, it.schema, it.alteredForeignKeys);
  30358. return [...forAdded, ...forAltered, ...alteredFKs];
  30359. }).flat();
  30360. const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  30361. (t4) => t4.type === "create_reference"
  30362. );
  30363. const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
  30364. (t4) => t4.type === "delete_reference"
  30365. );
  30366. const createViews = [];
  30367. const dropViews = [];
  30368. createViews.push(
  30369. ...createdViews.filter((it) => !it.isExisting).map((it) => {
  30370. return prepareSqliteCreateViewJson(
  30371. it.name,
  30372. it.definition
  30373. );
  30374. })
  30375. );
  30376. dropViews.push(
  30377. ...deletedViews.filter((it) => !it.isExisting).map((it) => {
  30378. return prepareDropViewJson(it.name);
  30379. })
  30380. );
  30381. dropViews.push(
  30382. ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
  30383. return prepareDropViewJson(it.from.name);
  30384. })
  30385. );
  30386. createViews.push(
  30387. ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
  30388. return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
  30389. })
  30390. );
  30391. const alteredViews = typedResult.alteredViews.filter((it) => !json2.views[it.name].isExisting);
  30392. for (const alteredView of alteredViews) {
  30393. const { definition } = json2.views[alteredView.name];
  30394. if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
  30395. dropViews.push(prepareDropViewJson(alteredView.name));
  30396. createViews.push(
  30397. prepareSqliteCreateViewJson(
  30398. alteredView.name,
  30399. definition
  30400. )
  30401. );
  30402. }
  30403. }
  30404. const jsonStatements = [];
  30405. jsonStatements.push(...jsonCreateTables);
  30406. jsonStatements.push(...jsonDropTables);
  30407. jsonStatements.push(...jsonRenameTables);
  30408. jsonStatements.push(...jsonRenameColumnsStatements);
  30409. jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
  30410. jsonStatements.push(...jsonDeletedCheckConstraints);
  30411. jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
  30412. jsonStatements.push(...jsonDeletedCompositePKs);
  30413. jsonStatements.push(...jsonTableAlternations);
  30414. jsonStatements.push(...jsonAddedCompositePKs);
  30415. jsonStatements.push(...jsonAddColumnsStatemets);
  30416. jsonStatements.push(...jsonCreateIndexesForCreatedTables);
  30417. jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
  30418. jsonStatements.push(...jsonCreatedCheckConstraints);
  30419. jsonStatements.push(...dropViews);
  30420. jsonStatements.push(...createViews);
  30421. jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
  30422. jsonStatements.push(...jsonDropColumnsStatemets);
  30423. jsonStatements.push(...jsonAlteredCompositePKs);
  30424. jsonStatements.push(...jsonAlteredUniqueConstraints);
  30425. const combinedJsonStatements = libSQLCombineStatements(jsonStatements, json2, action);
  30426. const sqlStatements = fromJson(
  30427. combinedJsonStatements,
  30428. "turso",
  30429. action,
  30430. json2
  30431. );
  30432. const uniqueSqlStatements = [];
  30433. sqlStatements.forEach((ss) => {
  30434. if (!uniqueSqlStatements.includes(ss)) {
  30435. uniqueSqlStatements.push(ss);
  30436. }
  30437. });
  30438. return {
  30439. statements: combinedJsonStatements,
  30440. sqlStatements: uniqueSqlStatements,
  30441. _meta
  30442. };
  30443. };
  30444. }
  30445. });
  30446. // src/utils/words.ts
  30447. var prepareMigrationMetadata, adjectives, heroes;
  30448. var init_words = __esm({
  30449. "src/utils/words.ts"() {
  30450. "use strict";
  30451. prepareMigrationMetadata = (idx, prefixMode, name) => {
  30452. const prefix2 = prefixMode === "index" ? idx.toFixed(0).padStart(4, "0") : prefixMode === "timestamp" || prefixMode === "supabase" ? (/* @__PURE__ */ new Date()).toISOString().replace("T", "").replaceAll("-", "").replaceAll(":", "").slice(0, 14) : prefixMode === "unix" ? Math.floor(Date.now() / 1e3) : "";
  30453. const suffix = name || `${adjectives.random()}_${heroes.random()}`;
  30454. const tag = `${prefix2}_${suffix}`;
  30455. return { prefix: prefix2, suffix, tag };
  30456. };
  30457. adjectives = [
  30458. "abandoned",
  30459. "aberrant",
  30460. "abnormal",
  30461. "absent",
  30462. "absurd",
  30463. "acoustic",
  30464. "adorable",
  30465. "amazing",
  30466. "ambiguous",
  30467. "ambitious",
  30468. "amused",
  30469. "amusing",
  30470. "ancient",
  30471. "aromatic",
  30472. "aspiring",
  30473. "awesome",
  30474. "bent",
  30475. "big",
  30476. "bitter",
  30477. "bizarre",
  30478. "black",
  30479. "blue",
  30480. "blushing",
  30481. "bored",
  30482. "boring",
  30483. "bouncy",
  30484. "brainy",
  30485. "brave",
  30486. "breezy",
  30487. "brief",
  30488. "bright",
  30489. "broad",
  30490. "broken",
  30491. "brown",
  30492. "bumpy",
  30493. "burly",
  30494. "busy",
  30495. "calm",
  30496. "careful",
  30497. "careless",
  30498. "certain",
  30499. "charming",
  30500. "cheerful",
  30501. "chemical",
  30502. "chief",
  30503. "chilly",
  30504. "chubby",
  30505. "chunky",
  30506. "clammy",
  30507. "classy",
  30508. "clean",
  30509. "clear",
  30510. "clever",
  30511. "cloudy",
  30512. "closed",
  30513. "clumsy",
  30514. "cold",
  30515. "colorful",
  30516. "colossal",
  30517. "common",
  30518. "complete",
  30519. "complex",
  30520. "concerned",
  30521. "condemned",
  30522. "confused",
  30523. "conscious",
  30524. "cooing",
  30525. "cool",
  30526. "crazy",
  30527. "cuddly",
  30528. "cultured",
  30529. "curious",
  30530. "curly",
  30531. "curved",
  30532. "curvy",
  30533. "cute",
  30534. "cynical",
  30535. "daffy",
  30536. "daily",
  30537. "damp",
  30538. "dapper",
  30539. "dark",
  30540. "dashing",
  30541. "dazzling",
  30542. "dear",
  30543. "deep",
  30544. "demonic",
  30545. "dizzy",
  30546. "dry",
  30547. "dusty",
  30548. "eager",
  30549. "early",
  30550. "easy",
  30551. "elite",
  30552. "eminent",
  30553. "empty",
  30554. "equal",
  30555. "even",
  30556. "exotic",
  30557. "fair",
  30558. "faithful",
  30559. "familiar",
  30560. "famous",
  30561. "fancy",
  30562. "fantastic",
  30563. "far",
  30564. "fast",
  30565. "fat",
  30566. "faulty",
  30567. "fearless",
  30568. "fine",
  30569. "first",
  30570. "fixed",
  30571. "flaky",
  30572. "flashy",
  30573. "flat",
  30574. "flawless",
  30575. "flimsy",
  30576. "flippant",
  30577. "flowery",
  30578. "fluffy",
  30579. "foamy",
  30580. "free",
  30581. "freezing",
  30582. "fresh",
  30583. "friendly",
  30584. "funny",
  30585. "furry",
  30586. "futuristic",
  30587. "fuzzy",
  30588. "giant",
  30589. "gifted",
  30590. "gigantic",
  30591. "glamorous",
  30592. "glorious",
  30593. "glossy",
  30594. "good",
  30595. "goofy",
  30596. "gorgeous",
  30597. "graceful",
  30598. "gray",
  30599. "great",
  30600. "greedy",
  30601. "green",
  30602. "grey",
  30603. "groovy",
  30604. "handy",
  30605. "happy",
  30606. "hard",
  30607. "harsh",
  30608. "heavy",
  30609. "hesitant",
  30610. "high",
  30611. "hot",
  30612. "huge",
  30613. "icy",
  30614. "illegal",
  30615. "jazzy",
  30616. "jittery",
  30617. "keen",
  30618. "kind",
  30619. "known",
  30620. "lame",
  30621. "large",
  30622. "last",
  30623. "late",
  30624. "lazy",
  30625. "lean",
  30626. "left",
  30627. "legal",
  30628. "lethal",
  30629. "light",
  30630. "little",
  30631. "lively",
  30632. "living",
  30633. "lonely",
  30634. "long",
  30635. "loose",
  30636. "loud",
  30637. "lovely",
  30638. "loving",
  30639. "low",
  30640. "lowly",
  30641. "lucky",
  30642. "lumpy",
  30643. "lush",
  30644. "luxuriant",
  30645. "lying",
  30646. "lyrical",
  30647. "magenta",
  30648. "magical",
  30649. "majestic",
  30650. "many",
  30651. "massive",
  30652. "married",
  30653. "marvelous",
  30654. "material",
  30655. "mature",
  30656. "mean",
  30657. "medical",
  30658. "melodic",
  30659. "melted",
  30660. "messy",
  30661. "mighty",
  30662. "military",
  30663. "milky",
  30664. "minor",
  30665. "misty",
  30666. "mixed",
  30667. "moaning",
  30668. "modern",
  30669. "motionless",
  30670. "mushy",
  30671. "mute",
  30672. "mysterious",
  30673. "naive",
  30674. "nappy",
  30675. "narrow",
  30676. "nasty",
  30677. "natural",
  30678. "neat",
  30679. "nebulous",
  30680. "needy",
  30681. "nervous",
  30682. "new",
  30683. "next",
  30684. "nice",
  30685. "nifty",
  30686. "noisy",
  30687. "normal",
  30688. "nostalgic",
  30689. "nosy",
  30690. "numerous",
  30691. "odd",
  30692. "old",
  30693. "omniscient",
  30694. "open",
  30695. "opposite",
  30696. "optimal",
  30697. "orange",
  30698. "ordinary",
  30699. "organic",
  30700. "outgoing",
  30701. "outstanding",
  30702. "oval",
  30703. "overconfident",
  30704. "overjoyed",
  30705. "overrated",
  30706. "pale",
  30707. "panoramic",
  30708. "parallel",
  30709. "parched",
  30710. "past",
  30711. "peaceful",
  30712. "perfect",
  30713. "perpetual",
  30714. "petite",
  30715. "pink",
  30716. "plain",
  30717. "polite",
  30718. "powerful",
  30719. "premium",
  30720. "pretty",
  30721. "previous",
  30722. "productive",
  30723. "public",
  30724. "purple",
  30725. "puzzling",
  30726. "quick",
  30727. "quiet",
  30728. "rainy",
  30729. "rapid",
  30730. "rare",
  30731. "real",
  30732. "red",
  30733. "redundant",
  30734. "reflective",
  30735. "regular",
  30736. "remarkable",
  30737. "rich",
  30738. "right",
  30739. "robust",
  30740. "romantic",
  30741. "round",
  30742. "sad",
  30743. "safe",
  30744. "salty",
  30745. "same",
  30746. "secret",
  30747. "serious",
  30748. "shallow",
  30749. "sharp",
  30750. "shiny",
  30751. "shocking",
  30752. "short",
  30753. "silent",
  30754. "silky",
  30755. "silly",
  30756. "simple",
  30757. "skinny",
  30758. "sleepy",
  30759. "slim",
  30760. "slimy",
  30761. "slippery",
  30762. "sloppy",
  30763. "slow",
  30764. "small",
  30765. "smart",
  30766. "smiling",
  30767. "smooth",
  30768. "soft",
  30769. "solid",
  30770. "sour",
  30771. "sparkling",
  30772. "special",
  30773. "spicy",
  30774. "spooky",
  30775. "spotty",
  30776. "square",
  30777. "stale",
  30778. "steady",
  30779. "steep",
  30780. "sticky",
  30781. "stiff",
  30782. "stormy",
  30783. "strange",
  30784. "striped",
  30785. "strong",
  30786. "sturdy",
  30787. "sudden",
  30788. "superb",
  30789. "supreme",
  30790. "sweet",
  30791. "swift",
  30792. "talented",
  30793. "tan",
  30794. "tearful",
  30795. "tense",
  30796. "thankful",
  30797. "thick",
  30798. "thin",
  30799. "third",
  30800. "tidy",
  30801. "tiny",
  30802. "tired",
  30803. "tiresome",
  30804. "tough",
  30805. "tranquil",
  30806. "tricky",
  30807. "true",
  30808. "typical",
  30809. "uneven",
  30810. "unique",
  30811. "unknown",
  30812. "unusual",
  30813. "useful",
  30814. "vengeful",
  30815. "violet",
  30816. "volatile",
  30817. "wakeful",
  30818. "wandering",
  30819. "warm",
  30820. "watery",
  30821. "wealthy",
  30822. "wet",
  30823. "white",
  30824. "whole",
  30825. "wide",
  30826. "wild",
  30827. "windy",
  30828. "wise",
  30829. "wonderful",
  30830. "wooden",
  30831. "woozy",
  30832. "workable",
  30833. "worried",
  30834. "worthless",
  30835. "yellow",
  30836. "yielding",
  30837. "young",
  30838. "youthful",
  30839. "yummy",
  30840. "zippy"
  30841. ];
  30842. heroes = [
  30843. "aaron_stack",
  30844. "abomination",
  30845. "absorbing_man",
  30846. "adam_destine",
  30847. "adam_warlock",
  30848. "agent_brand",
  30849. "agent_zero",
  30850. "albert_cleary",
  30851. "alex_power",
  30852. "alex_wilder",
  30853. "alice",
  30854. "amazoness",
  30855. "amphibian",
  30856. "angel",
  30857. "anita_blake",
  30858. "annihilus",
  30859. "anthem",
  30860. "apocalypse",
  30861. "aqueduct",
  30862. "arachne",
  30863. "archangel",
  30864. "arclight",
  30865. "ares",
  30866. "argent",
  30867. "avengers",
  30868. "azazel",
  30869. "banshee",
  30870. "baron_strucker",
  30871. "baron_zemo",
  30872. "barracuda",
  30873. "bastion",
  30874. "beast",
  30875. "bedlam",
  30876. "ben_grimm",
  30877. "ben_parker",
  30878. "ben_urich",
  30879. "betty_brant",
  30880. "betty_ross",
  30881. "beyonder",
  30882. "big_bertha",
  30883. "bill_hollister",
  30884. "bishop",
  30885. "black_bird",
  30886. "black_bolt",
  30887. "black_cat",
  30888. "black_crow",
  30889. "black_knight",
  30890. "black_panther",
  30891. "black_queen",
  30892. "black_tarantula",
  30893. "black_tom",
  30894. "black_widow",
  30895. "blackheart",
  30896. "blacklash",
  30897. "blade",
  30898. "blazing_skull",
  30899. "blindfold",
  30900. "blink",
  30901. "blizzard",
  30902. "blob",
  30903. "blockbuster",
  30904. "blonde_phantom",
  30905. "bloodaxe",
  30906. "bloodscream",
  30907. "bloodstorm",
  30908. "bloodstrike",
  30909. "blue_blade",
  30910. "blue_marvel",
  30911. "blue_shield",
  30912. "blur",
  30913. "boom_boom",
  30914. "boomer",
  30915. "boomerang",
  30916. "bromley",
  30917. "brood",
  30918. "brother_voodoo",
  30919. "bruce_banner",
  30920. "bucky",
  30921. "bug",
  30922. "bulldozer",
  30923. "bullseye",
  30924. "bushwacker",
  30925. "butterfly",
  30926. "cable",
  30927. "callisto",
  30928. "calypso",
  30929. "cammi",
  30930. "cannonball",
  30931. "captain_america",
  30932. "captain_britain",
  30933. "captain_cross",
  30934. "captain_flint",
  30935. "captain_marvel",
  30936. "captain_midlands",
  30937. "captain_stacy",
  30938. "captain_universe",
  30939. "cardiac",
  30940. "caretaker",
  30941. "cargill",
  30942. "carlie_cooper",
  30943. "carmella_unuscione",
  30944. "carnage",
  30945. "cassandra_nova",
  30946. "catseye",
  30947. "celestials",
  30948. "centennial",
  30949. "cerebro",
  30950. "cerise",
  30951. "chamber",
  30952. "chameleon",
  30953. "champions",
  30954. "changeling",
  30955. "charles_xavier",
  30956. "chat",
  30957. "chimera",
  30958. "christian_walker",
  30959. "chronomancer",
  30960. "clea",
  30961. "clint_barton",
  30962. "cloak",
  30963. "cobalt_man",
  30964. "colleen_wing",
  30965. "colonel_america",
  30966. "colossus",
  30967. "corsair",
  30968. "crusher_hogan",
  30969. "crystal",
  30970. "cyclops",
  30971. "dagger",
  30972. "daimon_hellstrom",
  30973. "dakota_north",
  30974. "daredevil",
  30975. "dark_beast",
  30976. "dark_phoenix",
  30977. "darkhawk",
  30978. "darkstar",
  30979. "darwin",
  30980. "dazzler",
  30981. "deadpool",
  30982. "deathbird",
  30983. "deathstrike",
  30984. "demogoblin",
  30985. "devos",
  30986. "dexter_bennett",
  30987. "diamondback",
  30988. "doctor_doom",
  30989. "doctor_faustus",
  30990. "doctor_octopus",
  30991. "doctor_spectrum",
  30992. "doctor_strange",
  30993. "domino",
  30994. "donald_blake",
  30995. "doomsday",
  30996. "doorman",
  30997. "dorian_gray",
  30998. "dormammu",
  30999. "dracula",
  31000. "dragon_lord",
  31001. "dragon_man",
  31002. "drax",
  31003. "dreadnoughts",
  31004. "dreaming_celestial",
  31005. "dust",
  31006. "earthquake",
  31007. "echo",
  31008. "eddie_brock",
  31009. "edwin_jarvis",
  31010. "ego",
  31011. "electro",
  31012. "elektra",
  31013. "emma_frost",
  31014. "enchantress",
  31015. "ender_wiggin",
  31016. "energizer",
  31017. "epoch",
  31018. "eternals",
  31019. "eternity",
  31020. "excalibur",
  31021. "exiles",
  31022. "exodus",
  31023. "expediter",
  31024. "ezekiel",
  31025. "ezekiel_stane",
  31026. "fabian_cortez",
  31027. "falcon",
  31028. "fallen_one",
  31029. "famine",
  31030. "fantastic_four",
  31031. "fat_cobra",
  31032. "felicia_hardy",
  31033. "fenris",
  31034. "firebird",
  31035. "firebrand",
  31036. "firedrake",
  31037. "firelord",
  31038. "firestar",
  31039. "fixer",
  31040. "flatman",
  31041. "forge",
  31042. "forgotten_one",
  31043. "frank_castle",
  31044. "franklin_richards",
  31045. "franklin_storm",
  31046. "freak",
  31047. "frightful_four",
  31048. "frog_thor",
  31049. "gabe_jones",
  31050. "galactus",
  31051. "gambit",
  31052. "gamma_corps",
  31053. "gamora",
  31054. "gargoyle",
  31055. "garia",
  31056. "gateway",
  31057. "gauntlet",
  31058. "genesis",
  31059. "george_stacy",
  31060. "gertrude_yorkes",
  31061. "ghost_rider",
  31062. "giant_girl",
  31063. "giant_man",
  31064. "gideon",
  31065. "gladiator",
  31066. "glorian",
  31067. "goblin_queen",
  31068. "golden_guardian",
  31069. "goliath",
  31070. "gorgon",
  31071. "gorilla_man",
  31072. "grandmaster",
  31073. "gravity",
  31074. "green_goblin",
  31075. "gressill",
  31076. "grey_gargoyle",
  31077. "greymalkin",
  31078. "grim_reaper",
  31079. "groot",
  31080. "guardian",
  31081. "guardsmen",
  31082. "gunslinger",
  31083. "gwen_stacy",
  31084. "hairball",
  31085. "hammerhead",
  31086. "hannibal_king",
  31087. "hardball",
  31088. "harpoon",
  31089. "harrier",
  31090. "harry_osborn",
  31091. "havok",
  31092. "hawkeye",
  31093. "hedge_knight",
  31094. "hellcat",
  31095. "hellfire_club",
  31096. "hellion",
  31097. "hemingway",
  31098. "hercules",
  31099. "hex",
  31100. "hiroim",
  31101. "hitman",
  31102. "hobgoblin",
  31103. "hulk",
  31104. "human_cannonball",
  31105. "human_fly",
  31106. "human_robot",
  31107. "human_torch",
  31108. "husk",
  31109. "hydra",
  31110. "iceman",
  31111. "ikaris",
  31112. "imperial_guard",
  31113. "impossible_man",
  31114. "inertia",
  31115. "infant_terrible",
  31116. "inhumans",
  31117. "ink",
  31118. "invaders",
  31119. "invisible_woman",
  31120. "iron_fist",
  31121. "iron_lad",
  31122. "iron_man",
  31123. "iron_monger",
  31124. "iron_patriot",
  31125. "ironclad",
  31126. "jack_flag",
  31127. "jack_murdock",
  31128. "jack_power",
  31129. "jackal",
  31130. "jackpot",
  31131. "james_howlett",
  31132. "jamie_braddock",
  31133. "jane_foster",
  31134. "jasper_sitwell",
  31135. "jazinda",
  31136. "jean_grey",
  31137. "jetstream",
  31138. "jigsaw",
  31139. "jimmy_woo",
  31140. "jocasta",
  31141. "johnny_blaze",
  31142. "johnny_storm",
  31143. "joseph",
  31144. "joshua_kane",
  31145. "joystick",
  31146. "jubilee",
  31147. "juggernaut",
  31148. "junta",
  31149. "justice",
  31150. "justin_hammer",
  31151. "kabuki",
  31152. "kang",
  31153. "karen_page",
  31154. "karma",
  31155. "karnak",
  31156. "kat_farrell",
  31157. "kate_bishop",
  31158. "katie_power",
  31159. "ken_ellis",
  31160. "khan",
  31161. "kid_colt",
  31162. "killer_shrike",
  31163. "killmonger",
  31164. "killraven",
  31165. "king_bedlam",
  31166. "king_cobra",
  31167. "kingpin",
  31168. "kinsey_walden",
  31169. "kitty_pryde",
  31170. "klaw",
  31171. "komodo",
  31172. "korath",
  31173. "korg",
  31174. "korvac",
  31175. "kree",
  31176. "krista_starr",
  31177. "kronos",
  31178. "kulan_gath",
  31179. "kylun",
  31180. "la_nuit",
  31181. "lady_bullseye",
  31182. "lady_deathstrike",
  31183. "lady_mastermind",
  31184. "lady_ursula",
  31185. "lady_vermin",
  31186. "lake",
  31187. "landau",
  31188. "layla_miller",
  31189. "leader",
  31190. "leech",
  31191. "legion",
  31192. "lenny_balinger",
  31193. "leo",
  31194. "leopardon",
  31195. "leper_queen",
  31196. "lester",
  31197. "lethal_legion",
  31198. "lifeguard",
  31199. "lightspeed",
  31200. "lila_cheney",
  31201. "lilandra",
  31202. "lilith",
  31203. "lily_hollister",
  31204. "lionheart",
  31205. "living_lightning",
  31206. "living_mummy",
  31207. "living_tribunal",
  31208. "liz_osborn",
  31209. "lizard",
  31210. "loa",
  31211. "lockheed",
  31212. "lockjaw",
  31213. "logan",
  31214. "loki",
  31215. "loners",
  31216. "longshot",
  31217. "lord_hawal",
  31218. "lord_tyger",
  31219. "lorna_dane",
  31220. "luckman",
  31221. "lucky_pierre",
  31222. "luke_cage",
  31223. "luminals",
  31224. "lyja",
  31225. "ma_gnuci",
  31226. "mac_gargan",
  31227. "mach_iv",
  31228. "machine_man",
  31229. "mad_thinker",
  31230. "madame_hydra",
  31231. "madame_masque",
  31232. "madame_web",
  31233. "maddog",
  31234. "madelyne_pryor",
  31235. "madripoor",
  31236. "madrox",
  31237. "maelstrom",
  31238. "maestro",
  31239. "magdalene",
  31240. "maggott",
  31241. "magik",
  31242. "maginty",
  31243. "magma",
  31244. "magneto",
  31245. "magus",
  31246. "major_mapleleaf",
  31247. "makkari",
  31248. "malcolm_colcord",
  31249. "malice",
  31250. "mandarin",
  31251. "mandrill",
  31252. "mandroid",
  31253. "manta",
  31254. "mantis",
  31255. "marauders",
  31256. "maria_hill",
  31257. "mariko_yashida",
  31258. "marrow",
  31259. "marten_broadcloak",
  31260. "martin_li",
  31261. "marvel_apes",
  31262. "marvel_boy",
  31263. "marvel_zombies",
  31264. "marvex",
  31265. "masked_marvel",
  31266. "masque",
  31267. "master_chief",
  31268. "master_mold",
  31269. "mastermind",
  31270. "mathemanic",
  31271. "matthew_murdock",
  31272. "mattie_franklin",
  31273. "mauler",
  31274. "maverick",
  31275. "maximus",
  31276. "may_parker",
  31277. "medusa",
  31278. "meggan",
  31279. "meltdown",
  31280. "menace",
  31281. "mentallo",
  31282. "mentor",
  31283. "mephisto",
  31284. "mephistopheles",
  31285. "mercury",
  31286. "mesmero",
  31287. "metal_master",
  31288. "meteorite",
  31289. "micromacro",
  31290. "microbe",
  31291. "microchip",
  31292. "micromax",
  31293. "midnight",
  31294. "miek",
  31295. "mikhail_rasputin",
  31296. "millenium_guard",
  31297. "mimic",
  31298. "mindworm",
  31299. "miracleman",
  31300. "miss_america",
  31301. "mister_fear",
  31302. "mister_sinister",
  31303. "misty_knight",
  31304. "mockingbird",
  31305. "moira_mactaggert",
  31306. "mojo",
  31307. "mole_man",
  31308. "molecule_man",
  31309. "molly_hayes",
  31310. "molten_man",
  31311. "mongoose",
  31312. "mongu",
  31313. "monster_badoon",
  31314. "moon_knight",
  31315. "moondragon",
  31316. "moonstone",
  31317. "morbius",
  31318. "mordo",
  31319. "morg",
  31320. "morgan_stark",
  31321. "morlocks",
  31322. "morlun",
  31323. "morph",
  31324. "mother_askani",
  31325. "mulholland_black",
  31326. "multiple_man",
  31327. "mysterio",
  31328. "mystique",
  31329. "namor",
  31330. "namora",
  31331. "namorita",
  31332. "naoko",
  31333. "natasha_romanoff",
  31334. "nebula",
  31335. "nehzno",
  31336. "nekra",
  31337. "nemesis",
  31338. "network",
  31339. "newton_destine",
  31340. "next_avengers",
  31341. "nextwave",
  31342. "nick_fury",
  31343. "nico_minoru",
  31344. "nicolaos",
  31345. "night_nurse",
  31346. "night_thrasher",
  31347. "nightcrawler",
  31348. "nighthawk",
  31349. "nightmare",
  31350. "nightshade",
  31351. "nitro",
  31352. "nocturne",
  31353. "nomad",
  31354. "norman_osborn",
  31355. "norrin_radd",
  31356. "northstar",
  31357. "nova",
  31358. "nuke",
  31359. "obadiah_stane",
  31360. "odin",
  31361. "ogun",
  31362. "old_lace",
  31363. "omega_flight",
  31364. "omega_red",
  31365. "omega_sentinel",
  31366. "onslaught",
  31367. "oracle",
  31368. "orphan",
  31369. "otto_octavius",
  31370. "outlaw_kid",
  31371. "overlord",
  31372. "owl",
  31373. "ozymandias",
  31374. "paibok",
  31375. "paladin",
  31376. "pandemic",
  31377. "paper_doll",
  31378. "patch",
  31379. "patriot",
  31380. "payback",
  31381. "penance",
  31382. "pepper_potts",
  31383. "pestilence",
  31384. "pet_avengers",
  31385. "pete_wisdom",
  31386. "peter_parker",
  31387. "peter_quill",
  31388. "phalanx",
  31389. "phantom_reporter",
  31390. "phil_sheldon",
  31391. "photon",
  31392. "piledriver",
  31393. "pixie",
  31394. "plazm",
  31395. "polaris",
  31396. "post",
  31397. "power_man",
  31398. "power_pack",
  31399. "praxagora",
  31400. "preak",
  31401. "pretty_boy",
  31402. "pride",
  31403. "prima",
  31404. "princess_powerful",
  31405. "prism",
  31406. "prodigy",
  31407. "proemial_gods",
  31408. "professor_monster",
  31409. "proteus",
  31410. "proudstar",
  31411. "prowler",
  31412. "psylocke",
  31413. "psynapse",
  31414. "puck",
  31415. "puff_adder",
  31416. "puma",
  31417. "punisher",
  31418. "puppet_master",
  31419. "purifiers",
  31420. "purple_man",
  31421. "pyro",
  31422. "quasar",
  31423. "quasimodo",
  31424. "queen_noir",
  31425. "quentin_quire",
  31426. "quicksilver",
  31427. "rachel_grey",
  31428. "radioactive_man",
  31429. "rafael_vega",
  31430. "rage",
  31431. "raider",
  31432. "randall",
  31433. "randall_flagg",
  31434. "random",
  31435. "rattler",
  31436. "ravenous",
  31437. "rawhide_kid",
  31438. "raza",
  31439. "reaper",
  31440. "reavers",
  31441. "red_ghost",
  31442. "red_hulk",
  31443. "red_shift",
  31444. "red_skull",
  31445. "red_wolf",
  31446. "redwing",
  31447. "reptil",
  31448. "retro_girl",
  31449. "revanche",
  31450. "rhino",
  31451. "rhodey",
  31452. "richard_fisk",
  31453. "rick_jones",
  31454. "ricochet",
  31455. "rictor",
  31456. "riptide",
  31457. "risque",
  31458. "robbie_robertson",
  31459. "robin_chapel",
  31460. "rocket_raccoon",
  31461. "rocket_racer",
  31462. "rockslide",
  31463. "rogue",
  31464. "roland_deschain",
  31465. "romulus",
  31466. "ronan",
  31467. "roughhouse",
  31468. "roulette",
  31469. "roxanne_simpson",
  31470. "rumiko_fujikawa",
  31471. "runaways",
  31472. "sabra",
  31473. "sabretooth",
  31474. "sage",
  31475. "sally_floyd",
  31476. "salo",
  31477. "sandman",
  31478. "santa_claus",
  31479. "saracen",
  31480. "sasquatch",
  31481. "satana",
  31482. "sauron",
  31483. "scalphunter",
  31484. "scarecrow",
  31485. "scarlet_spider",
  31486. "scarlet_witch",
  31487. "scorpion",
  31488. "scourge",
  31489. "scrambler",
  31490. "scream",
  31491. "screwball",
  31492. "sebastian_shaw",
  31493. "secret_warriors",
  31494. "selene",
  31495. "senator_kelly",
  31496. "sentinel",
  31497. "sentinels",
  31498. "sentry",
  31499. "ser_duncan",
  31500. "serpent_society",
  31501. "sersi",
  31502. "shadow_king",
  31503. "shadowcat",
  31504. "shaman",
  31505. "shape",
  31506. "shard",
  31507. "sharon_carter",
  31508. "sharon_ventura",
  31509. "shatterstar",
  31510. "shen",
  31511. "sheva_callister",
  31512. "shinko_yamashiro",
  31513. "shinobi_shaw",
  31514. "shiva",
  31515. "shiver_man",
  31516. "shocker",
  31517. "shockwave",
  31518. "shooting_star",
  31519. "shotgun",
  31520. "shriek",
  31521. "silhouette",
  31522. "silk_fever",
  31523. "silver_centurion",
  31524. "silver_fox",
  31525. "silver_sable",
  31526. "silver_samurai",
  31527. "silver_surfer",
  31528. "silverclaw",
  31529. "silvermane",
  31530. "sinister_six",
  31531. "sir_ram",
  31532. "siren",
  31533. "sister_grimm",
  31534. "skaar",
  31535. "skin",
  31536. "skreet",
  31537. "skrulls",
  31538. "skullbuster",
  31539. "slapstick",
  31540. "slayback",
  31541. "sleeper",
  31542. "sleepwalker",
  31543. "slipstream",
  31544. "slyde",
  31545. "smasher",
  31546. "smiling_tiger",
  31547. "snowbird",
  31548. "solo",
  31549. "songbird",
  31550. "spacker_dave",
  31551. "spectrum",
  31552. "speed",
  31553. "speed_demon",
  31554. "speedball",
  31555. "spencer_smythe",
  31556. "sphinx",
  31557. "spiral",
  31558. "spirit",
  31559. "spitfire",
  31560. "spot",
  31561. "sprite",
  31562. "spyke",
  31563. "squadron_sinister",
  31564. "squadron_supreme",
  31565. "squirrel_girl",
  31566. "star_brand",
  31567. "starbolt",
  31568. "stardust",
  31569. "starfox",
  31570. "starhawk",
  31571. "starjammers",
  31572. "stark_industries",
  31573. "stature",
  31574. "steel_serpent",
  31575. "stellaris",
  31576. "stepford_cuckoos",
  31577. "stephen_strange",
  31578. "steve_rogers",
  31579. "stick",
  31580. "stingray",
  31581. "stone_men",
  31582. "storm",
  31583. "stranger",
  31584. "strong_guy",
  31585. "stryfe",
  31586. "sue_storm",
  31587. "sugar_man",
  31588. "sumo",
  31589. "sunfire",
  31590. "sunset_bain",
  31591. "sunspot",
  31592. "supernaut",
  31593. "supreme_intelligence",
  31594. "surge",
  31595. "susan_delgado",
  31596. "swarm",
  31597. "sway",
  31598. "switch",
  31599. "swordsman",
  31600. "synch",
  31601. "tag",
  31602. "talisman",
  31603. "talkback",
  31604. "talon",
  31605. "talos",
  31606. "tana_nile",
  31607. "tarantula",
  31608. "tarot",
  31609. "taskmaster",
  31610. "tattoo",
  31611. "ted_forrester",
  31612. "tempest",
  31613. "tenebrous",
  31614. "terrax",
  31615. "terror",
  31616. "texas_twister",
  31617. "thaddeus_ross",
  31618. "thanos",
  31619. "the_anarchist",
  31620. "the_call",
  31621. "the_captain",
  31622. "the_enforcers",
  31623. "the_executioner",
  31624. "the_fallen",
  31625. "the_fury",
  31626. "the_hand",
  31627. "the_hood",
  31628. "the_hunter",
  31629. "the_initiative",
  31630. "the_leader",
  31631. "the_liberteens",
  31632. "the_order",
  31633. "the_phantom",
  31634. "the_professor",
  31635. "the_renegades",
  31636. "the_santerians",
  31637. "the_spike",
  31638. "the_stranger",
  31639. "the_twelve",
  31640. "the_watchers",
  31641. "thena",
  31642. "thing",
  31643. "thor",
  31644. "thor_girl",
  31645. "thunderball",
  31646. "thunderbird",
  31647. "thunderbolt",
  31648. "thunderbolt_ross",
  31649. "thunderbolts",
  31650. "thundra",
  31651. "tiger_shark",
  31652. "tigra",
  31653. "timeslip",
  31654. "tinkerer",
  31655. "titania",
  31656. "titanium_man",
  31657. "toad",
  31658. "toad_men",
  31659. "tomas",
  31660. "tombstone",
  31661. "tomorrow_man",
  31662. "tony_stark",
  31663. "toro",
  31664. "toxin",
  31665. "trauma",
  31666. "triathlon",
  31667. "trish_tilby",
  31668. "triton",
  31669. "true_believers",
  31670. "turbo",
  31671. "tusk",
  31672. "tyger_tiger",
  31673. "typhoid_mary",
  31674. "tyrannus",
  31675. "ulik",
  31676. "ultimates",
  31677. "ultimatum",
  31678. "ultimo",
  31679. "ultragirl",
  31680. "ultron",
  31681. "umar",
  31682. "unicorn",
  31683. "union_jack",
  31684. "unus",
  31685. "valeria_richards",
  31686. "valkyrie",
  31687. "vampiro",
  31688. "vance_astro",
  31689. "vanisher",
  31690. "vapor",
  31691. "vargas",
  31692. "vector",
  31693. "veda",
  31694. "vengeance",
  31695. "venom",
  31696. "venus",
  31697. "vermin",
  31698. "vertigo",
  31699. "victor_mancha",
  31700. "vin_gonzales",
  31701. "vindicator",
  31702. "violations",
  31703. "viper",
  31704. "virginia_dare",
  31705. "vision",
  31706. "vivisector",
  31707. "vulcan",
  31708. "vulture",
  31709. "wallflower",
  31710. "wallop",
  31711. "wallow",
  31712. "war_machine",
  31713. "warbird",
  31714. "warbound",
  31715. "warhawk",
  31716. "warlock",
  31717. "warpath",
  31718. "warstar",
  31719. "wasp",
  31720. "weapon_omega",
  31721. "wendell_rand",
  31722. "wendell_vaughn",
  31723. "wendigo",
  31724. "whiplash",
  31725. "whirlwind",
  31726. "whistler",
  31727. "white_queen",
  31728. "white_tiger",
  31729. "whizzer",
  31730. "wiccan",
  31731. "wild_child",
  31732. "wild_pack",
  31733. "wildside",
  31734. "william_stryker",
  31735. "wilson_fisk",
  31736. "wind_dancer",
  31737. "winter_soldier",
  31738. "wither",
  31739. "wolf_cub",
  31740. "wolfpack",
  31741. "wolfsbane",
  31742. "wolverine",
  31743. "wonder_man",
  31744. "wong",
  31745. "wraith",
  31746. "wrecker",
  31747. "wrecking_crew",
  31748. "xavin",
  31749. "xorn",
  31750. "yellow_claw",
  31751. "yellowjacket",
  31752. "young_avengers",
  31753. "zaladane",
  31754. "zaran",
  31755. "zarda",
  31756. "zarek",
  31757. "zeigeist",
  31758. "zemo",
  31759. "zodiak",
  31760. "zombie",
  31761. "zuras",
  31762. "zzzax"
  31763. ];
  31764. }
  31765. });
  31766. // src/cli/commands/migrate.ts
  31767. var migrate_exports = {};
  31768. __export(migrate_exports, {
  31769. BREAKPOINT: () => BREAKPOINT,
  31770. columnsResolver: () => columnsResolver,
  31771. embeddedMigrations: () => embeddedMigrations,
  31772. enumsResolver: () => enumsResolver,
  31773. indPolicyResolver: () => indPolicyResolver,
  31774. mySqlViewsResolver: () => mySqlViewsResolver,
  31775. policyResolver: () => policyResolver,
  31776. prepareAndExportLibSQL: () => prepareAndExportLibSQL,
  31777. prepareAndExportMysql: () => prepareAndExportMysql,
  31778. prepareAndExportPg: () => prepareAndExportPg,
  31779. prepareAndExportSinglestore: () => prepareAndExportSinglestore,
  31780. prepareAndExportSqlite: () => prepareAndExportSqlite,
  31781. prepareAndMigrateLibSQL: () => prepareAndMigrateLibSQL,
  31782. prepareAndMigrateMysql: () => prepareAndMigrateMysql,
  31783. prepareAndMigratePg: () => prepareAndMigratePg,
  31784. prepareAndMigrateSingleStore: () => prepareAndMigrateSingleStore,
  31785. prepareAndMigrateSqlite: () => prepareAndMigrateSqlite,
  31786. prepareLibSQLPush: () => prepareLibSQLPush,
  31787. prepareMySQLPush: () => prepareMySQLPush,
  31788. preparePgPush: () => preparePgPush,
  31789. prepareSQLitePush: () => prepareSQLitePush,
  31790. prepareSingleStorePush: () => prepareSingleStorePush,
  31791. prepareSnapshotFolderName: () => prepareSnapshotFolderName,
  31792. promptColumnsConflicts: () => promptColumnsConflicts,
  31793. promptNamedConflict: () => promptNamedConflict,
  31794. promptNamedWithSchemasConflict: () => promptNamedWithSchemasConflict,
  31795. promptSchemasConflict: () => promptSchemasConflict,
  31796. roleResolver: () => roleResolver,
  31797. schemasResolver: () => schemasResolver,
  31798. sequencesResolver: () => sequencesResolver,
  31799. sqliteViewsResolver: () => sqliteViewsResolver,
  31800. tablesResolver: () => tablesResolver,
  31801. viewsResolver: () => viewsResolver,
  31802. writeResult: () => writeResult
  31803. });
  31804. var import_fs6, import_hanji3, import_path5, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, roleResolver, policyResolver, indPolicyResolver, enumsResolver, columnsResolver, prepareAndMigratePg, prepareAndExportPg, preparePgPush, prepareMySQLPush, prepareAndMigrateMysql, prepareSingleStorePush, prepareAndMigrateSingleStore, prepareAndExportSinglestore, prepareAndExportMysql, prepareAndMigrateSqlite, prepareAndExportSqlite, prepareAndMigrateLibSQL, prepareAndExportLibSQL, prepareSQLitePush, prepareLibSQLPush, promptColumnsConflicts, promptNamedConflict, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT, writeResult, embeddedMigrations, prepareSnapshotFolderName, two;
  31805. var init_migrate = __esm({
  31806. "src/cli/commands/migrate.ts"() {
  31807. "use strict";
  31808. import_fs6 = __toESM(require("fs"));
  31809. init_migrationPreparator();
  31810. init_source();
  31811. import_hanji3 = __toESM(require_hanji());
  31812. import_path5 = __toESM(require("path"));
  31813. init_singlestoreSchema();
  31814. init_mysqlSchema();
  31815. init_pgSchema();
  31816. init_sqliteSchema();
  31817. init_snapshotsDiffer();
  31818. init_utils2();
  31819. init_words();
  31820. init_outputs();
  31821. init_views();
  31822. schemasResolver = async (input) => {
  31823. try {
  31824. const { created, deleted, renamed } = await promptSchemasConflict(
  31825. input.created,
  31826. input.deleted
  31827. );
  31828. return { created, deleted, renamed };
  31829. } catch (e4) {
  31830. console.error(e4);
  31831. throw e4;
  31832. }
  31833. };
  31834. tablesResolver = async (input) => {
  31835. try {
  31836. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  31837. input.created,
  31838. input.deleted,
  31839. "table"
  31840. );
  31841. return {
  31842. created,
  31843. deleted,
  31844. moved,
  31845. renamed
  31846. };
  31847. } catch (e4) {
  31848. console.error(e4);
  31849. throw e4;
  31850. }
  31851. };
  31852. viewsResolver = async (input) => {
  31853. try {
  31854. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  31855. input.created,
  31856. input.deleted,
  31857. "view"
  31858. );
  31859. return {
  31860. created,
  31861. deleted,
  31862. moved,
  31863. renamed
  31864. };
  31865. } catch (e4) {
  31866. console.error(e4);
  31867. throw e4;
  31868. }
  31869. };
  31870. mySqlViewsResolver = async (input) => {
  31871. try {
  31872. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  31873. input.created,
  31874. input.deleted,
  31875. "view"
  31876. );
  31877. return {
  31878. created,
  31879. deleted,
  31880. moved,
  31881. renamed
  31882. };
  31883. } catch (e4) {
  31884. console.error(e4);
  31885. throw e4;
  31886. }
  31887. };
  31888. sqliteViewsResolver = async (input) => {
  31889. try {
  31890. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  31891. input.created,
  31892. input.deleted,
  31893. "view"
  31894. );
  31895. return {
  31896. created,
  31897. deleted,
  31898. moved,
  31899. renamed
  31900. };
  31901. } catch (e4) {
  31902. console.error(e4);
  31903. throw e4;
  31904. }
  31905. };
  31906. sequencesResolver = async (input) => {
  31907. try {
  31908. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  31909. input.created,
  31910. input.deleted,
  31911. "sequence"
  31912. );
  31913. return {
  31914. created,
  31915. deleted,
  31916. moved,
  31917. renamed
  31918. };
  31919. } catch (e4) {
  31920. console.error(e4);
  31921. throw e4;
  31922. }
  31923. };
  31924. roleResolver = async (input) => {
  31925. const result = await promptNamedConflict(
  31926. input.created,
  31927. input.deleted,
  31928. "role"
  31929. );
  31930. return {
  31931. created: result.created,
  31932. deleted: result.deleted,
  31933. renamed: result.renamed
  31934. };
  31935. };
  31936. policyResolver = async (input) => {
  31937. const result = await promptColumnsConflicts(
  31938. input.tableName,
  31939. input.created,
  31940. input.deleted
  31941. );
  31942. return {
  31943. tableName: input.tableName,
  31944. schema: input.schema,
  31945. created: result.created,
  31946. deleted: result.deleted,
  31947. renamed: result.renamed
  31948. };
  31949. };
  31950. indPolicyResolver = async (input) => {
  31951. const result = await promptNamedConflict(
  31952. input.created,
  31953. input.deleted,
  31954. "policy"
  31955. );
  31956. return {
  31957. created: result.created,
  31958. deleted: result.deleted,
  31959. renamed: result.renamed
  31960. };
  31961. };
  31962. enumsResolver = async (input) => {
  31963. try {
  31964. const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
  31965. input.created,
  31966. input.deleted,
  31967. "enum"
  31968. );
  31969. return {
  31970. created,
  31971. deleted,
  31972. moved,
  31973. renamed
  31974. };
  31975. } catch (e4) {
  31976. console.error(e4);
  31977. throw e4;
  31978. }
  31979. };
  31980. columnsResolver = async (input) => {
  31981. const result = await promptColumnsConflicts(
  31982. input.tableName,
  31983. input.created,
  31984. input.deleted
  31985. );
  31986. return {
  31987. tableName: input.tableName,
  31988. schema: input.schema,
  31989. created: result.created,
  31990. deleted: result.deleted,
  31991. renamed: result.renamed
  31992. };
  31993. };
  31994. prepareAndMigratePg = async (config) => {
  31995. const outFolder = config.out;
  31996. const schemaPath = config.schema;
  31997. const casing2 = config.casing;
  31998. try {
  31999. assertV1OutFolder(outFolder);
  32000. const { snapshots, journal } = prepareMigrationFolder(
  32001. outFolder,
  32002. "postgresql"
  32003. );
  32004. const { prev, cur, custom: custom2 } = await preparePgMigrationSnapshot(
  32005. snapshots,
  32006. schemaPath,
  32007. casing2
  32008. );
  32009. const validatedPrev = pgSchema.parse(prev);
  32010. const validatedCur = pgSchema.parse(cur);
  32011. if (config.custom) {
  32012. writeResult({
  32013. cur: custom2,
  32014. sqlStatements: [],
  32015. journal,
  32016. outFolder,
  32017. name: config.name,
  32018. breakpoints: config.breakpoints,
  32019. type: "custom",
  32020. prefixMode: config.prefix
  32021. });
  32022. return;
  32023. }
  32024. const squashedPrev = squashPgScheme(validatedPrev);
  32025. const squashedCur = squashPgScheme(validatedCur);
  32026. const { sqlStatements, _meta } = await applyPgSnapshotsDiff(
  32027. squashedPrev,
  32028. squashedCur,
  32029. schemasResolver,
  32030. enumsResolver,
  32031. sequencesResolver,
  32032. policyResolver,
  32033. indPolicyResolver,
  32034. roleResolver,
  32035. tablesResolver,
  32036. columnsResolver,
  32037. viewsResolver,
  32038. validatedPrev,
  32039. validatedCur
  32040. );
  32041. writeResult({
  32042. cur,
  32043. sqlStatements,
  32044. journal,
  32045. outFolder,
  32046. name: config.name,
  32047. breakpoints: config.breakpoints,
  32048. prefixMode: config.prefix
  32049. });
  32050. } catch (e4) {
  32051. console.error(e4);
  32052. }
  32053. };
  32054. prepareAndExportPg = async (config) => {
  32055. const schemaPath = config.schema;
  32056. try {
  32057. const { prev, cur } = await preparePgMigrationSnapshot(
  32058. [],
  32059. // no snapshots before
  32060. schemaPath,
  32061. void 0
  32062. );
  32063. const validatedPrev = pgSchema.parse(prev);
  32064. const validatedCur = pgSchema.parse(cur);
  32065. const squashedPrev = squashPgScheme(validatedPrev);
  32066. const squashedCur = squashPgScheme(validatedCur);
  32067. const { sqlStatements } = await applyPgSnapshotsDiff(
  32068. squashedPrev,
  32069. squashedCur,
  32070. schemasResolver,
  32071. enumsResolver,
  32072. sequencesResolver,
  32073. policyResolver,
  32074. indPolicyResolver,
  32075. roleResolver,
  32076. tablesResolver,
  32077. columnsResolver,
  32078. viewsResolver,
  32079. validatedPrev,
  32080. validatedCur
  32081. );
  32082. console.log(sqlStatements.join("\n"));
  32083. } catch (e4) {
  32084. console.error(e4);
  32085. }
  32086. };
  32087. preparePgPush = async (cur, prev) => {
  32088. const validatedPrev = pgSchema.parse(prev);
  32089. const validatedCur = pgSchema.parse(cur);
  32090. const squashedPrev = squashPgScheme(validatedPrev, "push");
  32091. const squashedCur = squashPgScheme(validatedCur, "push");
  32092. const { sqlStatements, statements, _meta } = await applyPgSnapshotsDiff(
  32093. squashedPrev,
  32094. squashedCur,
  32095. schemasResolver,
  32096. enumsResolver,
  32097. sequencesResolver,
  32098. policyResolver,
  32099. indPolicyResolver,
  32100. roleResolver,
  32101. tablesResolver,
  32102. columnsResolver,
  32103. viewsResolver,
  32104. validatedPrev,
  32105. validatedCur,
  32106. "push"
  32107. );
  32108. return { sqlStatements, statements, squashedPrev, squashedCur };
  32109. };
  32110. prepareMySQLPush = async (schemaPath, snapshot, casing2) => {
  32111. try {
  32112. const { prev, cur } = await prepareMySqlDbPushSnapshot(
  32113. snapshot,
  32114. schemaPath,
  32115. casing2
  32116. );
  32117. const validatedPrev = mysqlSchema.parse(prev);
  32118. const validatedCur = mysqlSchema.parse(cur);
  32119. const squashedPrev = squashMysqlScheme(validatedPrev);
  32120. const squashedCur = squashMysqlScheme(validatedCur);
  32121. const { sqlStatements, statements } = await applyMysqlSnapshotsDiff(
  32122. squashedPrev,
  32123. squashedCur,
  32124. tablesResolver,
  32125. columnsResolver,
  32126. mySqlViewsResolver,
  32127. validatedPrev,
  32128. validatedCur,
  32129. "push"
  32130. );
  32131. return { sqlStatements, statements, validatedCur, validatedPrev };
  32132. } catch (e4) {
  32133. console.error(e4);
  32134. process.exit(1);
  32135. }
  32136. };
  32137. prepareAndMigrateMysql = async (config) => {
  32138. const outFolder = config.out;
  32139. const schemaPath = config.schema;
  32140. const casing2 = config.casing;
  32141. try {
  32142. assertV1OutFolder(outFolder);
  32143. const { snapshots, journal } = prepareMigrationFolder(outFolder, "mysql");
  32144. const { prev, cur, custom: custom2 } = await prepareMySqlMigrationSnapshot(
  32145. snapshots,
  32146. schemaPath,
  32147. casing2
  32148. );
  32149. const validatedPrev = mysqlSchema.parse(prev);
  32150. const validatedCur = mysqlSchema.parse(cur);
  32151. if (config.custom) {
  32152. writeResult({
  32153. cur: custom2,
  32154. sqlStatements: [],
  32155. journal,
  32156. outFolder,
  32157. name: config.name,
  32158. breakpoints: config.breakpoints,
  32159. type: "custom",
  32160. prefixMode: config.prefix
  32161. });
  32162. return;
  32163. }
  32164. const squashedPrev = squashMysqlScheme(validatedPrev);
  32165. const squashedCur = squashMysqlScheme(validatedCur);
  32166. const { sqlStatements, statements, _meta } = await applyMysqlSnapshotsDiff(
  32167. squashedPrev,
  32168. squashedCur,
  32169. tablesResolver,
  32170. columnsResolver,
  32171. mySqlViewsResolver,
  32172. validatedPrev,
  32173. validatedCur
  32174. );
  32175. writeResult({
  32176. cur,
  32177. sqlStatements,
  32178. journal,
  32179. _meta,
  32180. outFolder,
  32181. name: config.name,
  32182. breakpoints: config.breakpoints,
  32183. prefixMode: config.prefix
  32184. });
  32185. } catch (e4) {
  32186. console.error(e4);
  32187. }
  32188. };
  32189. prepareSingleStorePush = async (schemaPath, snapshot, casing2) => {
  32190. try {
  32191. const { prev, cur } = await prepareSingleStoreDbPushSnapshot(
  32192. snapshot,
  32193. schemaPath,
  32194. casing2
  32195. );
  32196. const validatedPrev = singlestoreSchema.parse(prev);
  32197. const validatedCur = singlestoreSchema.parse(cur);
  32198. const squashedPrev = squashSingleStoreScheme(validatedPrev);
  32199. const squashedCur = squashSingleStoreScheme(validatedCur);
  32200. const { sqlStatements, statements } = await applySingleStoreSnapshotsDiff(
  32201. squashedPrev,
  32202. squashedCur,
  32203. tablesResolver,
  32204. columnsResolver,
  32205. /* singleStoreViewsResolver, */
  32206. validatedPrev,
  32207. validatedCur,
  32208. "push"
  32209. );
  32210. return { sqlStatements, statements, validatedCur, validatedPrev };
  32211. } catch (e4) {
  32212. console.error(e4);
  32213. process.exit(1);
  32214. }
  32215. };
  32216. prepareAndMigrateSingleStore = async (config) => {
  32217. const outFolder = config.out;
  32218. const schemaPath = config.schema;
  32219. const casing2 = config.casing;
  32220. try {
  32221. assertV1OutFolder(outFolder);
  32222. const { snapshots, journal } = prepareMigrationFolder(outFolder, "singlestore");
  32223. const { prev, cur, custom: custom2 } = await prepareSingleStoreMigrationSnapshot(
  32224. snapshots,
  32225. schemaPath,
  32226. casing2
  32227. );
  32228. const validatedPrev = singlestoreSchema.parse(prev);
  32229. const validatedCur = singlestoreSchema.parse(cur);
  32230. if (config.custom) {
  32231. writeResult({
  32232. cur: custom2,
  32233. sqlStatements: [],
  32234. journal,
  32235. outFolder,
  32236. name: config.name,
  32237. breakpoints: config.breakpoints,
  32238. type: "custom",
  32239. prefixMode: config.prefix
  32240. });
  32241. return;
  32242. }
  32243. const squashedPrev = squashSingleStoreScheme(validatedPrev);
  32244. const squashedCur = squashSingleStoreScheme(validatedCur);
  32245. const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
  32246. squashedPrev,
  32247. squashedCur,
  32248. tablesResolver,
  32249. columnsResolver,
  32250. /* singleStoreViewsResolver, */
  32251. validatedPrev,
  32252. validatedCur
  32253. );
  32254. writeResult({
  32255. cur,
  32256. sqlStatements,
  32257. journal,
  32258. _meta,
  32259. outFolder,
  32260. name: config.name,
  32261. breakpoints: config.breakpoints,
  32262. prefixMode: config.prefix
  32263. });
  32264. } catch (e4) {
  32265. console.error(e4);
  32266. }
  32267. };
  32268. prepareAndExportSinglestore = async (config) => {
  32269. const schemaPath = config.schema;
  32270. try {
  32271. const { prev, cur } = await prepareSingleStoreMigrationSnapshot(
  32272. [],
  32273. schemaPath,
  32274. void 0
  32275. );
  32276. const validatedPrev = singlestoreSchema.parse(prev);
  32277. const validatedCur = singlestoreSchema.parse(cur);
  32278. const squashedPrev = squashSingleStoreScheme(validatedPrev);
  32279. const squashedCur = squashSingleStoreScheme(validatedCur);
  32280. const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
  32281. squashedPrev,
  32282. squashedCur,
  32283. tablesResolver,
  32284. columnsResolver,
  32285. /* singleStoreViewsResolver, */
  32286. validatedPrev,
  32287. validatedCur
  32288. );
  32289. console.log(sqlStatements.join("\n"));
  32290. } catch (e4) {
  32291. console.error(e4);
  32292. }
  32293. };
  32294. prepareAndExportMysql = async (config) => {
  32295. const schemaPath = config.schema;
  32296. try {
  32297. const { prev, cur, custom: custom2 } = await prepareMySqlMigrationSnapshot(
  32298. [],
  32299. schemaPath,
  32300. void 0
  32301. );
  32302. const validatedPrev = mysqlSchema.parse(prev);
  32303. const validatedCur = mysqlSchema.parse(cur);
  32304. const squashedPrev = squashMysqlScheme(validatedPrev);
  32305. const squashedCur = squashMysqlScheme(validatedCur);
  32306. const { sqlStatements, statements, _meta } = await applyMysqlSnapshotsDiff(
  32307. squashedPrev,
  32308. squashedCur,
  32309. tablesResolver,
  32310. columnsResolver,
  32311. mySqlViewsResolver,
  32312. validatedPrev,
  32313. validatedCur
  32314. );
  32315. console.log(sqlStatements.join("\n"));
  32316. } catch (e4) {
  32317. console.error(e4);
  32318. }
  32319. };
  32320. prepareAndMigrateSqlite = async (config) => {
  32321. const outFolder = config.out;
  32322. const schemaPath = config.schema;
  32323. const casing2 = config.casing;
  32324. try {
  32325. assertV1OutFolder(outFolder);
  32326. const { snapshots, journal } = prepareMigrationFolder(outFolder, "sqlite");
  32327. const { prev, cur, custom: custom2 } = await prepareSqliteMigrationSnapshot(
  32328. snapshots,
  32329. schemaPath,
  32330. casing2
  32331. );
  32332. const validatedPrev = sqliteSchema.parse(prev);
  32333. const validatedCur = sqliteSchema.parse(cur);
  32334. if (config.custom) {
  32335. writeResult({
  32336. cur: custom2,
  32337. sqlStatements: [],
  32338. journal,
  32339. outFolder,
  32340. name: config.name,
  32341. breakpoints: config.breakpoints,
  32342. bundle: config.bundle,
  32343. type: "custom",
  32344. prefixMode: config.prefix
  32345. });
  32346. return;
  32347. }
  32348. const squashedPrev = squashSqliteScheme(validatedPrev);
  32349. const squashedCur = squashSqliteScheme(validatedCur);
  32350. const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
  32351. squashedPrev,
  32352. squashedCur,
  32353. tablesResolver,
  32354. columnsResolver,
  32355. sqliteViewsResolver,
  32356. validatedPrev,
  32357. validatedCur
  32358. );
  32359. writeResult({
  32360. cur,
  32361. sqlStatements,
  32362. journal,
  32363. _meta,
  32364. outFolder,
  32365. name: config.name,
  32366. breakpoints: config.breakpoints,
  32367. bundle: config.bundle,
  32368. prefixMode: config.prefix,
  32369. driver: config.driver
  32370. });
  32371. } catch (e4) {
  32372. console.error(e4);
  32373. }
  32374. };
  32375. prepareAndExportSqlite = async (config) => {
  32376. const schemaPath = config.schema;
  32377. try {
  32378. const { prev, cur } = await prepareSqliteMigrationSnapshot(
  32379. [],
  32380. schemaPath,
  32381. void 0
  32382. );
  32383. const validatedPrev = sqliteSchema.parse(prev);
  32384. const validatedCur = sqliteSchema.parse(cur);
  32385. const squashedPrev = squashSqliteScheme(validatedPrev);
  32386. const squashedCur = squashSqliteScheme(validatedCur);
  32387. const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
  32388. squashedPrev,
  32389. squashedCur,
  32390. tablesResolver,
  32391. columnsResolver,
  32392. sqliteViewsResolver,
  32393. validatedPrev,
  32394. validatedCur
  32395. );
  32396. console.log(sqlStatements.join("\n"));
  32397. } catch (e4) {
  32398. console.error(e4);
  32399. }
  32400. };
  32401. prepareAndMigrateLibSQL = async (config) => {
  32402. const outFolder = config.out;
  32403. const schemaPath = config.schema;
  32404. const casing2 = config.casing;
  32405. try {
  32406. assertV1OutFolder(outFolder);
  32407. const { snapshots, journal } = prepareMigrationFolder(outFolder, "sqlite");
  32408. const { prev, cur, custom: custom2 } = await prepareSqliteMigrationSnapshot(
  32409. snapshots,
  32410. schemaPath,
  32411. casing2
  32412. );
  32413. const validatedPrev = sqliteSchema.parse(prev);
  32414. const validatedCur = sqliteSchema.parse(cur);
  32415. if (config.custom) {
  32416. writeResult({
  32417. cur: custom2,
  32418. sqlStatements: [],
  32419. journal,
  32420. outFolder,
  32421. name: config.name,
  32422. breakpoints: config.breakpoints,
  32423. bundle: config.bundle,
  32424. type: "custom",
  32425. prefixMode: config.prefix
  32426. });
  32427. return;
  32428. }
  32429. const squashedPrev = squashSqliteScheme(validatedPrev);
  32430. const squashedCur = squashSqliteScheme(validatedCur);
  32431. const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
  32432. squashedPrev,
  32433. squashedCur,
  32434. tablesResolver,
  32435. columnsResolver,
  32436. sqliteViewsResolver,
  32437. validatedPrev,
  32438. validatedCur
  32439. );
  32440. writeResult({
  32441. cur,
  32442. sqlStatements,
  32443. journal,
  32444. _meta,
  32445. outFolder,
  32446. name: config.name,
  32447. breakpoints: config.breakpoints,
  32448. bundle: config.bundle,
  32449. prefixMode: config.prefix
  32450. });
  32451. } catch (e4) {
  32452. console.error(e4);
  32453. }
  32454. };
  32455. prepareAndExportLibSQL = async (config) => {
  32456. const schemaPath = config.schema;
  32457. try {
  32458. const { prev, cur, custom: custom2 } = await prepareSqliteMigrationSnapshot(
  32459. [],
  32460. schemaPath,
  32461. void 0
  32462. );
  32463. const validatedPrev = sqliteSchema.parse(prev);
  32464. const validatedCur = sqliteSchema.parse(cur);
  32465. const squashedPrev = squashSqliteScheme(validatedPrev);
  32466. const squashedCur = squashSqliteScheme(validatedCur);
  32467. const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
  32468. squashedPrev,
  32469. squashedCur,
  32470. tablesResolver,
  32471. columnsResolver,
  32472. sqliteViewsResolver,
  32473. validatedPrev,
  32474. validatedCur
  32475. );
  32476. console.log(sqlStatements.join("\n"));
  32477. } catch (e4) {
  32478. console.error(e4);
  32479. }
  32480. };
  32481. prepareSQLitePush = async (schemaPath, snapshot, casing2) => {
  32482. const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath, casing2);
  32483. const validatedPrev = sqliteSchema.parse(prev);
  32484. const validatedCur = sqliteSchema.parse(cur);
  32485. const squashedPrev = squashSqliteScheme(validatedPrev, "push");
  32486. const squashedCur = squashSqliteScheme(validatedCur, "push");
  32487. const { sqlStatements, statements, _meta } = await applySqliteSnapshotsDiff(
  32488. squashedPrev,
  32489. squashedCur,
  32490. tablesResolver,
  32491. columnsResolver,
  32492. sqliteViewsResolver,
  32493. validatedPrev,
  32494. validatedCur,
  32495. "push"
  32496. );
  32497. return {
  32498. sqlStatements,
  32499. statements,
  32500. squashedPrev,
  32501. squashedCur,
  32502. meta: _meta
  32503. };
  32504. };
  32505. prepareLibSQLPush = async (schemaPath, snapshot, casing2) => {
  32506. const { prev, cur } = await prepareSQLiteDbPushSnapshot(snapshot, schemaPath, casing2);
  32507. const validatedPrev = sqliteSchema.parse(prev);
  32508. const validatedCur = sqliteSchema.parse(cur);
  32509. const squashedPrev = squashSqliteScheme(validatedPrev, "push");
  32510. const squashedCur = squashSqliteScheme(validatedCur, "push");
  32511. const { sqlStatements, statements, _meta } = await applyLibSQLSnapshotsDiff(
  32512. squashedPrev,
  32513. squashedCur,
  32514. tablesResolver,
  32515. columnsResolver,
  32516. sqliteViewsResolver,
  32517. validatedPrev,
  32518. validatedCur,
  32519. "push"
  32520. );
  32521. return {
  32522. sqlStatements,
  32523. statements,
  32524. squashedPrev,
  32525. squashedCur,
  32526. meta: _meta
  32527. };
  32528. };
  32529. promptColumnsConflicts = async (tableName, newColumns, missingColumns) => {
  32530. if (newColumns.length === 0 || missingColumns.length === 0) {
  32531. return { created: newColumns, renamed: [], deleted: missingColumns };
  32532. }
  32533. const result = {
  32534. created: [],
  32535. renamed: [],
  32536. deleted: []
  32537. };
  32538. let index6 = 0;
  32539. let leftMissing = [...missingColumns];
  32540. do {
  32541. const created = newColumns[index6];
  32542. const renames = leftMissing.map((it) => {
  32543. return { from: it, to: created };
  32544. });
  32545. const promptData = [created, ...renames];
  32546. const { status, data } = await (0, import_hanji3.render)(
  32547. new ResolveColumnSelect(tableName, created, promptData)
  32548. );
  32549. if (status === "aborted") {
  32550. console.error("ERROR");
  32551. process.exit(1);
  32552. }
  32553. if (isRenamePromptItem(data)) {
  32554. console.log(
  32555. `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
  32556. "column will be renamed"
  32557. )}`
  32558. );
  32559. result.renamed.push(data);
  32560. delete leftMissing[leftMissing.indexOf(data.from)];
  32561. leftMissing = leftMissing.filter(Boolean);
  32562. } else {
  32563. console.log(
  32564. `${source_default.green("+")} ${data.name} ${source_default.gray(
  32565. "column will be created"
  32566. )}`
  32567. );
  32568. result.created.push(created);
  32569. }
  32570. index6 += 1;
  32571. } while (index6 < newColumns.length);
  32572. console.log(
  32573. source_default.gray(`--- all columns conflicts in ${tableName} table resolved ---
  32574. `)
  32575. );
  32576. result.deleted.push(...leftMissing);
  32577. return result;
  32578. };
  32579. promptNamedConflict = async (newItems, missingItems, entity) => {
  32580. if (missingItems.length === 0 || newItems.length === 0) {
  32581. return {
  32582. created: newItems,
  32583. renamed: [],
  32584. deleted: missingItems
  32585. };
  32586. }
  32587. const result = { created: [], renamed: [], deleted: [] };
  32588. let index6 = 0;
  32589. let leftMissing = [...missingItems];
  32590. do {
  32591. const created = newItems[index6];
  32592. const renames = leftMissing.map((it) => {
  32593. return { from: it, to: created };
  32594. });
  32595. const promptData = [created, ...renames];
  32596. const { status, data } = await (0, import_hanji3.render)(
  32597. new ResolveSelectNamed(created, promptData, entity)
  32598. );
  32599. if (status === "aborted") {
  32600. console.error("ERROR");
  32601. process.exit(1);
  32602. }
  32603. if (isRenamePromptItem(data)) {
  32604. console.log(
  32605. `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
  32606. `${entity} will be renamed/moved`
  32607. )}`
  32608. );
  32609. if (data.from.name !== data.to.name) {
  32610. result.renamed.push(data);
  32611. }
  32612. delete leftMissing[leftMissing.indexOf(data.from)];
  32613. leftMissing = leftMissing.filter(Boolean);
  32614. } else {
  32615. console.log(
  32616. `${source_default.green("+")} ${data.name} ${source_default.gray(
  32617. `${entity} will be created`
  32618. )}`
  32619. );
  32620. result.created.push(created);
  32621. }
  32622. index6 += 1;
  32623. } while (index6 < newItems.length);
  32624. console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
  32625. `));
  32626. result.deleted.push(...leftMissing);
  32627. return result;
  32628. };
  32629. promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => {
  32630. if (missingItems.length === 0 || newItems.length === 0) {
  32631. return {
  32632. created: newItems,
  32633. renamed: [],
  32634. moved: [],
  32635. deleted: missingItems
  32636. };
  32637. }
  32638. const result = { created: [], renamed: [], moved: [], deleted: [] };
  32639. let index6 = 0;
  32640. let leftMissing = [...missingItems];
  32641. do {
  32642. const created = newItems[index6];
  32643. const renames = leftMissing.map((it) => {
  32644. return { from: it, to: created };
  32645. });
  32646. const promptData = [created, ...renames];
  32647. const { status, data } = await (0, import_hanji3.render)(
  32648. new ResolveSelect(created, promptData, entity)
  32649. );
  32650. if (status === "aborted") {
  32651. console.error("ERROR");
  32652. process.exit(1);
  32653. }
  32654. if (isRenamePromptItem(data)) {
  32655. const schemaFromPrefix = !data.from.schema || data.from.schema === "public" ? "" : `${data.from.schema}.`;
  32656. const schemaToPrefix = !data.to.schema || data.to.schema === "public" ? "" : `${data.to.schema}.`;
  32657. console.log(
  32658. `${source_default.yellow("~")} ${schemaFromPrefix}${data.from.name} \u203A ${schemaToPrefix}${data.to.name} ${source_default.gray(
  32659. `${entity} will be renamed/moved`
  32660. )}`
  32661. );
  32662. if (data.from.name !== data.to.name) {
  32663. result.renamed.push(data);
  32664. }
  32665. if (data.from.schema !== data.to.schema) {
  32666. result.moved.push({
  32667. name: data.from.name,
  32668. schemaFrom: data.from.schema || "public",
  32669. schemaTo: data.to.schema || "public"
  32670. });
  32671. }
  32672. delete leftMissing[leftMissing.indexOf(data.from)];
  32673. leftMissing = leftMissing.filter(Boolean);
  32674. } else {
  32675. console.log(
  32676. `${source_default.green("+")} ${data.name} ${source_default.gray(
  32677. `${entity} will be created`
  32678. )}`
  32679. );
  32680. result.created.push(created);
  32681. }
  32682. index6 += 1;
  32683. } while (index6 < newItems.length);
  32684. console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
  32685. `));
  32686. result.deleted.push(...leftMissing);
  32687. return result;
  32688. };
  32689. promptSchemasConflict = async (newSchemas, missingSchemas) => {
  32690. if (missingSchemas.length === 0 || newSchemas.length === 0) {
  32691. return { created: newSchemas, renamed: [], deleted: missingSchemas };
  32692. }
  32693. const result = {
  32694. created: [],
  32695. renamed: [],
  32696. deleted: []
  32697. };
  32698. let index6 = 0;
  32699. let leftMissing = [...missingSchemas];
  32700. do {
  32701. const created = newSchemas[index6];
  32702. const renames = leftMissing.map((it) => {
  32703. return { from: it, to: created };
  32704. });
  32705. const promptData = [created, ...renames];
  32706. const { status, data } = await (0, import_hanji3.render)(
  32707. new ResolveSchemasSelect(created, promptData)
  32708. );
  32709. if (status === "aborted") {
  32710. console.error("ERROR");
  32711. process.exit(1);
  32712. }
  32713. if (isRenamePromptItem(data)) {
  32714. console.log(
  32715. `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
  32716. "schema will be renamed"
  32717. )}`
  32718. );
  32719. result.renamed.push(data);
  32720. delete leftMissing[leftMissing.indexOf(data.from)];
  32721. leftMissing = leftMissing.filter(Boolean);
  32722. } else {
  32723. console.log(
  32724. `${source_default.green("+")} ${data.name} ${source_default.gray(
  32725. "schema will be created"
  32726. )}`
  32727. );
  32728. result.created.push(created);
  32729. }
  32730. index6 += 1;
  32731. } while (index6 < newSchemas.length);
  32732. console.log(source_default.gray("--- all schemas conflicts resolved ---\n"));
  32733. result.deleted.push(...leftMissing);
  32734. return result;
  32735. };
  32736. BREAKPOINT = "--> statement-breakpoint\n";
  32737. writeResult = ({
  32738. cur,
  32739. sqlStatements,
  32740. journal,
  32741. _meta = {
  32742. columns: {},
  32743. schemas: {},
  32744. tables: {}
  32745. },
  32746. outFolder,
  32747. breakpoints,
  32748. name,
  32749. bundle = false,
  32750. type = "none",
  32751. prefixMode,
  32752. driver: driver2
  32753. }) => {
  32754. if (type === "none") {
  32755. console.log(schema4(cur));
  32756. if (sqlStatements.length === 0) {
  32757. console.log("No schema changes, nothing to migrate \u{1F634}");
  32758. return;
  32759. }
  32760. }
  32761. const lastEntryInJournal = journal.entries[journal.entries.length - 1];
  32762. const idx = typeof lastEntryInJournal === "undefined" ? 0 : lastEntryInJournal.idx + 1;
  32763. const { prefix: prefix2, tag } = prepareMigrationMetadata(idx, prefixMode, name);
  32764. const toSave = JSON.parse(JSON.stringify(cur));
  32765. toSave["_meta"] = _meta;
  32766. const metaFolderPath = (0, import_path5.join)(outFolder, "meta");
  32767. const metaJournal = (0, import_path5.join)(metaFolderPath, "_journal.json");
  32768. import_fs6.default.writeFileSync(
  32769. (0, import_path5.join)(metaFolderPath, `${prefix2}_snapshot.json`),
  32770. JSON.stringify(toSave, null, 2)
  32771. );
  32772. const sqlDelimiter = breakpoints ? BREAKPOINT : "\n";
  32773. let sql = sqlStatements.join(sqlDelimiter);
  32774. if (type === "introspect") {
  32775. sql = `-- Current sql file was generated after introspecting the database
  32776. -- If you want to run this migration please uncomment this code before executing migrations
  32777. /*
  32778. ${sql}
  32779. */`;
  32780. }
  32781. if (type === "custom") {
  32782. console.log("Prepared empty file for your custom SQL migration!");
  32783. sql = "-- Custom SQL migration file, put your code below! --";
  32784. }
  32785. journal.entries.push({
  32786. idx,
  32787. version: cur.version,
  32788. when: +/* @__PURE__ */ new Date(),
  32789. tag,
  32790. breakpoints
  32791. });
  32792. import_fs6.default.writeFileSync(metaJournal, JSON.stringify(journal, null, 2));
  32793. import_fs6.default.writeFileSync(`${outFolder}/${tag}.sql`, sql);
  32794. if (bundle) {
  32795. const js = embeddedMigrations(journal, driver2);
  32796. import_fs6.default.writeFileSync(`${outFolder}/migrations.js`, js);
  32797. }
  32798. (0, import_hanji3.render)(
  32799. `[${source_default.green(
  32800. "\u2713"
  32801. )}] Your SQL migration file \u279C ${source_default.bold.underline.blue(
  32802. import_path5.default.join(`${outFolder}/${tag}.sql`)
  32803. )} \u{1F680}`
  32804. );
  32805. };
  32806. embeddedMigrations = (journal, driver2) => {
  32807. let content = driver2 === "expo" ? "// This file is required for Expo/React Native SQLite migrations - https://orm.drizzle.team/quick-sqlite/expo\n\n" : "";
  32808. content += "import journal from './meta/_journal.json';\n";
  32809. journal.entries.forEach((entry) => {
  32810. content += `import m${entry.idx.toString().padStart(4, "0")} from './${entry.tag}.sql';
  32811. `;
  32812. });
  32813. content += `
  32814. export default {
  32815. journal,
  32816. migrations: {
  32817. ${journal.entries.map((it) => `m${it.idx.toString().padStart(4, "0")}`).join(",\n")}
  32818. }
  32819. }
  32820. `;
  32821. return content;
  32822. };
  32823. prepareSnapshotFolderName = () => {
  32824. const now = /* @__PURE__ */ new Date();
  32825. return `${now.getFullYear()}${two(now.getUTCMonth() + 1)}${two(
  32826. now.getUTCDate()
  32827. )}${two(now.getUTCHours())}${two(now.getUTCMinutes())}${two(
  32828. now.getUTCSeconds()
  32829. )}`;
  32830. };
  32831. two = (input) => {
  32832. return input.toString().padStart(2, "0");
  32833. };
  32834. }
  32835. });
  32836. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js
  32837. var require_constants = __commonJS({
  32838. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js"(exports2, module2) {
  32839. "use strict";
  32840. var SEMVER_SPEC_VERSION = "2.0.0";
  32841. var MAX_LENGTH = 256;
  32842. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
  32843. 9007199254740991;
  32844. var MAX_SAFE_COMPONENT_LENGTH = 16;
  32845. var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
  32846. var RELEASE_TYPES = [
  32847. "major",
  32848. "premajor",
  32849. "minor",
  32850. "preminor",
  32851. "patch",
  32852. "prepatch",
  32853. "prerelease"
  32854. ];
  32855. module2.exports = {
  32856. MAX_LENGTH,
  32857. MAX_SAFE_COMPONENT_LENGTH,
  32858. MAX_SAFE_BUILD_LENGTH,
  32859. MAX_SAFE_INTEGER,
  32860. RELEASE_TYPES,
  32861. SEMVER_SPEC_VERSION,
  32862. FLAG_INCLUDE_PRERELEASE: 1,
  32863. FLAG_LOOSE: 2
  32864. };
  32865. }
  32866. });
  32867. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js
  32868. var require_debug = __commonJS({
  32869. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js"(exports2, module2) {
  32870. "use strict";
  32871. var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
  32872. };
  32873. module2.exports = debug;
  32874. }
  32875. });
  32876. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js
  32877. var require_re = __commonJS({
  32878. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js"(exports2, module2) {
  32879. "use strict";
  32880. var {
  32881. MAX_SAFE_COMPONENT_LENGTH,
  32882. MAX_SAFE_BUILD_LENGTH,
  32883. MAX_LENGTH
  32884. } = require_constants();
  32885. var debug = require_debug();
  32886. exports2 = module2.exports = {};
  32887. var re = exports2.re = [];
  32888. var safeRe = exports2.safeRe = [];
  32889. var src = exports2.src = [];
  32890. var safeSrc = exports2.safeSrc = [];
  32891. var t4 = exports2.t = {};
  32892. var R = 0;
  32893. var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
  32894. var safeRegexReplacements = [
  32895. ["\\s", 1],
  32896. ["\\d", MAX_LENGTH],
  32897. [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
  32898. ];
  32899. var makeSafeRegex = (value) => {
  32900. for (const [token, max] of safeRegexReplacements) {
  32901. value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
  32902. }
  32903. return value;
  32904. };
  32905. var createToken = (name, value, isGlobal) => {
  32906. const safe = makeSafeRegex(value);
  32907. const index6 = R++;
  32908. debug(name, index6, value);
  32909. t4[name] = index6;
  32910. src[index6] = value;
  32911. safeSrc[index6] = safe;
  32912. re[index6] = new RegExp(value, isGlobal ? "g" : void 0);
  32913. safeRe[index6] = new RegExp(safe, isGlobal ? "g" : void 0);
  32914. };
  32915. createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
  32916. createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
  32917. createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
  32918. createToken("MAINVERSION", `(${src[t4.NUMERICIDENTIFIER]})\\.(${src[t4.NUMERICIDENTIFIER]})\\.(${src[t4.NUMERICIDENTIFIER]})`);
  32919. createToken("MAINVERSIONLOOSE", `(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t4.NUMERICIDENTIFIERLOOSE]})`);
  32920. createToken("PRERELEASEIDENTIFIER", `(?:${src[t4.NONNUMERICIDENTIFIER]}|${src[t4.NUMERICIDENTIFIER]})`);
  32921. createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t4.NONNUMERICIDENTIFIER]}|${src[t4.NUMERICIDENTIFIERLOOSE]})`);
  32922. createToken("PRERELEASE", `(?:-(${src[t4.PRERELEASEIDENTIFIER]}(?:\\.${src[t4.PRERELEASEIDENTIFIER]})*))`);
  32923. createToken("PRERELEASELOOSE", `(?:-?(${src[t4.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t4.PRERELEASEIDENTIFIERLOOSE]})*))`);
  32924. createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
  32925. createToken("BUILD", `(?:\\+(${src[t4.BUILDIDENTIFIER]}(?:\\.${src[t4.BUILDIDENTIFIER]})*))`);
  32926. createToken("FULLPLAIN", `v?${src[t4.MAINVERSION]}${src[t4.PRERELEASE]}?${src[t4.BUILD]}?`);
  32927. createToken("FULL", `^${src[t4.FULLPLAIN]}$`);
  32928. createToken("LOOSEPLAIN", `[v=\\s]*${src[t4.MAINVERSIONLOOSE]}${src[t4.PRERELEASELOOSE]}?${src[t4.BUILD]}?`);
  32929. createToken("LOOSE", `^${src[t4.LOOSEPLAIN]}$`);
  32930. createToken("GTLT", "((?:<|>)?=?)");
  32931. createToken("XRANGEIDENTIFIERLOOSE", `${src[t4.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
  32932. createToken("XRANGEIDENTIFIER", `${src[t4.NUMERICIDENTIFIER]}|x|X|\\*`);
  32933. createToken("XRANGEPLAIN", `[v=\\s]*(${src[t4.XRANGEIDENTIFIER]})(?:\\.(${src[t4.XRANGEIDENTIFIER]})(?:\\.(${src[t4.XRANGEIDENTIFIER]})(?:${src[t4.PRERELEASE]})?${src[t4.BUILD]}?)?)?`);
  32934. createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:${src[t4.PRERELEASELOOSE]})?${src[t4.BUILD]}?)?)?`);
  32935. createToken("XRANGE", `^${src[t4.GTLT]}\\s*${src[t4.XRANGEPLAIN]}$`);
  32936. createToken("XRANGELOOSE", `^${src[t4.GTLT]}\\s*${src[t4.XRANGEPLAINLOOSE]}$`);
  32937. createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
  32938. createToken("COERCE", `${src[t4.COERCEPLAIN]}(?:$|[^\\d])`);
  32939. createToken("COERCEFULL", src[t4.COERCEPLAIN] + `(?:${src[t4.PRERELEASE]})?(?:${src[t4.BUILD]})?(?:$|[^\\d])`);
  32940. createToken("COERCERTL", src[t4.COERCE], true);
  32941. createToken("COERCERTLFULL", src[t4.COERCEFULL], true);
  32942. createToken("LONETILDE", "(?:~>?)");
  32943. createToken("TILDETRIM", `(\\s*)${src[t4.LONETILDE]}\\s+`, true);
  32944. exports2.tildeTrimReplace = "$1~";
  32945. createToken("TILDE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAIN]}$`);
  32946. createToken("TILDELOOSE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAINLOOSE]}$`);
  32947. createToken("LONECARET", "(?:\\^)");
  32948. createToken("CARETTRIM", `(\\s*)${src[t4.LONECARET]}\\s+`, true);
  32949. exports2.caretTrimReplace = "$1^";
  32950. createToken("CARET", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAIN]}$`);
  32951. createToken("CARETLOOSE", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAINLOOSE]}$`);
  32952. createToken("COMPARATORLOOSE", `^${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]})$|^$`);
  32953. createToken("COMPARATOR", `^${src[t4.GTLT]}\\s*(${src[t4.FULLPLAIN]})$|^$`);
  32954. createToken("COMPARATORTRIM", `(\\s*)${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]}|${src[t4.XRANGEPLAIN]})`, true);
  32955. exports2.comparatorTrimReplace = "$1$2$3";
  32956. createToken("HYPHENRANGE", `^\\s*(${src[t4.XRANGEPLAIN]})\\s+-\\s+(${src[t4.XRANGEPLAIN]})\\s*$`);
  32957. createToken("HYPHENRANGELOOSE", `^\\s*(${src[t4.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t4.XRANGEPLAINLOOSE]})\\s*$`);
  32958. createToken("STAR", "(<|>)?=?\\s*\\*");
  32959. createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
  32960. createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
  32961. }
  32962. });
  32963. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js
  32964. var require_parse_options = __commonJS({
  32965. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js"(exports2, module2) {
  32966. "use strict";
  32967. var looseOption = Object.freeze({ loose: true });
  32968. var emptyOpts = Object.freeze({});
  32969. var parseOptions2 = (options) => {
  32970. if (!options) {
  32971. return emptyOpts;
  32972. }
  32973. if (typeof options !== "object") {
  32974. return looseOption;
  32975. }
  32976. return options;
  32977. };
  32978. module2.exports = parseOptions2;
  32979. }
  32980. });
  32981. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js
  32982. var require_identifiers = __commonJS({
  32983. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js"(exports2, module2) {
  32984. "use strict";
  32985. var numeric = /^[0-9]+$/;
  32986. var compareIdentifiers = (a3, b3) => {
  32987. const anum = numeric.test(a3);
  32988. const bnum = numeric.test(b3);
  32989. if (anum && bnum) {
  32990. a3 = +a3;
  32991. b3 = +b3;
  32992. }
  32993. return a3 === b3 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a3 < b3 ? -1 : 1;
  32994. };
  32995. var rcompareIdentifiers = (a3, b3) => compareIdentifiers(b3, a3);
  32996. module2.exports = {
  32997. compareIdentifiers,
  32998. rcompareIdentifiers
  32999. };
  33000. }
  33001. });
  33002. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js
  33003. var require_semver = __commonJS({
  33004. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js"(exports2, module2) {
  33005. "use strict";
  33006. var debug = require_debug();
  33007. var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
  33008. var { safeRe: re, t: t4 } = require_re();
  33009. var parseOptions2 = require_parse_options();
  33010. var { compareIdentifiers } = require_identifiers();
  33011. var SemVer = class _SemVer {
  33012. constructor(version3, options) {
  33013. options = parseOptions2(options);
  33014. if (version3 instanceof _SemVer) {
  33015. if (version3.loose === !!options.loose && version3.includePrerelease === !!options.includePrerelease) {
  33016. return version3;
  33017. } else {
  33018. version3 = version3.version;
  33019. }
  33020. } else if (typeof version3 !== "string") {
  33021. throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version3}".`);
  33022. }
  33023. if (version3.length > MAX_LENGTH) {
  33024. throw new TypeError(
  33025. `version is longer than ${MAX_LENGTH} characters`
  33026. );
  33027. }
  33028. debug("SemVer", version3, options);
  33029. this.options = options;
  33030. this.loose = !!options.loose;
  33031. this.includePrerelease = !!options.includePrerelease;
  33032. const m4 = version3.trim().match(options.loose ? re[t4.LOOSE] : re[t4.FULL]);
  33033. if (!m4) {
  33034. throw new TypeError(`Invalid Version: ${version3}`);
  33035. }
  33036. this.raw = version3;
  33037. this.major = +m4[1];
  33038. this.minor = +m4[2];
  33039. this.patch = +m4[3];
  33040. if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
  33041. throw new TypeError("Invalid major version");
  33042. }
  33043. if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
  33044. throw new TypeError("Invalid minor version");
  33045. }
  33046. if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
  33047. throw new TypeError("Invalid patch version");
  33048. }
  33049. if (!m4[4]) {
  33050. this.prerelease = [];
  33051. } else {
  33052. this.prerelease = m4[4].split(".").map((id) => {
  33053. if (/^[0-9]+$/.test(id)) {
  33054. const num = +id;
  33055. if (num >= 0 && num < MAX_SAFE_INTEGER) {
  33056. return num;
  33057. }
  33058. }
  33059. return id;
  33060. });
  33061. }
  33062. this.build = m4[5] ? m4[5].split(".") : [];
  33063. this.format();
  33064. }
  33065. format() {
  33066. this.version = `${this.major}.${this.minor}.${this.patch}`;
  33067. if (this.prerelease.length) {
  33068. this.version += `-${this.prerelease.join(".")}`;
  33069. }
  33070. return this.version;
  33071. }
  33072. toString() {
  33073. return this.version;
  33074. }
  33075. compare(other) {
  33076. debug("SemVer.compare", this.version, this.options, other);
  33077. if (!(other instanceof _SemVer)) {
  33078. if (typeof other === "string" && other === this.version) {
  33079. return 0;
  33080. }
  33081. other = new _SemVer(other, this.options);
  33082. }
  33083. if (other.version === this.version) {
  33084. return 0;
  33085. }
  33086. return this.compareMain(other) || this.comparePre(other);
  33087. }
  33088. compareMain(other) {
  33089. if (!(other instanceof _SemVer)) {
  33090. other = new _SemVer(other, this.options);
  33091. }
  33092. return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
  33093. }
  33094. comparePre(other) {
  33095. if (!(other instanceof _SemVer)) {
  33096. other = new _SemVer(other, this.options);
  33097. }
  33098. if (this.prerelease.length && !other.prerelease.length) {
  33099. return -1;
  33100. } else if (!this.prerelease.length && other.prerelease.length) {
  33101. return 1;
  33102. } else if (!this.prerelease.length && !other.prerelease.length) {
  33103. return 0;
  33104. }
  33105. let i4 = 0;
  33106. do {
  33107. const a3 = this.prerelease[i4];
  33108. const b3 = other.prerelease[i4];
  33109. debug("prerelease compare", i4, a3, b3);
  33110. if (a3 === void 0 && b3 === void 0) {
  33111. return 0;
  33112. } else if (b3 === void 0) {
  33113. return 1;
  33114. } else if (a3 === void 0) {
  33115. return -1;
  33116. } else if (a3 === b3) {
  33117. continue;
  33118. } else {
  33119. return compareIdentifiers(a3, b3);
  33120. }
  33121. } while (++i4);
  33122. }
  33123. compareBuild(other) {
  33124. if (!(other instanceof _SemVer)) {
  33125. other = new _SemVer(other, this.options);
  33126. }
  33127. let i4 = 0;
  33128. do {
  33129. const a3 = this.build[i4];
  33130. const b3 = other.build[i4];
  33131. debug("build compare", i4, a3, b3);
  33132. if (a3 === void 0 && b3 === void 0) {
  33133. return 0;
  33134. } else if (b3 === void 0) {
  33135. return 1;
  33136. } else if (a3 === void 0) {
  33137. return -1;
  33138. } else if (a3 === b3) {
  33139. continue;
  33140. } else {
  33141. return compareIdentifiers(a3, b3);
  33142. }
  33143. } while (++i4);
  33144. }
  33145. // preminor will bump the version up to the next minor release, and immediately
  33146. // down to pre-release. premajor and prepatch work the same way.
  33147. inc(release, identifier, identifierBase) {
  33148. if (release.startsWith("pre")) {
  33149. if (!identifier && identifierBase === false) {
  33150. throw new Error("invalid increment argument: identifier is empty");
  33151. }
  33152. if (identifier) {
  33153. const match2 = `-${identifier}`.match(this.options.loose ? re[t4.PRERELEASELOOSE] : re[t4.PRERELEASE]);
  33154. if (!match2 || match2[1] !== identifier) {
  33155. throw new Error(`invalid identifier: ${identifier}`);
  33156. }
  33157. }
  33158. }
  33159. switch (release) {
  33160. case "premajor":
  33161. this.prerelease.length = 0;
  33162. this.patch = 0;
  33163. this.minor = 0;
  33164. this.major++;
  33165. this.inc("pre", identifier, identifierBase);
  33166. break;
  33167. case "preminor":
  33168. this.prerelease.length = 0;
  33169. this.patch = 0;
  33170. this.minor++;
  33171. this.inc("pre", identifier, identifierBase);
  33172. break;
  33173. case "prepatch":
  33174. this.prerelease.length = 0;
  33175. this.inc("patch", identifier, identifierBase);
  33176. this.inc("pre", identifier, identifierBase);
  33177. break;
  33178. // If the input is a non-prerelease version, this acts the same as
  33179. // prepatch.
  33180. case "prerelease":
  33181. if (this.prerelease.length === 0) {
  33182. this.inc("patch", identifier, identifierBase);
  33183. }
  33184. this.inc("pre", identifier, identifierBase);
  33185. break;
  33186. case "release":
  33187. if (this.prerelease.length === 0) {
  33188. throw new Error(`version ${this.raw} is not a prerelease`);
  33189. }
  33190. this.prerelease.length = 0;
  33191. break;
  33192. case "major":
  33193. if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
  33194. this.major++;
  33195. }
  33196. this.minor = 0;
  33197. this.patch = 0;
  33198. this.prerelease = [];
  33199. break;
  33200. case "minor":
  33201. if (this.patch !== 0 || this.prerelease.length === 0) {
  33202. this.minor++;
  33203. }
  33204. this.patch = 0;
  33205. this.prerelease = [];
  33206. break;
  33207. case "patch":
  33208. if (this.prerelease.length === 0) {
  33209. this.patch++;
  33210. }
  33211. this.prerelease = [];
  33212. break;
  33213. // This probably shouldn't be used publicly.
  33214. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
  33215. case "pre": {
  33216. const base = Number(identifierBase) ? 1 : 0;
  33217. if (this.prerelease.length === 0) {
  33218. this.prerelease = [base];
  33219. } else {
  33220. let i4 = this.prerelease.length;
  33221. while (--i4 >= 0) {
  33222. if (typeof this.prerelease[i4] === "number") {
  33223. this.prerelease[i4]++;
  33224. i4 = -2;
  33225. }
  33226. }
  33227. if (i4 === -1) {
  33228. if (identifier === this.prerelease.join(".") && identifierBase === false) {
  33229. throw new Error("invalid increment argument: identifier already exists");
  33230. }
  33231. this.prerelease.push(base);
  33232. }
  33233. }
  33234. if (identifier) {
  33235. let prerelease = [identifier, base];
  33236. if (identifierBase === false) {
  33237. prerelease = [identifier];
  33238. }
  33239. if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
  33240. if (isNaN(this.prerelease[1])) {
  33241. this.prerelease = prerelease;
  33242. }
  33243. } else {
  33244. this.prerelease = prerelease;
  33245. }
  33246. }
  33247. break;
  33248. }
  33249. default:
  33250. throw new Error(`invalid increment argument: ${release}`);
  33251. }
  33252. this.raw = this.format();
  33253. if (this.build.length) {
  33254. this.raw += `+${this.build.join(".")}`;
  33255. }
  33256. return this;
  33257. }
  33258. };
  33259. module2.exports = SemVer;
  33260. }
  33261. });
  33262. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js
  33263. var require_parse2 = __commonJS({
  33264. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js"(exports2, module2) {
  33265. "use strict";
  33266. var SemVer = require_semver();
  33267. var parse4 = (version3, options, throwErrors = false) => {
  33268. if (version3 instanceof SemVer) {
  33269. return version3;
  33270. }
  33271. try {
  33272. return new SemVer(version3, options);
  33273. } catch (er) {
  33274. if (!throwErrors) {
  33275. return null;
  33276. }
  33277. throw er;
  33278. }
  33279. };
  33280. module2.exports = parse4;
  33281. }
  33282. });
  33283. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js
  33284. var require_valid = __commonJS({
  33285. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js"(exports2, module2) {
  33286. "use strict";
  33287. var parse4 = require_parse2();
  33288. var valid = (version3, options) => {
  33289. const v6 = parse4(version3, options);
  33290. return v6 ? v6.version : null;
  33291. };
  33292. module2.exports = valid;
  33293. }
  33294. });
  33295. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js
  33296. var require_clean = __commonJS({
  33297. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js"(exports2, module2) {
  33298. "use strict";
  33299. var parse4 = require_parse2();
  33300. var clean = (version3, options) => {
  33301. const s4 = parse4(version3.trim().replace(/^[=v]+/, ""), options);
  33302. return s4 ? s4.version : null;
  33303. };
  33304. module2.exports = clean;
  33305. }
  33306. });
  33307. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js
  33308. var require_inc = __commonJS({
  33309. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js"(exports2, module2) {
  33310. "use strict";
  33311. var SemVer = require_semver();
  33312. var inc = (version3, release, options, identifier, identifierBase) => {
  33313. if (typeof options === "string") {
  33314. identifierBase = identifier;
  33315. identifier = options;
  33316. options = void 0;
  33317. }
  33318. try {
  33319. return new SemVer(
  33320. version3 instanceof SemVer ? version3.version : version3,
  33321. options
  33322. ).inc(release, identifier, identifierBase).version;
  33323. } catch (er) {
  33324. return null;
  33325. }
  33326. };
  33327. module2.exports = inc;
  33328. }
  33329. });
  33330. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js
  33331. var require_diff = __commonJS({
  33332. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js"(exports2, module2) {
  33333. "use strict";
  33334. var parse4 = require_parse2();
  33335. var diff2 = (version1, version22) => {
  33336. const v12 = parse4(version1, null, true);
  33337. const v22 = parse4(version22, null, true);
  33338. const comparison = v12.compare(v22);
  33339. if (comparison === 0) {
  33340. return null;
  33341. }
  33342. const v1Higher = comparison > 0;
  33343. const highVersion = v1Higher ? v12 : v22;
  33344. const lowVersion = v1Higher ? v22 : v12;
  33345. const highHasPre = !!highVersion.prerelease.length;
  33346. const lowHasPre = !!lowVersion.prerelease.length;
  33347. if (lowHasPre && !highHasPre) {
  33348. if (!lowVersion.patch && !lowVersion.minor) {
  33349. return "major";
  33350. }
  33351. if (lowVersion.compareMain(highVersion) === 0) {
  33352. if (lowVersion.minor && !lowVersion.patch) {
  33353. return "minor";
  33354. }
  33355. return "patch";
  33356. }
  33357. }
  33358. const prefix2 = highHasPre ? "pre" : "";
  33359. if (v12.major !== v22.major) {
  33360. return prefix2 + "major";
  33361. }
  33362. if (v12.minor !== v22.minor) {
  33363. return prefix2 + "minor";
  33364. }
  33365. if (v12.patch !== v22.patch) {
  33366. return prefix2 + "patch";
  33367. }
  33368. return "prerelease";
  33369. };
  33370. module2.exports = diff2;
  33371. }
  33372. });
  33373. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js
  33374. var require_major = __commonJS({
  33375. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js"(exports2, module2) {
  33376. "use strict";
  33377. var SemVer = require_semver();
  33378. var major = (a3, loose) => new SemVer(a3, loose).major;
  33379. module2.exports = major;
  33380. }
  33381. });
  33382. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js
  33383. var require_minor = __commonJS({
  33384. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js"(exports2, module2) {
  33385. "use strict";
  33386. var SemVer = require_semver();
  33387. var minor = (a3, loose) => new SemVer(a3, loose).minor;
  33388. module2.exports = minor;
  33389. }
  33390. });
  33391. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js
  33392. var require_patch = __commonJS({
  33393. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js"(exports2, module2) {
  33394. "use strict";
  33395. var SemVer = require_semver();
  33396. var patch = (a3, loose) => new SemVer(a3, loose).patch;
  33397. module2.exports = patch;
  33398. }
  33399. });
  33400. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js
  33401. var require_prerelease = __commonJS({
  33402. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js"(exports2, module2) {
  33403. "use strict";
  33404. var parse4 = require_parse2();
  33405. var prerelease = (version3, options) => {
  33406. const parsed = parse4(version3, options);
  33407. return parsed && parsed.prerelease.length ? parsed.prerelease : null;
  33408. };
  33409. module2.exports = prerelease;
  33410. }
  33411. });
  33412. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js
  33413. var require_compare = __commonJS({
  33414. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js"(exports2, module2) {
  33415. "use strict";
  33416. var SemVer = require_semver();
  33417. var compare = (a3, b3, loose) => new SemVer(a3, loose).compare(new SemVer(b3, loose));
  33418. module2.exports = compare;
  33419. }
  33420. });
  33421. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js
  33422. var require_rcompare = __commonJS({
  33423. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js"(exports2, module2) {
  33424. "use strict";
  33425. var compare = require_compare();
  33426. var rcompare = (a3, b3, loose) => compare(b3, a3, loose);
  33427. module2.exports = rcompare;
  33428. }
  33429. });
  33430. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js
  33431. var require_compare_loose = __commonJS({
  33432. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js"(exports2, module2) {
  33433. "use strict";
  33434. var compare = require_compare();
  33435. var compareLoose = (a3, b3) => compare(a3, b3, true);
  33436. module2.exports = compareLoose;
  33437. }
  33438. });
  33439. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js
  33440. var require_compare_build = __commonJS({
  33441. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js"(exports2, module2) {
  33442. "use strict";
  33443. var SemVer = require_semver();
  33444. var compareBuild = (a3, b3, loose) => {
  33445. const versionA = new SemVer(a3, loose);
  33446. const versionB = new SemVer(b3, loose);
  33447. return versionA.compare(versionB) || versionA.compareBuild(versionB);
  33448. };
  33449. module2.exports = compareBuild;
  33450. }
  33451. });
  33452. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js
  33453. var require_sort = __commonJS({
  33454. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js"(exports2, module2) {
  33455. "use strict";
  33456. var compareBuild = require_compare_build();
  33457. var sort = (list, loose) => list.sort((a3, b3) => compareBuild(a3, b3, loose));
  33458. module2.exports = sort;
  33459. }
  33460. });
  33461. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js
  33462. var require_rsort = __commonJS({
  33463. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js"(exports2, module2) {
  33464. "use strict";
  33465. var compareBuild = require_compare_build();
  33466. var rsort = (list, loose) => list.sort((a3, b3) => compareBuild(b3, a3, loose));
  33467. module2.exports = rsort;
  33468. }
  33469. });
  33470. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js
  33471. var require_gt = __commonJS({
  33472. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js"(exports2, module2) {
  33473. "use strict";
  33474. var compare = require_compare();
  33475. var gt = (a3, b3, loose) => compare(a3, b3, loose) > 0;
  33476. module2.exports = gt;
  33477. }
  33478. });
  33479. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js
  33480. var require_lt = __commonJS({
  33481. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js"(exports2, module2) {
  33482. "use strict";
  33483. var compare = require_compare();
  33484. var lt = (a3, b3, loose) => compare(a3, b3, loose) < 0;
  33485. module2.exports = lt;
  33486. }
  33487. });
  33488. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js
  33489. var require_eq = __commonJS({
  33490. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js"(exports2, module2) {
  33491. "use strict";
  33492. var compare = require_compare();
  33493. var eq = (a3, b3, loose) => compare(a3, b3, loose) === 0;
  33494. module2.exports = eq;
  33495. }
  33496. });
  33497. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js
  33498. var require_neq = __commonJS({
  33499. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js"(exports2, module2) {
  33500. "use strict";
  33501. var compare = require_compare();
  33502. var neq = (a3, b3, loose) => compare(a3, b3, loose) !== 0;
  33503. module2.exports = neq;
  33504. }
  33505. });
  33506. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js
  33507. var require_gte = __commonJS({
  33508. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js"(exports2, module2) {
  33509. "use strict";
  33510. var compare = require_compare();
  33511. var gte = (a3, b3, loose) => compare(a3, b3, loose) >= 0;
  33512. module2.exports = gte;
  33513. }
  33514. });
  33515. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js
  33516. var require_lte = __commonJS({
  33517. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js"(exports2, module2) {
  33518. "use strict";
  33519. var compare = require_compare();
  33520. var lte = (a3, b3, loose) => compare(a3, b3, loose) <= 0;
  33521. module2.exports = lte;
  33522. }
  33523. });
  33524. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js
  33525. var require_cmp = __commonJS({
  33526. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js"(exports2, module2) {
  33527. "use strict";
  33528. var eq = require_eq();
  33529. var neq = require_neq();
  33530. var gt = require_gt();
  33531. var gte = require_gte();
  33532. var lt = require_lt();
  33533. var lte = require_lte();
  33534. var cmp = (a3, op, b3, loose) => {
  33535. switch (op) {
  33536. case "===":
  33537. if (typeof a3 === "object") {
  33538. a3 = a3.version;
  33539. }
  33540. if (typeof b3 === "object") {
  33541. b3 = b3.version;
  33542. }
  33543. return a3 === b3;
  33544. case "!==":
  33545. if (typeof a3 === "object") {
  33546. a3 = a3.version;
  33547. }
  33548. if (typeof b3 === "object") {
  33549. b3 = b3.version;
  33550. }
  33551. return a3 !== b3;
  33552. case "":
  33553. case "=":
  33554. case "==":
  33555. return eq(a3, b3, loose);
  33556. case "!=":
  33557. return neq(a3, b3, loose);
  33558. case ">":
  33559. return gt(a3, b3, loose);
  33560. case ">=":
  33561. return gte(a3, b3, loose);
  33562. case "<":
  33563. return lt(a3, b3, loose);
  33564. case "<=":
  33565. return lte(a3, b3, loose);
  33566. default:
  33567. throw new TypeError(`Invalid operator: ${op}`);
  33568. }
  33569. };
  33570. module2.exports = cmp;
  33571. }
  33572. });
  33573. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js
  33574. var require_coerce = __commonJS({
  33575. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js"(exports2, module2) {
  33576. "use strict";
  33577. var SemVer = require_semver();
  33578. var parse4 = require_parse2();
  33579. var { safeRe: re, t: t4 } = require_re();
  33580. var coerce2 = (version3, options) => {
  33581. if (version3 instanceof SemVer) {
  33582. return version3;
  33583. }
  33584. if (typeof version3 === "number") {
  33585. version3 = String(version3);
  33586. }
  33587. if (typeof version3 !== "string") {
  33588. return null;
  33589. }
  33590. options = options || {};
  33591. let match2 = null;
  33592. if (!options.rtl) {
  33593. match2 = version3.match(options.includePrerelease ? re[t4.COERCEFULL] : re[t4.COERCE]);
  33594. } else {
  33595. const coerceRtlRegex = options.includePrerelease ? re[t4.COERCERTLFULL] : re[t4.COERCERTL];
  33596. let next;
  33597. while ((next = coerceRtlRegex.exec(version3)) && (!match2 || match2.index + match2[0].length !== version3.length)) {
  33598. if (!match2 || next.index + next[0].length !== match2.index + match2[0].length) {
  33599. match2 = next;
  33600. }
  33601. coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
  33602. }
  33603. coerceRtlRegex.lastIndex = -1;
  33604. }
  33605. if (match2 === null) {
  33606. return null;
  33607. }
  33608. const major = match2[2];
  33609. const minor = match2[3] || "0";
  33610. const patch = match2[4] || "0";
  33611. const prerelease = options.includePrerelease && match2[5] ? `-${match2[5]}` : "";
  33612. const build = options.includePrerelease && match2[6] ? `+${match2[6]}` : "";
  33613. return parse4(`${major}.${minor}.${patch}${prerelease}${build}`, options);
  33614. };
  33615. module2.exports = coerce2;
  33616. }
  33617. });
  33618. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js
  33619. var require_lrucache = __commonJS({
  33620. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js"(exports2, module2) {
  33621. "use strict";
  33622. var LRUCache = class {
  33623. constructor() {
  33624. this.max = 1e3;
  33625. this.map = /* @__PURE__ */ new Map();
  33626. }
  33627. get(key) {
  33628. const value = this.map.get(key);
  33629. if (value === void 0) {
  33630. return void 0;
  33631. } else {
  33632. this.map.delete(key);
  33633. this.map.set(key, value);
  33634. return value;
  33635. }
  33636. }
  33637. delete(key) {
  33638. return this.map.delete(key);
  33639. }
  33640. set(key, value) {
  33641. const deleted = this.delete(key);
  33642. if (!deleted && value !== void 0) {
  33643. if (this.map.size >= this.max) {
  33644. const firstKey = this.map.keys().next().value;
  33645. this.delete(firstKey);
  33646. }
  33647. this.map.set(key, value);
  33648. }
  33649. return this;
  33650. }
  33651. };
  33652. module2.exports = LRUCache;
  33653. }
  33654. });
  33655. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js
  33656. var require_range = __commonJS({
  33657. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js"(exports2, module2) {
  33658. "use strict";
  33659. var SPACE_CHARACTERS = /\s+/g;
  33660. var Range = class _Range {
  33661. constructor(range, options) {
  33662. options = parseOptions2(options);
  33663. if (range instanceof _Range) {
  33664. if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
  33665. return range;
  33666. } else {
  33667. return new _Range(range.raw, options);
  33668. }
  33669. }
  33670. if (range instanceof Comparator) {
  33671. this.raw = range.value;
  33672. this.set = [[range]];
  33673. this.formatted = void 0;
  33674. return this;
  33675. }
  33676. this.options = options;
  33677. this.loose = !!options.loose;
  33678. this.includePrerelease = !!options.includePrerelease;
  33679. this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
  33680. this.set = this.raw.split("||").map((r4) => this.parseRange(r4.trim())).filter((c3) => c3.length);
  33681. if (!this.set.length) {
  33682. throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
  33683. }
  33684. if (this.set.length > 1) {
  33685. const first = this.set[0];
  33686. this.set = this.set.filter((c3) => !isNullSet(c3[0]));
  33687. if (this.set.length === 0) {
  33688. this.set = [first];
  33689. } else if (this.set.length > 1) {
  33690. for (const c3 of this.set) {
  33691. if (c3.length === 1 && isAny(c3[0])) {
  33692. this.set = [c3];
  33693. break;
  33694. }
  33695. }
  33696. }
  33697. }
  33698. this.formatted = void 0;
  33699. }
  33700. get range() {
  33701. if (this.formatted === void 0) {
  33702. this.formatted = "";
  33703. for (let i4 = 0; i4 < this.set.length; i4++) {
  33704. if (i4 > 0) {
  33705. this.formatted += "||";
  33706. }
  33707. const comps = this.set[i4];
  33708. for (let k3 = 0; k3 < comps.length; k3++) {
  33709. if (k3 > 0) {
  33710. this.formatted += " ";
  33711. }
  33712. this.formatted += comps[k3].toString().trim();
  33713. }
  33714. }
  33715. }
  33716. return this.formatted;
  33717. }
  33718. format() {
  33719. return this.range;
  33720. }
  33721. toString() {
  33722. return this.range;
  33723. }
  33724. parseRange(range) {
  33725. const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
  33726. const memoKey = memoOpts + ":" + range;
  33727. const cached = cache3.get(memoKey);
  33728. if (cached) {
  33729. return cached;
  33730. }
  33731. const loose = this.options.loose;
  33732. const hr = loose ? re[t4.HYPHENRANGELOOSE] : re[t4.HYPHENRANGE];
  33733. range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
  33734. debug("hyphen replace", range);
  33735. range = range.replace(re[t4.COMPARATORTRIM], comparatorTrimReplace);
  33736. debug("comparator trim", range);
  33737. range = range.replace(re[t4.TILDETRIM], tildeTrimReplace);
  33738. debug("tilde trim", range);
  33739. range = range.replace(re[t4.CARETTRIM], caretTrimReplace);
  33740. debug("caret trim", range);
  33741. let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
  33742. if (loose) {
  33743. rangeList = rangeList.filter((comp) => {
  33744. debug("loose invalid filter", comp, this.options);
  33745. return !!comp.match(re[t4.COMPARATORLOOSE]);
  33746. });
  33747. }
  33748. debug("range list", rangeList);
  33749. const rangeMap = /* @__PURE__ */ new Map();
  33750. const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
  33751. for (const comp of comparators) {
  33752. if (isNullSet(comp)) {
  33753. return [comp];
  33754. }
  33755. rangeMap.set(comp.value, comp);
  33756. }
  33757. if (rangeMap.size > 1 && rangeMap.has("")) {
  33758. rangeMap.delete("");
  33759. }
  33760. const result = [...rangeMap.values()];
  33761. cache3.set(memoKey, result);
  33762. return result;
  33763. }
  33764. intersects(range, options) {
  33765. if (!(range instanceof _Range)) {
  33766. throw new TypeError("a Range is required");
  33767. }
  33768. return this.set.some((thisComparators) => {
  33769. return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
  33770. return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
  33771. return rangeComparators.every((rangeComparator) => {
  33772. return thisComparator.intersects(rangeComparator, options);
  33773. });
  33774. });
  33775. });
  33776. });
  33777. }
  33778. // if ANY of the sets match ALL of its comparators, then pass
  33779. test(version3) {
  33780. if (!version3) {
  33781. return false;
  33782. }
  33783. if (typeof version3 === "string") {
  33784. try {
  33785. version3 = new SemVer(version3, this.options);
  33786. } catch (er) {
  33787. return false;
  33788. }
  33789. }
  33790. for (let i4 = 0; i4 < this.set.length; i4++) {
  33791. if (testSet(this.set[i4], version3, this.options)) {
  33792. return true;
  33793. }
  33794. }
  33795. return false;
  33796. }
  33797. };
  33798. module2.exports = Range;
  33799. var LRU = require_lrucache();
  33800. var cache3 = new LRU();
  33801. var parseOptions2 = require_parse_options();
  33802. var Comparator = require_comparator();
  33803. var debug = require_debug();
  33804. var SemVer = require_semver();
  33805. var {
  33806. safeRe: re,
  33807. t: t4,
  33808. comparatorTrimReplace,
  33809. tildeTrimReplace,
  33810. caretTrimReplace
  33811. } = require_re();
  33812. var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();
  33813. var isNullSet = (c3) => c3.value === "<0.0.0-0";
  33814. var isAny = (c3) => c3.value === "";
  33815. var isSatisfiable = (comparators, options) => {
  33816. let result = true;
  33817. const remainingComparators = comparators.slice();
  33818. let testComparator = remainingComparators.pop();
  33819. while (result && remainingComparators.length) {
  33820. result = remainingComparators.every((otherComparator) => {
  33821. return testComparator.intersects(otherComparator, options);
  33822. });
  33823. testComparator = remainingComparators.pop();
  33824. }
  33825. return result;
  33826. };
  33827. var parseComparator = (comp, options) => {
  33828. debug("comp", comp, options);
  33829. comp = replaceCarets(comp, options);
  33830. debug("caret", comp);
  33831. comp = replaceTildes(comp, options);
  33832. debug("tildes", comp);
  33833. comp = replaceXRanges(comp, options);
  33834. debug("xrange", comp);
  33835. comp = replaceStars(comp, options);
  33836. debug("stars", comp);
  33837. return comp;
  33838. };
  33839. var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
  33840. var replaceTildes = (comp, options) => {
  33841. return comp.trim().split(/\s+/).map((c3) => replaceTilde(c3, options)).join(" ");
  33842. };
  33843. var replaceTilde = (comp, options) => {
  33844. const r4 = options.loose ? re[t4.TILDELOOSE] : re[t4.TILDE];
  33845. return comp.replace(r4, (_3, M, m4, p3, pr) => {
  33846. debug("tilde", comp, _3, M, m4, p3, pr);
  33847. let ret;
  33848. if (isX(M)) {
  33849. ret = "";
  33850. } else if (isX(m4)) {
  33851. ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
  33852. } else if (isX(p3)) {
  33853. ret = `>=${M}.${m4}.0 <${M}.${+m4 + 1}.0-0`;
  33854. } else if (pr) {
  33855. debug("replaceTilde pr", pr);
  33856. ret = `>=${M}.${m4}.${p3}-${pr} <${M}.${+m4 + 1}.0-0`;
  33857. } else {
  33858. ret = `>=${M}.${m4}.${p3} <${M}.${+m4 + 1}.0-0`;
  33859. }
  33860. debug("tilde return", ret);
  33861. return ret;
  33862. });
  33863. };
  33864. var replaceCarets = (comp, options) => {
  33865. return comp.trim().split(/\s+/).map((c3) => replaceCaret(c3, options)).join(" ");
  33866. };
  33867. var replaceCaret = (comp, options) => {
  33868. debug("caret", comp, options);
  33869. const r4 = options.loose ? re[t4.CARETLOOSE] : re[t4.CARET];
  33870. const z2 = options.includePrerelease ? "-0" : "";
  33871. return comp.replace(r4, (_3, M, m4, p3, pr) => {
  33872. debug("caret", comp, _3, M, m4, p3, pr);
  33873. let ret;
  33874. if (isX(M)) {
  33875. ret = "";
  33876. } else if (isX(m4)) {
  33877. ret = `>=${M}.0.0${z2} <${+M + 1}.0.0-0`;
  33878. } else if (isX(p3)) {
  33879. if (M === "0") {
  33880. ret = `>=${M}.${m4}.0${z2} <${M}.${+m4 + 1}.0-0`;
  33881. } else {
  33882. ret = `>=${M}.${m4}.0${z2} <${+M + 1}.0.0-0`;
  33883. }
  33884. } else if (pr) {
  33885. debug("replaceCaret pr", pr);
  33886. if (M === "0") {
  33887. if (m4 === "0") {
  33888. ret = `>=${M}.${m4}.${p3}-${pr} <${M}.${m4}.${+p3 + 1}-0`;
  33889. } else {
  33890. ret = `>=${M}.${m4}.${p3}-${pr} <${M}.${+m4 + 1}.0-0`;
  33891. }
  33892. } else {
  33893. ret = `>=${M}.${m4}.${p3}-${pr} <${+M + 1}.0.0-0`;
  33894. }
  33895. } else {
  33896. debug("no pr");
  33897. if (M === "0") {
  33898. if (m4 === "0") {
  33899. ret = `>=${M}.${m4}.${p3}${z2} <${M}.${m4}.${+p3 + 1}-0`;
  33900. } else {
  33901. ret = `>=${M}.${m4}.${p3}${z2} <${M}.${+m4 + 1}.0-0`;
  33902. }
  33903. } else {
  33904. ret = `>=${M}.${m4}.${p3} <${+M + 1}.0.0-0`;
  33905. }
  33906. }
  33907. debug("caret return", ret);
  33908. return ret;
  33909. });
  33910. };
  33911. var replaceXRanges = (comp, options) => {
  33912. debug("replaceXRanges", comp, options);
  33913. return comp.split(/\s+/).map((c3) => replaceXRange(c3, options)).join(" ");
  33914. };
  33915. var replaceXRange = (comp, options) => {
  33916. comp = comp.trim();
  33917. const r4 = options.loose ? re[t4.XRANGELOOSE] : re[t4.XRANGE];
  33918. return comp.replace(r4, (ret, gtlt, M, m4, p3, pr) => {
  33919. debug("xRange", comp, ret, gtlt, M, m4, p3, pr);
  33920. const xM = isX(M);
  33921. const xm = xM || isX(m4);
  33922. const xp = xm || isX(p3);
  33923. const anyX = xp;
  33924. if (gtlt === "=" && anyX) {
  33925. gtlt = "";
  33926. }
  33927. pr = options.includePrerelease ? "-0" : "";
  33928. if (xM) {
  33929. if (gtlt === ">" || gtlt === "<") {
  33930. ret = "<0.0.0-0";
  33931. } else {
  33932. ret = "*";
  33933. }
  33934. } else if (gtlt && anyX) {
  33935. if (xm) {
  33936. m4 = 0;
  33937. }
  33938. p3 = 0;
  33939. if (gtlt === ">") {
  33940. gtlt = ">=";
  33941. if (xm) {
  33942. M = +M + 1;
  33943. m4 = 0;
  33944. p3 = 0;
  33945. } else {
  33946. m4 = +m4 + 1;
  33947. p3 = 0;
  33948. }
  33949. } else if (gtlt === "<=") {
  33950. gtlt = "<";
  33951. if (xm) {
  33952. M = +M + 1;
  33953. } else {
  33954. m4 = +m4 + 1;
  33955. }
  33956. }
  33957. if (gtlt === "<") {
  33958. pr = "-0";
  33959. }
  33960. ret = `${gtlt + M}.${m4}.${p3}${pr}`;
  33961. } else if (xm) {
  33962. ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
  33963. } else if (xp) {
  33964. ret = `>=${M}.${m4}.0${pr} <${M}.${+m4 + 1}.0-0`;
  33965. }
  33966. debug("xRange return", ret);
  33967. return ret;
  33968. });
  33969. };
  33970. var replaceStars = (comp, options) => {
  33971. debug("replaceStars", comp, options);
  33972. return comp.trim().replace(re[t4.STAR], "");
  33973. };
  33974. var replaceGTE0 = (comp, options) => {
  33975. debug("replaceGTE0", comp, options);
  33976. return comp.trim().replace(re[options.includePrerelease ? t4.GTE0PRE : t4.GTE0], "");
  33977. };
  33978. var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
  33979. if (isX(fM)) {
  33980. from = "";
  33981. } else if (isX(fm)) {
  33982. from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
  33983. } else if (isX(fp)) {
  33984. from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
  33985. } else if (fpr) {
  33986. from = `>=${from}`;
  33987. } else {
  33988. from = `>=${from}${incPr ? "-0" : ""}`;
  33989. }
  33990. if (isX(tM)) {
  33991. to = "";
  33992. } else if (isX(tm)) {
  33993. to = `<${+tM + 1}.0.0-0`;
  33994. } else if (isX(tp)) {
  33995. to = `<${tM}.${+tm + 1}.0-0`;
  33996. } else if (tpr) {
  33997. to = `<=${tM}.${tm}.${tp}-${tpr}`;
  33998. } else if (incPr) {
  33999. to = `<${tM}.${tm}.${+tp + 1}-0`;
  34000. } else {
  34001. to = `<=${to}`;
  34002. }
  34003. return `${from} ${to}`.trim();
  34004. };
  34005. var testSet = (set, version3, options) => {
  34006. for (let i4 = 0; i4 < set.length; i4++) {
  34007. if (!set[i4].test(version3)) {
  34008. return false;
  34009. }
  34010. }
  34011. if (version3.prerelease.length && !options.includePrerelease) {
  34012. for (let i4 = 0; i4 < set.length; i4++) {
  34013. debug(set[i4].semver);
  34014. if (set[i4].semver === Comparator.ANY) {
  34015. continue;
  34016. }
  34017. if (set[i4].semver.prerelease.length > 0) {
  34018. const allowed = set[i4].semver;
  34019. if (allowed.major === version3.major && allowed.minor === version3.minor && allowed.patch === version3.patch) {
  34020. return true;
  34021. }
  34022. }
  34023. }
  34024. return false;
  34025. }
  34026. return true;
  34027. };
  34028. }
  34029. });
  34030. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js
  34031. var require_comparator = __commonJS({
  34032. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js"(exports2, module2) {
  34033. "use strict";
  34034. var ANY = Symbol("SemVer ANY");
  34035. var Comparator = class _Comparator {
  34036. static get ANY() {
  34037. return ANY;
  34038. }
  34039. constructor(comp, options) {
  34040. options = parseOptions2(options);
  34041. if (comp instanceof _Comparator) {
  34042. if (comp.loose === !!options.loose) {
  34043. return comp;
  34044. } else {
  34045. comp = comp.value;
  34046. }
  34047. }
  34048. comp = comp.trim().split(/\s+/).join(" ");
  34049. debug("comparator", comp, options);
  34050. this.options = options;
  34051. this.loose = !!options.loose;
  34052. this.parse(comp);
  34053. if (this.semver === ANY) {
  34054. this.value = "";
  34055. } else {
  34056. this.value = this.operator + this.semver.version;
  34057. }
  34058. debug("comp", this);
  34059. }
  34060. parse(comp) {
  34061. const r4 = this.options.loose ? re[t4.COMPARATORLOOSE] : re[t4.COMPARATOR];
  34062. const m4 = comp.match(r4);
  34063. if (!m4) {
  34064. throw new TypeError(`Invalid comparator: ${comp}`);
  34065. }
  34066. this.operator = m4[1] !== void 0 ? m4[1] : "";
  34067. if (this.operator === "=") {
  34068. this.operator = "";
  34069. }
  34070. if (!m4[2]) {
  34071. this.semver = ANY;
  34072. } else {
  34073. this.semver = new SemVer(m4[2], this.options.loose);
  34074. }
  34075. }
  34076. toString() {
  34077. return this.value;
  34078. }
  34079. test(version3) {
  34080. debug("Comparator.test", version3, this.options.loose);
  34081. if (this.semver === ANY || version3 === ANY) {
  34082. return true;
  34083. }
  34084. if (typeof version3 === "string") {
  34085. try {
  34086. version3 = new SemVer(version3, this.options);
  34087. } catch (er) {
  34088. return false;
  34089. }
  34090. }
  34091. return cmp(version3, this.operator, this.semver, this.options);
  34092. }
  34093. intersects(comp, options) {
  34094. if (!(comp instanceof _Comparator)) {
  34095. throw new TypeError("a Comparator is required");
  34096. }
  34097. if (this.operator === "") {
  34098. if (this.value === "") {
  34099. return true;
  34100. }
  34101. return new Range(comp.value, options).test(this.value);
  34102. } else if (comp.operator === "") {
  34103. if (comp.value === "") {
  34104. return true;
  34105. }
  34106. return new Range(this.value, options).test(comp.semver);
  34107. }
  34108. options = parseOptions2(options);
  34109. if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
  34110. return false;
  34111. }
  34112. if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
  34113. return false;
  34114. }
  34115. if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
  34116. return true;
  34117. }
  34118. if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
  34119. return true;
  34120. }
  34121. if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
  34122. return true;
  34123. }
  34124. if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
  34125. return true;
  34126. }
  34127. if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
  34128. return true;
  34129. }
  34130. return false;
  34131. }
  34132. };
  34133. module2.exports = Comparator;
  34134. var parseOptions2 = require_parse_options();
  34135. var { safeRe: re, t: t4 } = require_re();
  34136. var cmp = require_cmp();
  34137. var debug = require_debug();
  34138. var SemVer = require_semver();
  34139. var Range = require_range();
  34140. }
  34141. });
  34142. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js
  34143. var require_satisfies = __commonJS({
  34144. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js"(exports2, module2) {
  34145. "use strict";
  34146. var Range = require_range();
  34147. var satisfies = (version3, range, options) => {
  34148. try {
  34149. range = new Range(range, options);
  34150. } catch (er) {
  34151. return false;
  34152. }
  34153. return range.test(version3);
  34154. };
  34155. module2.exports = satisfies;
  34156. }
  34157. });
  34158. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js
  34159. var require_to_comparators = __commonJS({
  34160. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js"(exports2, module2) {
  34161. "use strict";
  34162. var Range = require_range();
  34163. var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c3) => c3.value).join(" ").trim().split(" "));
  34164. module2.exports = toComparators;
  34165. }
  34166. });
  34167. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js
  34168. var require_max_satisfying = __commonJS({
  34169. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js"(exports2, module2) {
  34170. "use strict";
  34171. var SemVer = require_semver();
  34172. var Range = require_range();
  34173. var maxSatisfying = (versions, range, options) => {
  34174. let max = null;
  34175. let maxSV = null;
  34176. let rangeObj = null;
  34177. try {
  34178. rangeObj = new Range(range, options);
  34179. } catch (er) {
  34180. return null;
  34181. }
  34182. versions.forEach((v6) => {
  34183. if (rangeObj.test(v6)) {
  34184. if (!max || maxSV.compare(v6) === -1) {
  34185. max = v6;
  34186. maxSV = new SemVer(max, options);
  34187. }
  34188. }
  34189. });
  34190. return max;
  34191. };
  34192. module2.exports = maxSatisfying;
  34193. }
  34194. });
  34195. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js
  34196. var require_min_satisfying = __commonJS({
  34197. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js"(exports2, module2) {
  34198. "use strict";
  34199. var SemVer = require_semver();
  34200. var Range = require_range();
  34201. var minSatisfying = (versions, range, options) => {
  34202. let min = null;
  34203. let minSV = null;
  34204. let rangeObj = null;
  34205. try {
  34206. rangeObj = new Range(range, options);
  34207. } catch (er) {
  34208. return null;
  34209. }
  34210. versions.forEach((v6) => {
  34211. if (rangeObj.test(v6)) {
  34212. if (!min || minSV.compare(v6) === 1) {
  34213. min = v6;
  34214. minSV = new SemVer(min, options);
  34215. }
  34216. }
  34217. });
  34218. return min;
  34219. };
  34220. module2.exports = minSatisfying;
  34221. }
  34222. });
  34223. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js
  34224. var require_min_version = __commonJS({
  34225. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js"(exports2, module2) {
  34226. "use strict";
  34227. var SemVer = require_semver();
  34228. var Range = require_range();
  34229. var gt = require_gt();
  34230. var minVersion = (range, loose) => {
  34231. range = new Range(range, loose);
  34232. let minver = new SemVer("0.0.0");
  34233. if (range.test(minver)) {
  34234. return minver;
  34235. }
  34236. minver = new SemVer("0.0.0-0");
  34237. if (range.test(minver)) {
  34238. return minver;
  34239. }
  34240. minver = null;
  34241. for (let i4 = 0; i4 < range.set.length; ++i4) {
  34242. const comparators = range.set[i4];
  34243. let setMin = null;
  34244. comparators.forEach((comparator) => {
  34245. const compver = new SemVer(comparator.semver.version);
  34246. switch (comparator.operator) {
  34247. case ">":
  34248. if (compver.prerelease.length === 0) {
  34249. compver.patch++;
  34250. } else {
  34251. compver.prerelease.push(0);
  34252. }
  34253. compver.raw = compver.format();
  34254. /* fallthrough */
  34255. case "":
  34256. case ">=":
  34257. if (!setMin || gt(compver, setMin)) {
  34258. setMin = compver;
  34259. }
  34260. break;
  34261. case "<":
  34262. case "<=":
  34263. break;
  34264. /* istanbul ignore next */
  34265. default:
  34266. throw new Error(`Unexpected operation: ${comparator.operator}`);
  34267. }
  34268. });
  34269. if (setMin && (!minver || gt(minver, setMin))) {
  34270. minver = setMin;
  34271. }
  34272. }
  34273. if (minver && range.test(minver)) {
  34274. return minver;
  34275. }
  34276. return null;
  34277. };
  34278. module2.exports = minVersion;
  34279. }
  34280. });
  34281. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js
  34282. var require_valid2 = __commonJS({
  34283. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js"(exports2, module2) {
  34284. "use strict";
  34285. var Range = require_range();
  34286. var validRange = (range, options) => {
  34287. try {
  34288. return new Range(range, options).range || "*";
  34289. } catch (er) {
  34290. return null;
  34291. }
  34292. };
  34293. module2.exports = validRange;
  34294. }
  34295. });
  34296. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js
  34297. var require_outside = __commonJS({
  34298. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js"(exports2, module2) {
  34299. "use strict";
  34300. var SemVer = require_semver();
  34301. var Comparator = require_comparator();
  34302. var { ANY } = Comparator;
  34303. var Range = require_range();
  34304. var satisfies = require_satisfies();
  34305. var gt = require_gt();
  34306. var lt = require_lt();
  34307. var lte = require_lte();
  34308. var gte = require_gte();
  34309. var outside = (version3, range, hilo, options) => {
  34310. version3 = new SemVer(version3, options);
  34311. range = new Range(range, options);
  34312. let gtfn, ltefn, ltfn, comp, ecomp;
  34313. switch (hilo) {
  34314. case ">":
  34315. gtfn = gt;
  34316. ltefn = lte;
  34317. ltfn = lt;
  34318. comp = ">";
  34319. ecomp = ">=";
  34320. break;
  34321. case "<":
  34322. gtfn = lt;
  34323. ltefn = gte;
  34324. ltfn = gt;
  34325. comp = "<";
  34326. ecomp = "<=";
  34327. break;
  34328. default:
  34329. throw new TypeError('Must provide a hilo val of "<" or ">"');
  34330. }
  34331. if (satisfies(version3, range, options)) {
  34332. return false;
  34333. }
  34334. for (let i4 = 0; i4 < range.set.length; ++i4) {
  34335. const comparators = range.set[i4];
  34336. let high = null;
  34337. let low = null;
  34338. comparators.forEach((comparator) => {
  34339. if (comparator.semver === ANY) {
  34340. comparator = new Comparator(">=0.0.0");
  34341. }
  34342. high = high || comparator;
  34343. low = low || comparator;
  34344. if (gtfn(comparator.semver, high.semver, options)) {
  34345. high = comparator;
  34346. } else if (ltfn(comparator.semver, low.semver, options)) {
  34347. low = comparator;
  34348. }
  34349. });
  34350. if (high.operator === comp || high.operator === ecomp) {
  34351. return false;
  34352. }
  34353. if ((!low.operator || low.operator === comp) && ltefn(version3, low.semver)) {
  34354. return false;
  34355. } else if (low.operator === ecomp && ltfn(version3, low.semver)) {
  34356. return false;
  34357. }
  34358. }
  34359. return true;
  34360. };
  34361. module2.exports = outside;
  34362. }
  34363. });
  34364. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js
  34365. var require_gtr = __commonJS({
  34366. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js"(exports2, module2) {
  34367. "use strict";
  34368. var outside = require_outside();
  34369. var gtr = (version3, range, options) => outside(version3, range, ">", options);
  34370. module2.exports = gtr;
  34371. }
  34372. });
  34373. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js
  34374. var require_ltr = __commonJS({
  34375. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js"(exports2, module2) {
  34376. "use strict";
  34377. var outside = require_outside();
  34378. var ltr = (version3, range, options) => outside(version3, range, "<", options);
  34379. module2.exports = ltr;
  34380. }
  34381. });
  34382. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js
  34383. var require_intersects = __commonJS({
  34384. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js"(exports2, module2) {
  34385. "use strict";
  34386. var Range = require_range();
  34387. var intersects = (r1, r22, options) => {
  34388. r1 = new Range(r1, options);
  34389. r22 = new Range(r22, options);
  34390. return r1.intersects(r22, options);
  34391. };
  34392. module2.exports = intersects;
  34393. }
  34394. });
  34395. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js
  34396. var require_simplify = __commonJS({
  34397. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js"(exports2, module2) {
  34398. "use strict";
  34399. var satisfies = require_satisfies();
  34400. var compare = require_compare();
  34401. module2.exports = (versions, range, options) => {
  34402. const set = [];
  34403. let first = null;
  34404. let prev = null;
  34405. const v6 = versions.sort((a3, b3) => compare(a3, b3, options));
  34406. for (const version3 of v6) {
  34407. const included = satisfies(version3, range, options);
  34408. if (included) {
  34409. prev = version3;
  34410. if (!first) {
  34411. first = version3;
  34412. }
  34413. } else {
  34414. if (prev) {
  34415. set.push([first, prev]);
  34416. }
  34417. prev = null;
  34418. first = null;
  34419. }
  34420. }
  34421. if (first) {
  34422. set.push([first, null]);
  34423. }
  34424. const ranges = [];
  34425. for (const [min, max] of set) {
  34426. if (min === max) {
  34427. ranges.push(min);
  34428. } else if (!max && min === v6[0]) {
  34429. ranges.push("*");
  34430. } else if (!max) {
  34431. ranges.push(`>=${min}`);
  34432. } else if (min === v6[0]) {
  34433. ranges.push(`<=${max}`);
  34434. } else {
  34435. ranges.push(`${min} - ${max}`);
  34436. }
  34437. }
  34438. const simplified = ranges.join(" || ");
  34439. const original = typeof range.raw === "string" ? range.raw : String(range);
  34440. return simplified.length < original.length ? simplified : range;
  34441. };
  34442. }
  34443. });
  34444. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js
  34445. var require_subset = __commonJS({
  34446. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js"(exports2, module2) {
  34447. "use strict";
  34448. var Range = require_range();
  34449. var Comparator = require_comparator();
  34450. var { ANY } = Comparator;
  34451. var satisfies = require_satisfies();
  34452. var compare = require_compare();
  34453. var subset = (sub, dom, options = {}) => {
  34454. if (sub === dom) {
  34455. return true;
  34456. }
  34457. sub = new Range(sub, options);
  34458. dom = new Range(dom, options);
  34459. let sawNonNull = false;
  34460. OUTER: for (const simpleSub of sub.set) {
  34461. for (const simpleDom of dom.set) {
  34462. const isSub = simpleSubset(simpleSub, simpleDom, options);
  34463. sawNonNull = sawNonNull || isSub !== null;
  34464. if (isSub) {
  34465. continue OUTER;
  34466. }
  34467. }
  34468. if (sawNonNull) {
  34469. return false;
  34470. }
  34471. }
  34472. return true;
  34473. };
  34474. var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
  34475. var minimumVersion = [new Comparator(">=0.0.0")];
  34476. var simpleSubset = (sub, dom, options) => {
  34477. if (sub === dom) {
  34478. return true;
  34479. }
  34480. if (sub.length === 1 && sub[0].semver === ANY) {
  34481. if (dom.length === 1 && dom[0].semver === ANY) {
  34482. return true;
  34483. } else if (options.includePrerelease) {
  34484. sub = minimumVersionWithPreRelease;
  34485. } else {
  34486. sub = minimumVersion;
  34487. }
  34488. }
  34489. if (dom.length === 1 && dom[0].semver === ANY) {
  34490. if (options.includePrerelease) {
  34491. return true;
  34492. } else {
  34493. dom = minimumVersion;
  34494. }
  34495. }
  34496. const eqSet = /* @__PURE__ */ new Set();
  34497. let gt, lt;
  34498. for (const c3 of sub) {
  34499. if (c3.operator === ">" || c3.operator === ">=") {
  34500. gt = higherGT(gt, c3, options);
  34501. } else if (c3.operator === "<" || c3.operator === "<=") {
  34502. lt = lowerLT(lt, c3, options);
  34503. } else {
  34504. eqSet.add(c3.semver);
  34505. }
  34506. }
  34507. if (eqSet.size > 1) {
  34508. return null;
  34509. }
  34510. let gtltComp;
  34511. if (gt && lt) {
  34512. gtltComp = compare(gt.semver, lt.semver, options);
  34513. if (gtltComp > 0) {
  34514. return null;
  34515. } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
  34516. return null;
  34517. }
  34518. }
  34519. for (const eq of eqSet) {
  34520. if (gt && !satisfies(eq, String(gt), options)) {
  34521. return null;
  34522. }
  34523. if (lt && !satisfies(eq, String(lt), options)) {
  34524. return null;
  34525. }
  34526. for (const c3 of dom) {
  34527. if (!satisfies(eq, String(c3), options)) {
  34528. return false;
  34529. }
  34530. }
  34531. return true;
  34532. }
  34533. let higher, lower2;
  34534. let hasDomLT, hasDomGT;
  34535. let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
  34536. let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
  34537. if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
  34538. needDomLTPre = false;
  34539. }
  34540. for (const c3 of dom) {
  34541. hasDomGT = hasDomGT || c3.operator === ">" || c3.operator === ">=";
  34542. hasDomLT = hasDomLT || c3.operator === "<" || c3.operator === "<=";
  34543. if (gt) {
  34544. if (needDomGTPre) {
  34545. if (c3.semver.prerelease && c3.semver.prerelease.length && c3.semver.major === needDomGTPre.major && c3.semver.minor === needDomGTPre.minor && c3.semver.patch === needDomGTPre.patch) {
  34546. needDomGTPre = false;
  34547. }
  34548. }
  34549. if (c3.operator === ">" || c3.operator === ">=") {
  34550. higher = higherGT(gt, c3, options);
  34551. if (higher === c3 && higher !== gt) {
  34552. return false;
  34553. }
  34554. } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c3), options)) {
  34555. return false;
  34556. }
  34557. }
  34558. if (lt) {
  34559. if (needDomLTPre) {
  34560. if (c3.semver.prerelease && c3.semver.prerelease.length && c3.semver.major === needDomLTPre.major && c3.semver.minor === needDomLTPre.minor && c3.semver.patch === needDomLTPre.patch) {
  34561. needDomLTPre = false;
  34562. }
  34563. }
  34564. if (c3.operator === "<" || c3.operator === "<=") {
  34565. lower2 = lowerLT(lt, c3, options);
  34566. if (lower2 === c3 && lower2 !== lt) {
  34567. return false;
  34568. }
  34569. } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c3), options)) {
  34570. return false;
  34571. }
  34572. }
  34573. if (!c3.operator && (lt || gt) && gtltComp !== 0) {
  34574. return false;
  34575. }
  34576. }
  34577. if (gt && hasDomLT && !lt && gtltComp !== 0) {
  34578. return false;
  34579. }
  34580. if (lt && hasDomGT && !gt && gtltComp !== 0) {
  34581. return false;
  34582. }
  34583. if (needDomGTPre || needDomLTPre) {
  34584. return false;
  34585. }
  34586. return true;
  34587. };
  34588. var higherGT = (a3, b3, options) => {
  34589. if (!a3) {
  34590. return b3;
  34591. }
  34592. const comp = compare(a3.semver, b3.semver, options);
  34593. return comp > 0 ? a3 : comp < 0 ? b3 : b3.operator === ">" && a3.operator === ">=" ? b3 : a3;
  34594. };
  34595. var lowerLT = (a3, b3, options) => {
  34596. if (!a3) {
  34597. return b3;
  34598. }
  34599. const comp = compare(a3.semver, b3.semver, options);
  34600. return comp < 0 ? a3 : comp > 0 ? b3 : b3.operator === "<" && a3.operator === "<=" ? b3 : a3;
  34601. };
  34602. module2.exports = subset;
  34603. }
  34604. });
  34605. // ../node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js
  34606. var require_semver2 = __commonJS({
  34607. "../node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js"(exports2, module2) {
  34608. "use strict";
  34609. var internalRe = require_re();
  34610. var constants = require_constants();
  34611. var SemVer = require_semver();
  34612. var identifiers = require_identifiers();
  34613. var parse4 = require_parse2();
  34614. var valid = require_valid();
  34615. var clean = require_clean();
  34616. var inc = require_inc();
  34617. var diff2 = require_diff();
  34618. var major = require_major();
  34619. var minor = require_minor();
  34620. var patch = require_patch();
  34621. var prerelease = require_prerelease();
  34622. var compare = require_compare();
  34623. var rcompare = require_rcompare();
  34624. var compareLoose = require_compare_loose();
  34625. var compareBuild = require_compare_build();
  34626. var sort = require_sort();
  34627. var rsort = require_rsort();
  34628. var gt = require_gt();
  34629. var lt = require_lt();
  34630. var eq = require_eq();
  34631. var neq = require_neq();
  34632. var gte = require_gte();
  34633. var lte = require_lte();
  34634. var cmp = require_cmp();
  34635. var coerce2 = require_coerce();
  34636. var Comparator = require_comparator();
  34637. var Range = require_range();
  34638. var satisfies = require_satisfies();
  34639. var toComparators = require_to_comparators();
  34640. var maxSatisfying = require_max_satisfying();
  34641. var minSatisfying = require_min_satisfying();
  34642. var minVersion = require_min_version();
  34643. var validRange = require_valid2();
  34644. var outside = require_outside();
  34645. var gtr = require_gtr();
  34646. var ltr = require_ltr();
  34647. var intersects = require_intersects();
  34648. var simplifyRange = require_simplify();
  34649. var subset = require_subset();
  34650. module2.exports = {
  34651. parse: parse4,
  34652. valid,
  34653. clean,
  34654. inc,
  34655. diff: diff2,
  34656. major,
  34657. minor,
  34658. patch,
  34659. prerelease,
  34660. compare,
  34661. rcompare,
  34662. compareLoose,
  34663. compareBuild,
  34664. sort,
  34665. rsort,
  34666. gt,
  34667. lt,
  34668. eq,
  34669. neq,
  34670. gte,
  34671. lte,
  34672. cmp,
  34673. coerce: coerce2,
  34674. Comparator,
  34675. Range,
  34676. satisfies,
  34677. toComparators,
  34678. maxSatisfying,
  34679. minSatisfying,
  34680. minVersion,
  34681. validRange,
  34682. outside,
  34683. gtr,
  34684. ltr,
  34685. intersects,
  34686. simplifyRange,
  34687. subset,
  34688. SemVer,
  34689. re: internalRe.re,
  34690. src: internalRe.src,
  34691. tokens: internalRe.t,
  34692. SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
  34693. RELEASE_TYPES: constants.RELEASE_TYPES,
  34694. compareIdentifiers: identifiers.compareIdentifiers,
  34695. rcompareIdentifiers: identifiers.rcompareIdentifiers
  34696. };
  34697. }
  34698. });
  34699. // src/cli/utils.ts
  34700. var import_semver, ormVersionGt, assertStudioNodeVersion, checkPackage, assertPackages, requiredApiVersion, assertOrmCoreVersion, ormCoreVersions;
  34701. var init_utils5 = __esm({
  34702. "src/cli/utils.ts"() {
  34703. "use strict";
  34704. import_semver = __toESM(require_semver2());
  34705. init_views();
  34706. ormVersionGt = async (version3) => {
  34707. const { npmVersion } = await import("drizzle-orm/version");
  34708. if (!import_semver.default.gte(npmVersion, version3)) {
  34709. return false;
  34710. }
  34711. return true;
  34712. };
  34713. assertStudioNodeVersion = () => {
  34714. if (import_semver.default.gte(process.version, "18.0.0")) return;
  34715. err("Drizzle Studio requires NodeJS v18 or above");
  34716. process.exit(1);
  34717. };
  34718. checkPackage = async (it) => {
  34719. try {
  34720. await import(it);
  34721. return true;
  34722. } catch (e4) {
  34723. return false;
  34724. }
  34725. };
  34726. assertPackages = async (...pkgs) => {
  34727. try {
  34728. for (let i4 = 0; i4 < pkgs.length; i4++) {
  34729. const it = pkgs[i4];
  34730. await import(it);
  34731. }
  34732. } catch (e4) {
  34733. err(
  34734. `please install required packages: ${pkgs.map((it) => `'${it}'`).join(" ")}`
  34735. );
  34736. process.exit(1);
  34737. }
  34738. };
  34739. requiredApiVersion = 10;
  34740. assertOrmCoreVersion = async () => {
  34741. try {
  34742. const { compatibilityVersion } = await import("drizzle-orm/version");
  34743. await import("drizzle-orm/relations");
  34744. if (compatibilityVersion && compatibilityVersion === requiredApiVersion) {
  34745. return;
  34746. }
  34747. if (!compatibilityVersion || compatibilityVersion < requiredApiVersion) {
  34748. console.log(
  34749. "This version of drizzle-kit requires newer version of drizzle-orm\nPlease update drizzle-orm package to the latest version \u{1F44D}"
  34750. );
  34751. } else {
  34752. console.log(
  34753. "This version of drizzle-kit is outdated\nPlease update drizzle-kit package to the latest version \u{1F44D}"
  34754. );
  34755. }
  34756. } catch (e4) {
  34757. console.log("Please install latest version of drizzle-orm");
  34758. }
  34759. process.exit(1);
  34760. };
  34761. ormCoreVersions = async () => {
  34762. try {
  34763. const { compatibilityVersion, npmVersion } = await import("drizzle-orm/version");
  34764. return { compatibilityVersion, npmVersion };
  34765. } catch (e4) {
  34766. return {};
  34767. }
  34768. };
  34769. }
  34770. });
  34771. // ../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js
  34772. function dataUriToBuffer(uri) {
  34773. if (!/^data:/i.test(uri)) {
  34774. throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
  34775. }
  34776. uri = uri.replace(/\r?\n/g, "");
  34777. const firstComma = uri.indexOf(",");
  34778. if (firstComma === -1 || firstComma <= 4) {
  34779. throw new TypeError("malformed data: URI");
  34780. }
  34781. const meta = uri.substring(5, firstComma).split(";");
  34782. let charset = "";
  34783. let base64 = false;
  34784. const type = meta[0] || "text/plain";
  34785. let typeFull = type;
  34786. for (let i4 = 1; i4 < meta.length; i4++) {
  34787. if (meta[i4] === "base64") {
  34788. base64 = true;
  34789. } else if (meta[i4]) {
  34790. typeFull += `;${meta[i4]}`;
  34791. if (meta[i4].indexOf("charset=") === 0) {
  34792. charset = meta[i4].substring(8);
  34793. }
  34794. }
  34795. }
  34796. if (!meta[0] && !charset.length) {
  34797. typeFull += ";charset=US-ASCII";
  34798. charset = "US-ASCII";
  34799. }
  34800. const encoding = base64 ? "base64" : "ascii";
  34801. const data = unescape(uri.substring(firstComma + 1));
  34802. const buffer = Buffer.from(data, encoding);
  34803. buffer.type = type;
  34804. buffer.typeFull = typeFull;
  34805. buffer.charset = charset;
  34806. return buffer;
  34807. }
  34808. var dist_default;
  34809. var init_dist = __esm({
  34810. "../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js"() {
  34811. dist_default = dataUriToBuffer;
  34812. }
  34813. });
  34814. // ../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js
  34815. var require_ponyfill_es2018 = __commonJS({
  34816. "../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports2, module2) {
  34817. (function(global2, factory) {
  34818. typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {}));
  34819. })(exports2, function(exports3) {
  34820. "use strict";
  34821. function noop2() {
  34822. return void 0;
  34823. }
  34824. function typeIsObject(x4) {
  34825. return typeof x4 === "object" && x4 !== null || typeof x4 === "function";
  34826. }
  34827. const rethrowAssertionErrorRejection = noop2;
  34828. function setFunctionName(fn, name) {
  34829. try {
  34830. Object.defineProperty(fn, "name", {
  34831. value: name,
  34832. configurable: true
  34833. });
  34834. } catch (_a3) {
  34835. }
  34836. }
  34837. const originalPromise = Promise;
  34838. const originalPromiseThen = Promise.prototype.then;
  34839. const originalPromiseReject = Promise.reject.bind(originalPromise);
  34840. function newPromise(executor) {
  34841. return new originalPromise(executor);
  34842. }
  34843. function promiseResolvedWith(value) {
  34844. return newPromise((resolve2) => resolve2(value));
  34845. }
  34846. function promiseRejectedWith(reason) {
  34847. return originalPromiseReject(reason);
  34848. }
  34849. function PerformPromiseThen(promise, onFulfilled, onRejected) {
  34850. return originalPromiseThen.call(promise, onFulfilled, onRejected);
  34851. }
  34852. function uponPromise(promise, onFulfilled, onRejected) {
  34853. PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection);
  34854. }
  34855. function uponFulfillment(promise, onFulfilled) {
  34856. uponPromise(promise, onFulfilled);
  34857. }
  34858. function uponRejection(promise, onRejected) {
  34859. uponPromise(promise, void 0, onRejected);
  34860. }
  34861. function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
  34862. return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
  34863. }
  34864. function setPromiseIsHandledToTrue(promise) {
  34865. PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection);
  34866. }
  34867. let _queueMicrotask = (callback) => {
  34868. if (typeof queueMicrotask === "function") {
  34869. _queueMicrotask = queueMicrotask;
  34870. } else {
  34871. const resolvedPromise = promiseResolvedWith(void 0);
  34872. _queueMicrotask = (cb) => PerformPromiseThen(resolvedPromise, cb);
  34873. }
  34874. return _queueMicrotask(callback);
  34875. };
  34876. function reflectCall(F3, V, args) {
  34877. if (typeof F3 !== "function") {
  34878. throw new TypeError("Argument is not a function");
  34879. }
  34880. return Function.prototype.apply.call(F3, V, args);
  34881. }
  34882. function promiseCall(F3, V, args) {
  34883. try {
  34884. return promiseResolvedWith(reflectCall(F3, V, args));
  34885. } catch (value) {
  34886. return promiseRejectedWith(value);
  34887. }
  34888. }
  34889. const QUEUE_MAX_ARRAY_SIZE = 16384;
  34890. class SimpleQueue {
  34891. constructor() {
  34892. this._cursor = 0;
  34893. this._size = 0;
  34894. this._front = {
  34895. _elements: [],
  34896. _next: void 0
  34897. };
  34898. this._back = this._front;
  34899. this._cursor = 0;
  34900. this._size = 0;
  34901. }
  34902. get length() {
  34903. return this._size;
  34904. }
  34905. // For exception safety, this method is structured in order:
  34906. // 1. Read state
  34907. // 2. Calculate required state mutations
  34908. // 3. Perform state mutations
  34909. push(element) {
  34910. const oldBack = this._back;
  34911. let newBack = oldBack;
  34912. if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
  34913. newBack = {
  34914. _elements: [],
  34915. _next: void 0
  34916. };
  34917. }
  34918. oldBack._elements.push(element);
  34919. if (newBack !== oldBack) {
  34920. this._back = newBack;
  34921. oldBack._next = newBack;
  34922. }
  34923. ++this._size;
  34924. }
  34925. // Like push(), shift() follows the read -> calculate -> mutate pattern for
  34926. // exception safety.
  34927. shift() {
  34928. const oldFront = this._front;
  34929. let newFront = oldFront;
  34930. const oldCursor = this._cursor;
  34931. let newCursor = oldCursor + 1;
  34932. const elements = oldFront._elements;
  34933. const element = elements[oldCursor];
  34934. if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
  34935. newFront = oldFront._next;
  34936. newCursor = 0;
  34937. }
  34938. --this._size;
  34939. this._cursor = newCursor;
  34940. if (oldFront !== newFront) {
  34941. this._front = newFront;
  34942. }
  34943. elements[oldCursor] = void 0;
  34944. return element;
  34945. }
  34946. // The tricky thing about forEach() is that it can be called
  34947. // re-entrantly. The queue may be mutated inside the callback. It is easy to
  34948. // see that push() within the callback has no negative effects since the end
  34949. // of the queue is checked for on every iteration. If shift() is called
  34950. // repeatedly within the callback then the next iteration may return an
  34951. // element that has been removed. In this case the callback will be called
  34952. // with undefined values until we either "catch up" with elements that still
  34953. // exist or reach the back of the queue.
  34954. forEach(callback) {
  34955. let i4 = this._cursor;
  34956. let node = this._front;
  34957. let elements = node._elements;
  34958. while (i4 !== elements.length || node._next !== void 0) {
  34959. if (i4 === elements.length) {
  34960. node = node._next;
  34961. elements = node._elements;
  34962. i4 = 0;
  34963. if (elements.length === 0) {
  34964. break;
  34965. }
  34966. }
  34967. callback(elements[i4]);
  34968. ++i4;
  34969. }
  34970. }
  34971. // Return the element that would be returned if shift() was called now,
  34972. // without modifying the queue.
  34973. peek() {
  34974. const front = this._front;
  34975. const cursor = this._cursor;
  34976. return front._elements[cursor];
  34977. }
  34978. }
  34979. const AbortSteps = Symbol("[[AbortSteps]]");
  34980. const ErrorSteps = Symbol("[[ErrorSteps]]");
  34981. const CancelSteps = Symbol("[[CancelSteps]]");
  34982. const PullSteps = Symbol("[[PullSteps]]");
  34983. const ReleaseSteps = Symbol("[[ReleaseSteps]]");
  34984. function ReadableStreamReaderGenericInitialize(reader, stream) {
  34985. reader._ownerReadableStream = stream;
  34986. stream._reader = reader;
  34987. if (stream._state === "readable") {
  34988. defaultReaderClosedPromiseInitialize(reader);
  34989. } else if (stream._state === "closed") {
  34990. defaultReaderClosedPromiseInitializeAsResolved(reader);
  34991. } else {
  34992. defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
  34993. }
  34994. }
  34995. function ReadableStreamReaderGenericCancel(reader, reason) {
  34996. const stream = reader._ownerReadableStream;
  34997. return ReadableStreamCancel(stream, reason);
  34998. }
  34999. function ReadableStreamReaderGenericRelease(reader) {
  35000. const stream = reader._ownerReadableStream;
  35001. if (stream._state === "readable") {
  35002. defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
  35003. } else {
  35004. defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
  35005. }
  35006. stream._readableStreamController[ReleaseSteps]();
  35007. stream._reader = void 0;
  35008. reader._ownerReadableStream = void 0;
  35009. }
  35010. function readerLockException(name) {
  35011. return new TypeError("Cannot " + name + " a stream using a released reader");
  35012. }
  35013. function defaultReaderClosedPromiseInitialize(reader) {
  35014. reader._closedPromise = newPromise((resolve2, reject) => {
  35015. reader._closedPromise_resolve = resolve2;
  35016. reader._closedPromise_reject = reject;
  35017. });
  35018. }
  35019. function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
  35020. defaultReaderClosedPromiseInitialize(reader);
  35021. defaultReaderClosedPromiseReject(reader, reason);
  35022. }
  35023. function defaultReaderClosedPromiseInitializeAsResolved(reader) {
  35024. defaultReaderClosedPromiseInitialize(reader);
  35025. defaultReaderClosedPromiseResolve(reader);
  35026. }
  35027. function defaultReaderClosedPromiseReject(reader, reason) {
  35028. if (reader._closedPromise_reject === void 0) {
  35029. return;
  35030. }
  35031. setPromiseIsHandledToTrue(reader._closedPromise);
  35032. reader._closedPromise_reject(reason);
  35033. reader._closedPromise_resolve = void 0;
  35034. reader._closedPromise_reject = void 0;
  35035. }
  35036. function defaultReaderClosedPromiseResetToRejected(reader, reason) {
  35037. defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
  35038. }
  35039. function defaultReaderClosedPromiseResolve(reader) {
  35040. if (reader._closedPromise_resolve === void 0) {
  35041. return;
  35042. }
  35043. reader._closedPromise_resolve(void 0);
  35044. reader._closedPromise_resolve = void 0;
  35045. reader._closedPromise_reject = void 0;
  35046. }
  35047. const NumberIsFinite = Number.isFinite || function(x4) {
  35048. return typeof x4 === "number" && isFinite(x4);
  35049. };
  35050. const MathTrunc = Math.trunc || function(v6) {
  35051. return v6 < 0 ? Math.ceil(v6) : Math.floor(v6);
  35052. };
  35053. function isDictionary(x4) {
  35054. return typeof x4 === "object" || typeof x4 === "function";
  35055. }
  35056. function assertDictionary(obj, context) {
  35057. if (obj !== void 0 && !isDictionary(obj)) {
  35058. throw new TypeError(`${context} is not an object.`);
  35059. }
  35060. }
  35061. function assertFunction(x4, context) {
  35062. if (typeof x4 !== "function") {
  35063. throw new TypeError(`${context} is not a function.`);
  35064. }
  35065. }
  35066. function isObject(x4) {
  35067. return typeof x4 === "object" && x4 !== null || typeof x4 === "function";
  35068. }
  35069. function assertObject(x4, context) {
  35070. if (!isObject(x4)) {
  35071. throw new TypeError(`${context} is not an object.`);
  35072. }
  35073. }
  35074. function assertRequiredArgument(x4, position, context) {
  35075. if (x4 === void 0) {
  35076. throw new TypeError(`Parameter ${position} is required in '${context}'.`);
  35077. }
  35078. }
  35079. function assertRequiredField(x4, field, context) {
  35080. if (x4 === void 0) {
  35081. throw new TypeError(`${field} is required in '${context}'.`);
  35082. }
  35083. }
  35084. function convertUnrestrictedDouble(value) {
  35085. return Number(value);
  35086. }
  35087. function censorNegativeZero(x4) {
  35088. return x4 === 0 ? 0 : x4;
  35089. }
  35090. function integerPart(x4) {
  35091. return censorNegativeZero(MathTrunc(x4));
  35092. }
  35093. function convertUnsignedLongLongWithEnforceRange(value, context) {
  35094. const lowerBound = 0;
  35095. const upperBound = Number.MAX_SAFE_INTEGER;
  35096. let x4 = Number(value);
  35097. x4 = censorNegativeZero(x4);
  35098. if (!NumberIsFinite(x4)) {
  35099. throw new TypeError(`${context} is not a finite number`);
  35100. }
  35101. x4 = integerPart(x4);
  35102. if (x4 < lowerBound || x4 > upperBound) {
  35103. throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
  35104. }
  35105. if (!NumberIsFinite(x4) || x4 === 0) {
  35106. return 0;
  35107. }
  35108. return x4;
  35109. }
  35110. function assertReadableStream(x4, context) {
  35111. if (!IsReadableStream(x4)) {
  35112. throw new TypeError(`${context} is not a ReadableStream.`);
  35113. }
  35114. }
  35115. function AcquireReadableStreamDefaultReader(stream) {
  35116. return new ReadableStreamDefaultReader(stream);
  35117. }
  35118. function ReadableStreamAddReadRequest(stream, readRequest) {
  35119. stream._reader._readRequests.push(readRequest);
  35120. }
  35121. function ReadableStreamFulfillReadRequest(stream, chunk, done) {
  35122. const reader = stream._reader;
  35123. const readRequest = reader._readRequests.shift();
  35124. if (done) {
  35125. readRequest._closeSteps();
  35126. } else {
  35127. readRequest._chunkSteps(chunk);
  35128. }
  35129. }
  35130. function ReadableStreamGetNumReadRequests(stream) {
  35131. return stream._reader._readRequests.length;
  35132. }
  35133. function ReadableStreamHasDefaultReader(stream) {
  35134. const reader = stream._reader;
  35135. if (reader === void 0) {
  35136. return false;
  35137. }
  35138. if (!IsReadableStreamDefaultReader(reader)) {
  35139. return false;
  35140. }
  35141. return true;
  35142. }
  35143. class ReadableStreamDefaultReader {
  35144. constructor(stream) {
  35145. assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader");
  35146. assertReadableStream(stream, "First parameter");
  35147. if (IsReadableStreamLocked(stream)) {
  35148. throw new TypeError("This stream has already been locked for exclusive reading by another reader");
  35149. }
  35150. ReadableStreamReaderGenericInitialize(this, stream);
  35151. this._readRequests = new SimpleQueue();
  35152. }
  35153. /**
  35154. * Returns a promise that will be fulfilled when the stream becomes closed,
  35155. * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
  35156. */
  35157. get closed() {
  35158. if (!IsReadableStreamDefaultReader(this)) {
  35159. return promiseRejectedWith(defaultReaderBrandCheckException("closed"));
  35160. }
  35161. return this._closedPromise;
  35162. }
  35163. /**
  35164. * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
  35165. */
  35166. cancel(reason = void 0) {
  35167. if (!IsReadableStreamDefaultReader(this)) {
  35168. return promiseRejectedWith(defaultReaderBrandCheckException("cancel"));
  35169. }
  35170. if (this._ownerReadableStream === void 0) {
  35171. return promiseRejectedWith(readerLockException("cancel"));
  35172. }
  35173. return ReadableStreamReaderGenericCancel(this, reason);
  35174. }
  35175. /**
  35176. * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
  35177. *
  35178. * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
  35179. */
  35180. read() {
  35181. if (!IsReadableStreamDefaultReader(this)) {
  35182. return promiseRejectedWith(defaultReaderBrandCheckException("read"));
  35183. }
  35184. if (this._ownerReadableStream === void 0) {
  35185. return promiseRejectedWith(readerLockException("read from"));
  35186. }
  35187. let resolvePromise;
  35188. let rejectPromise;
  35189. const promise = newPromise((resolve2, reject) => {
  35190. resolvePromise = resolve2;
  35191. rejectPromise = reject;
  35192. });
  35193. const readRequest = {
  35194. _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }),
  35195. _closeSteps: () => resolvePromise({ value: void 0, done: true }),
  35196. _errorSteps: (e4) => rejectPromise(e4)
  35197. };
  35198. ReadableStreamDefaultReaderRead(this, readRequest);
  35199. return promise;
  35200. }
  35201. /**
  35202. * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
  35203. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
  35204. * from now on; otherwise, the reader will appear closed.
  35205. *
  35206. * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
  35207. * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
  35208. * do so will throw a `TypeError` and leave the reader locked to the stream.
  35209. */
  35210. releaseLock() {
  35211. if (!IsReadableStreamDefaultReader(this)) {
  35212. throw defaultReaderBrandCheckException("releaseLock");
  35213. }
  35214. if (this._ownerReadableStream === void 0) {
  35215. return;
  35216. }
  35217. ReadableStreamDefaultReaderRelease(this);
  35218. }
  35219. }
  35220. Object.defineProperties(ReadableStreamDefaultReader.prototype, {
  35221. cancel: { enumerable: true },
  35222. read: { enumerable: true },
  35223. releaseLock: { enumerable: true },
  35224. closed: { enumerable: true }
  35225. });
  35226. setFunctionName(ReadableStreamDefaultReader.prototype.cancel, "cancel");
  35227. setFunctionName(ReadableStreamDefaultReader.prototype.read, "read");
  35228. setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, "releaseLock");
  35229. if (typeof Symbol.toStringTag === "symbol") {
  35230. Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {
  35231. value: "ReadableStreamDefaultReader",
  35232. configurable: true
  35233. });
  35234. }
  35235. function IsReadableStreamDefaultReader(x4) {
  35236. if (!typeIsObject(x4)) {
  35237. return false;
  35238. }
  35239. if (!Object.prototype.hasOwnProperty.call(x4, "_readRequests")) {
  35240. return false;
  35241. }
  35242. return x4 instanceof ReadableStreamDefaultReader;
  35243. }
  35244. function ReadableStreamDefaultReaderRead(reader, readRequest) {
  35245. const stream = reader._ownerReadableStream;
  35246. stream._disturbed = true;
  35247. if (stream._state === "closed") {
  35248. readRequest._closeSteps();
  35249. } else if (stream._state === "errored") {
  35250. readRequest._errorSteps(stream._storedError);
  35251. } else {
  35252. stream._readableStreamController[PullSteps](readRequest);
  35253. }
  35254. }
  35255. function ReadableStreamDefaultReaderRelease(reader) {
  35256. ReadableStreamReaderGenericRelease(reader);
  35257. const e4 = new TypeError("Reader was released");
  35258. ReadableStreamDefaultReaderErrorReadRequests(reader, e4);
  35259. }
  35260. function ReadableStreamDefaultReaderErrorReadRequests(reader, e4) {
  35261. const readRequests = reader._readRequests;
  35262. reader._readRequests = new SimpleQueue();
  35263. readRequests.forEach((readRequest) => {
  35264. readRequest._errorSteps(e4);
  35265. });
  35266. }
  35267. function defaultReaderBrandCheckException(name) {
  35268. return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
  35269. }
  35270. const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {
  35271. }).prototype);
  35272. class ReadableStreamAsyncIteratorImpl {
  35273. constructor(reader, preventCancel) {
  35274. this._ongoingPromise = void 0;
  35275. this._isFinished = false;
  35276. this._reader = reader;
  35277. this._preventCancel = preventCancel;
  35278. }
  35279. next() {
  35280. const nextSteps = () => this._nextSteps();
  35281. this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps();
  35282. return this._ongoingPromise;
  35283. }
  35284. return(value) {
  35285. const returnSteps = () => this._returnSteps(value);
  35286. return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps();
  35287. }
  35288. _nextSteps() {
  35289. if (this._isFinished) {
  35290. return Promise.resolve({ value: void 0, done: true });
  35291. }
  35292. const reader = this._reader;
  35293. let resolvePromise;
  35294. let rejectPromise;
  35295. const promise = newPromise((resolve2, reject) => {
  35296. resolvePromise = resolve2;
  35297. rejectPromise = reject;
  35298. });
  35299. const readRequest = {
  35300. _chunkSteps: (chunk) => {
  35301. this._ongoingPromise = void 0;
  35302. _queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
  35303. },
  35304. _closeSteps: () => {
  35305. this._ongoingPromise = void 0;
  35306. this._isFinished = true;
  35307. ReadableStreamReaderGenericRelease(reader);
  35308. resolvePromise({ value: void 0, done: true });
  35309. },
  35310. _errorSteps: (reason) => {
  35311. this._ongoingPromise = void 0;
  35312. this._isFinished = true;
  35313. ReadableStreamReaderGenericRelease(reader);
  35314. rejectPromise(reason);
  35315. }
  35316. };
  35317. ReadableStreamDefaultReaderRead(reader, readRequest);
  35318. return promise;
  35319. }
  35320. _returnSteps(value) {
  35321. if (this._isFinished) {
  35322. return Promise.resolve({ value, done: true });
  35323. }
  35324. this._isFinished = true;
  35325. const reader = this._reader;
  35326. if (!this._preventCancel) {
  35327. const result = ReadableStreamReaderGenericCancel(reader, value);
  35328. ReadableStreamReaderGenericRelease(reader);
  35329. return transformPromiseWith(result, () => ({ value, done: true }));
  35330. }
  35331. ReadableStreamReaderGenericRelease(reader);
  35332. return promiseResolvedWith({ value, done: true });
  35333. }
  35334. }
  35335. const ReadableStreamAsyncIteratorPrototype = {
  35336. next() {
  35337. if (!IsReadableStreamAsyncIterator(this)) {
  35338. return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next"));
  35339. }
  35340. return this._asyncIteratorImpl.next();
  35341. },
  35342. return(value) {
  35343. if (!IsReadableStreamAsyncIterator(this)) {
  35344. return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return"));
  35345. }
  35346. return this._asyncIteratorImpl.return(value);
  35347. }
  35348. };
  35349. Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
  35350. function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
  35351. const reader = AcquireReadableStreamDefaultReader(stream);
  35352. const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
  35353. const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
  35354. iterator._asyncIteratorImpl = impl;
  35355. return iterator;
  35356. }
  35357. function IsReadableStreamAsyncIterator(x4) {
  35358. if (!typeIsObject(x4)) {
  35359. return false;
  35360. }
  35361. if (!Object.prototype.hasOwnProperty.call(x4, "_asyncIteratorImpl")) {
  35362. return false;
  35363. }
  35364. try {
  35365. return x4._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl;
  35366. } catch (_a3) {
  35367. return false;
  35368. }
  35369. }
  35370. function streamAsyncIteratorBrandCheckException(name) {
  35371. return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
  35372. }
  35373. const NumberIsNaN = Number.isNaN || function(x4) {
  35374. return x4 !== x4;
  35375. };
  35376. var _a2, _b, _c;
  35377. function CreateArrayFromList(elements) {
  35378. return elements.slice();
  35379. }
  35380. function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n3) {
  35381. new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n3), destOffset);
  35382. }
  35383. let TransferArrayBuffer = (O) => {
  35384. if (typeof O.transfer === "function") {
  35385. TransferArrayBuffer = (buffer) => buffer.transfer();
  35386. } else if (typeof structuredClone === "function") {
  35387. TransferArrayBuffer = (buffer) => structuredClone(buffer, { transfer: [buffer] });
  35388. } else {
  35389. TransferArrayBuffer = (buffer) => buffer;
  35390. }
  35391. return TransferArrayBuffer(O);
  35392. };
  35393. let IsDetachedBuffer = (O) => {
  35394. if (typeof O.detached === "boolean") {
  35395. IsDetachedBuffer = (buffer) => buffer.detached;
  35396. } else {
  35397. IsDetachedBuffer = (buffer) => buffer.byteLength === 0;
  35398. }
  35399. return IsDetachedBuffer(O);
  35400. };
  35401. function ArrayBufferSlice(buffer, begin, end) {
  35402. if (buffer.slice) {
  35403. return buffer.slice(begin, end);
  35404. }
  35405. const length = end - begin;
  35406. const slice = new ArrayBuffer(length);
  35407. CopyDataBlockBytes(slice, 0, buffer, begin, length);
  35408. return slice;
  35409. }
  35410. function GetMethod(receiver, prop) {
  35411. const func = receiver[prop];
  35412. if (func === void 0 || func === null) {
  35413. return void 0;
  35414. }
  35415. if (typeof func !== "function") {
  35416. throw new TypeError(`${String(prop)} is not a function`);
  35417. }
  35418. return func;
  35419. }
  35420. function CreateAsyncFromSyncIterator(syncIteratorRecord) {
  35421. const syncIterable = {
  35422. [Symbol.iterator]: () => syncIteratorRecord.iterator
  35423. };
  35424. const asyncIterator = async function* () {
  35425. return yield* syncIterable;
  35426. }();
  35427. const nextMethod = asyncIterator.next;
  35428. return { iterator: asyncIterator, nextMethod, done: false };
  35429. }
  35430. const SymbolAsyncIterator = (_c = (_a2 = Symbol.asyncIterator) !== null && _a2 !== void 0 ? _a2 : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, "Symbol.asyncIterator")) !== null && _c !== void 0 ? _c : "@@asyncIterator";
  35431. function GetIterator(obj, hint = "sync", method) {
  35432. if (method === void 0) {
  35433. if (hint === "async") {
  35434. method = GetMethod(obj, SymbolAsyncIterator);
  35435. if (method === void 0) {
  35436. const syncMethod = GetMethod(obj, Symbol.iterator);
  35437. const syncIteratorRecord = GetIterator(obj, "sync", syncMethod);
  35438. return CreateAsyncFromSyncIterator(syncIteratorRecord);
  35439. }
  35440. } else {
  35441. method = GetMethod(obj, Symbol.iterator);
  35442. }
  35443. }
  35444. if (method === void 0) {
  35445. throw new TypeError("The object is not iterable");
  35446. }
  35447. const iterator = reflectCall(method, obj, []);
  35448. if (!typeIsObject(iterator)) {
  35449. throw new TypeError("The iterator method must return an object");
  35450. }
  35451. const nextMethod = iterator.next;
  35452. return { iterator, nextMethod, done: false };
  35453. }
  35454. function IteratorNext(iteratorRecord) {
  35455. const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
  35456. if (!typeIsObject(result)) {
  35457. throw new TypeError("The iterator.next() method must return an object");
  35458. }
  35459. return result;
  35460. }
  35461. function IteratorComplete(iterResult) {
  35462. return Boolean(iterResult.done);
  35463. }
  35464. function IteratorValue(iterResult) {
  35465. return iterResult.value;
  35466. }
  35467. function IsNonNegativeNumber(v6) {
  35468. if (typeof v6 !== "number") {
  35469. return false;
  35470. }
  35471. if (NumberIsNaN(v6)) {
  35472. return false;
  35473. }
  35474. if (v6 < 0) {
  35475. return false;
  35476. }
  35477. return true;
  35478. }
  35479. function CloneAsUint8Array(O) {
  35480. const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);
  35481. return new Uint8Array(buffer);
  35482. }
  35483. function DequeueValue(container) {
  35484. const pair = container._queue.shift();
  35485. container._queueTotalSize -= pair.size;
  35486. if (container._queueTotalSize < 0) {
  35487. container._queueTotalSize = 0;
  35488. }
  35489. return pair.value;
  35490. }
  35491. function EnqueueValueWithSize(container, value, size) {
  35492. if (!IsNonNegativeNumber(size) || size === Infinity) {
  35493. throw new RangeError("Size must be a finite, non-NaN, non-negative number.");
  35494. }
  35495. container._queue.push({ value, size });
  35496. container._queueTotalSize += size;
  35497. }
  35498. function PeekQueueValue(container) {
  35499. const pair = container._queue.peek();
  35500. return pair.value;
  35501. }
  35502. function ResetQueue(container) {
  35503. container._queue = new SimpleQueue();
  35504. container._queueTotalSize = 0;
  35505. }
  35506. function isDataViewConstructor(ctor) {
  35507. return ctor === DataView;
  35508. }
  35509. function isDataView(view5) {
  35510. return isDataViewConstructor(view5.constructor);
  35511. }
  35512. function arrayBufferViewElementSize(ctor) {
  35513. if (isDataViewConstructor(ctor)) {
  35514. return 1;
  35515. }
  35516. return ctor.BYTES_PER_ELEMENT;
  35517. }
  35518. class ReadableStreamBYOBRequest {
  35519. constructor() {
  35520. throw new TypeError("Illegal constructor");
  35521. }
  35522. /**
  35523. * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
  35524. */
  35525. get view() {
  35526. if (!IsReadableStreamBYOBRequest(this)) {
  35527. throw byobRequestBrandCheckException("view");
  35528. }
  35529. return this._view;
  35530. }
  35531. respond(bytesWritten) {
  35532. if (!IsReadableStreamBYOBRequest(this)) {
  35533. throw byobRequestBrandCheckException("respond");
  35534. }
  35535. assertRequiredArgument(bytesWritten, 1, "respond");
  35536. bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter");
  35537. if (this._associatedReadableByteStreamController === void 0) {
  35538. throw new TypeError("This BYOB request has been invalidated");
  35539. }
  35540. if (IsDetachedBuffer(this._view.buffer)) {
  35541. throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
  35542. }
  35543. ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
  35544. }
  35545. respondWithNewView(view5) {
  35546. if (!IsReadableStreamBYOBRequest(this)) {
  35547. throw byobRequestBrandCheckException("respondWithNewView");
  35548. }
  35549. assertRequiredArgument(view5, 1, "respondWithNewView");
  35550. if (!ArrayBuffer.isView(view5)) {
  35551. throw new TypeError("You can only respond with array buffer views");
  35552. }
  35553. if (this._associatedReadableByteStreamController === void 0) {
  35554. throw new TypeError("This BYOB request has been invalidated");
  35555. }
  35556. if (IsDetachedBuffer(view5.buffer)) {
  35557. throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");
  35558. }
  35559. ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view5);
  35560. }
  35561. }
  35562. Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
  35563. respond: { enumerable: true },
  35564. respondWithNewView: { enumerable: true },
  35565. view: { enumerable: true }
  35566. });
  35567. setFunctionName(ReadableStreamBYOBRequest.prototype.respond, "respond");
  35568. setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, "respondWithNewView");
  35569. if (typeof Symbol.toStringTag === "symbol") {
  35570. Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {
  35571. value: "ReadableStreamBYOBRequest",
  35572. configurable: true
  35573. });
  35574. }
  35575. class ReadableByteStreamController {
  35576. constructor() {
  35577. throw new TypeError("Illegal constructor");
  35578. }
  35579. /**
  35580. * Returns the current BYOB pull request, or `null` if there isn't one.
  35581. */
  35582. get byobRequest() {
  35583. if (!IsReadableByteStreamController(this)) {
  35584. throw byteStreamControllerBrandCheckException("byobRequest");
  35585. }
  35586. return ReadableByteStreamControllerGetBYOBRequest(this);
  35587. }
  35588. /**
  35589. * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
  35590. * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
  35591. */
  35592. get desiredSize() {
  35593. if (!IsReadableByteStreamController(this)) {
  35594. throw byteStreamControllerBrandCheckException("desiredSize");
  35595. }
  35596. return ReadableByteStreamControllerGetDesiredSize(this);
  35597. }
  35598. /**
  35599. * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
  35600. * the stream, but once those are read, the stream will become closed.
  35601. */
  35602. close() {
  35603. if (!IsReadableByteStreamController(this)) {
  35604. throw byteStreamControllerBrandCheckException("close");
  35605. }
  35606. if (this._closeRequested) {
  35607. throw new TypeError("The stream has already been closed; do not close it again!");
  35608. }
  35609. const state2 = this._controlledReadableByteStream._state;
  35610. if (state2 !== "readable") {
  35611. throw new TypeError(`The stream (in ${state2} state) is not in the readable state and cannot be closed`);
  35612. }
  35613. ReadableByteStreamControllerClose(this);
  35614. }
  35615. enqueue(chunk) {
  35616. if (!IsReadableByteStreamController(this)) {
  35617. throw byteStreamControllerBrandCheckException("enqueue");
  35618. }
  35619. assertRequiredArgument(chunk, 1, "enqueue");
  35620. if (!ArrayBuffer.isView(chunk)) {
  35621. throw new TypeError("chunk must be an array buffer view");
  35622. }
  35623. if (chunk.byteLength === 0) {
  35624. throw new TypeError("chunk must have non-zero byteLength");
  35625. }
  35626. if (chunk.buffer.byteLength === 0) {
  35627. throw new TypeError(`chunk's buffer must have non-zero byteLength`);
  35628. }
  35629. if (this._closeRequested) {
  35630. throw new TypeError("stream is closed or draining");
  35631. }
  35632. const state2 = this._controlledReadableByteStream._state;
  35633. if (state2 !== "readable") {
  35634. throw new TypeError(`The stream (in ${state2} state) is not in the readable state and cannot be enqueued to`);
  35635. }
  35636. ReadableByteStreamControllerEnqueue(this, chunk);
  35637. }
  35638. /**
  35639. * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
  35640. */
  35641. error(e4 = void 0) {
  35642. if (!IsReadableByteStreamController(this)) {
  35643. throw byteStreamControllerBrandCheckException("error");
  35644. }
  35645. ReadableByteStreamControllerError(this, e4);
  35646. }
  35647. /** @internal */
  35648. [CancelSteps](reason) {
  35649. ReadableByteStreamControllerClearPendingPullIntos(this);
  35650. ResetQueue(this);
  35651. const result = this._cancelAlgorithm(reason);
  35652. ReadableByteStreamControllerClearAlgorithms(this);
  35653. return result;
  35654. }
  35655. /** @internal */
  35656. [PullSteps](readRequest) {
  35657. const stream = this._controlledReadableByteStream;
  35658. if (this._queueTotalSize > 0) {
  35659. ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
  35660. return;
  35661. }
  35662. const autoAllocateChunkSize = this._autoAllocateChunkSize;
  35663. if (autoAllocateChunkSize !== void 0) {
  35664. let buffer;
  35665. try {
  35666. buffer = new ArrayBuffer(autoAllocateChunkSize);
  35667. } catch (bufferE) {
  35668. readRequest._errorSteps(bufferE);
  35669. return;
  35670. }
  35671. const pullIntoDescriptor = {
  35672. buffer,
  35673. bufferByteLength: autoAllocateChunkSize,
  35674. byteOffset: 0,
  35675. byteLength: autoAllocateChunkSize,
  35676. bytesFilled: 0,
  35677. minimumFill: 1,
  35678. elementSize: 1,
  35679. viewConstructor: Uint8Array,
  35680. readerType: "default"
  35681. };
  35682. this._pendingPullIntos.push(pullIntoDescriptor);
  35683. }
  35684. ReadableStreamAddReadRequest(stream, readRequest);
  35685. ReadableByteStreamControllerCallPullIfNeeded(this);
  35686. }
  35687. /** @internal */
  35688. [ReleaseSteps]() {
  35689. if (this._pendingPullIntos.length > 0) {
  35690. const firstPullInto = this._pendingPullIntos.peek();
  35691. firstPullInto.readerType = "none";
  35692. this._pendingPullIntos = new SimpleQueue();
  35693. this._pendingPullIntos.push(firstPullInto);
  35694. }
  35695. }
  35696. }
  35697. Object.defineProperties(ReadableByteStreamController.prototype, {
  35698. close: { enumerable: true },
  35699. enqueue: { enumerable: true },
  35700. error: { enumerable: true },
  35701. byobRequest: { enumerable: true },
  35702. desiredSize: { enumerable: true }
  35703. });
  35704. setFunctionName(ReadableByteStreamController.prototype.close, "close");
  35705. setFunctionName(ReadableByteStreamController.prototype.enqueue, "enqueue");
  35706. setFunctionName(ReadableByteStreamController.prototype.error, "error");
  35707. if (typeof Symbol.toStringTag === "symbol") {
  35708. Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {
  35709. value: "ReadableByteStreamController",
  35710. configurable: true
  35711. });
  35712. }
  35713. function IsReadableByteStreamController(x4) {
  35714. if (!typeIsObject(x4)) {
  35715. return false;
  35716. }
  35717. if (!Object.prototype.hasOwnProperty.call(x4, "_controlledReadableByteStream")) {
  35718. return false;
  35719. }
  35720. return x4 instanceof ReadableByteStreamController;
  35721. }
  35722. function IsReadableStreamBYOBRequest(x4) {
  35723. if (!typeIsObject(x4)) {
  35724. return false;
  35725. }
  35726. if (!Object.prototype.hasOwnProperty.call(x4, "_associatedReadableByteStreamController")) {
  35727. return false;
  35728. }
  35729. return x4 instanceof ReadableStreamBYOBRequest;
  35730. }
  35731. function ReadableByteStreamControllerCallPullIfNeeded(controller) {
  35732. const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
  35733. if (!shouldPull) {
  35734. return;
  35735. }
  35736. if (controller._pulling) {
  35737. controller._pullAgain = true;
  35738. return;
  35739. }
  35740. controller._pulling = true;
  35741. const pullPromise = controller._pullAlgorithm();
  35742. uponPromise(pullPromise, () => {
  35743. controller._pulling = false;
  35744. if (controller._pullAgain) {
  35745. controller._pullAgain = false;
  35746. ReadableByteStreamControllerCallPullIfNeeded(controller);
  35747. }
  35748. return null;
  35749. }, (e4) => {
  35750. ReadableByteStreamControllerError(controller, e4);
  35751. return null;
  35752. });
  35753. }
  35754. function ReadableByteStreamControllerClearPendingPullIntos(controller) {
  35755. ReadableByteStreamControllerInvalidateBYOBRequest(controller);
  35756. controller._pendingPullIntos = new SimpleQueue();
  35757. }
  35758. function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
  35759. let done = false;
  35760. if (stream._state === "closed") {
  35761. done = true;
  35762. }
  35763. const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
  35764. if (pullIntoDescriptor.readerType === "default") {
  35765. ReadableStreamFulfillReadRequest(stream, filledView, done);
  35766. } else {
  35767. ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
  35768. }
  35769. }
  35770. function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
  35771. const bytesFilled = pullIntoDescriptor.bytesFilled;
  35772. const elementSize = pullIntoDescriptor.elementSize;
  35773. return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
  35774. }
  35775. function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
  35776. controller._queue.push({ buffer, byteOffset, byteLength });
  35777. controller._queueTotalSize += byteLength;
  35778. }
  35779. function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
  35780. let clonedChunk;
  35781. try {
  35782. clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
  35783. } catch (cloneE) {
  35784. ReadableByteStreamControllerError(controller, cloneE);
  35785. throw cloneE;
  35786. }
  35787. ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
  35788. }
  35789. function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
  35790. if (firstDescriptor.bytesFilled > 0) {
  35791. ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
  35792. }
  35793. ReadableByteStreamControllerShiftPendingPullInto(controller);
  35794. }
  35795. function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
  35796. const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
  35797. const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
  35798. let totalBytesToCopyRemaining = maxBytesToCopy;
  35799. let ready = false;
  35800. const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;
  35801. const maxAlignedBytes = maxBytesFilled - remainderBytes;
  35802. if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
  35803. totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
  35804. ready = true;
  35805. }
  35806. const queue = controller._queue;
  35807. while (totalBytesToCopyRemaining > 0) {
  35808. const headOfQueue = queue.peek();
  35809. const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
  35810. const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
  35811. CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
  35812. if (headOfQueue.byteLength === bytesToCopy) {
  35813. queue.shift();
  35814. } else {
  35815. headOfQueue.byteOffset += bytesToCopy;
  35816. headOfQueue.byteLength -= bytesToCopy;
  35817. }
  35818. controller._queueTotalSize -= bytesToCopy;
  35819. ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
  35820. totalBytesToCopyRemaining -= bytesToCopy;
  35821. }
  35822. return ready;
  35823. }
  35824. function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
  35825. pullIntoDescriptor.bytesFilled += size;
  35826. }
  35827. function ReadableByteStreamControllerHandleQueueDrain(controller) {
  35828. if (controller._queueTotalSize === 0 && controller._closeRequested) {
  35829. ReadableByteStreamControllerClearAlgorithms(controller);
  35830. ReadableStreamClose(controller._controlledReadableByteStream);
  35831. } else {
  35832. ReadableByteStreamControllerCallPullIfNeeded(controller);
  35833. }
  35834. }
  35835. function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
  35836. if (controller._byobRequest === null) {
  35837. return;
  35838. }
  35839. controller._byobRequest._associatedReadableByteStreamController = void 0;
  35840. controller._byobRequest._view = null;
  35841. controller._byobRequest = null;
  35842. }
  35843. function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
  35844. while (controller._pendingPullIntos.length > 0) {
  35845. if (controller._queueTotalSize === 0) {
  35846. return;
  35847. }
  35848. const pullIntoDescriptor = controller._pendingPullIntos.peek();
  35849. if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
  35850. ReadableByteStreamControllerShiftPendingPullInto(controller);
  35851. ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
  35852. }
  35853. }
  35854. }
  35855. function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
  35856. const reader = controller._controlledReadableByteStream._reader;
  35857. while (reader._readRequests.length > 0) {
  35858. if (controller._queueTotalSize === 0) {
  35859. return;
  35860. }
  35861. const readRequest = reader._readRequests.shift();
  35862. ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);
  35863. }
  35864. }
  35865. function ReadableByteStreamControllerPullInto(controller, view5, min, readIntoRequest) {
  35866. const stream = controller._controlledReadableByteStream;
  35867. const ctor = view5.constructor;
  35868. const elementSize = arrayBufferViewElementSize(ctor);
  35869. const { byteOffset, byteLength } = view5;
  35870. const minimumFill = min * elementSize;
  35871. let buffer;
  35872. try {
  35873. buffer = TransferArrayBuffer(view5.buffer);
  35874. } catch (e4) {
  35875. readIntoRequest._errorSteps(e4);
  35876. return;
  35877. }
  35878. const pullIntoDescriptor = {
  35879. buffer,
  35880. bufferByteLength: buffer.byteLength,
  35881. byteOffset,
  35882. byteLength,
  35883. bytesFilled: 0,
  35884. minimumFill,
  35885. elementSize,
  35886. viewConstructor: ctor,
  35887. readerType: "byob"
  35888. };
  35889. if (controller._pendingPullIntos.length > 0) {
  35890. controller._pendingPullIntos.push(pullIntoDescriptor);
  35891. ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
  35892. return;
  35893. }
  35894. if (stream._state === "closed") {
  35895. const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
  35896. readIntoRequest._closeSteps(emptyView);
  35897. return;
  35898. }
  35899. if (controller._queueTotalSize > 0) {
  35900. if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
  35901. const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
  35902. ReadableByteStreamControllerHandleQueueDrain(controller);
  35903. readIntoRequest._chunkSteps(filledView);
  35904. return;
  35905. }
  35906. if (controller._closeRequested) {
  35907. const e4 = new TypeError("Insufficient bytes to fill elements in the given buffer");
  35908. ReadableByteStreamControllerError(controller, e4);
  35909. readIntoRequest._errorSteps(e4);
  35910. return;
  35911. }
  35912. }
  35913. controller._pendingPullIntos.push(pullIntoDescriptor);
  35914. ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
  35915. ReadableByteStreamControllerCallPullIfNeeded(controller);
  35916. }
  35917. function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
  35918. if (firstDescriptor.readerType === "none") {
  35919. ReadableByteStreamControllerShiftPendingPullInto(controller);
  35920. }
  35921. const stream = controller._controlledReadableByteStream;
  35922. if (ReadableStreamHasBYOBReader(stream)) {
  35923. while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
  35924. const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
  35925. ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
  35926. }
  35927. }
  35928. }
  35929. function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
  35930. ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
  35931. if (pullIntoDescriptor.readerType === "none") {
  35932. ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
  35933. ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
  35934. return;
  35935. }
  35936. if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {
  35937. return;
  35938. }
  35939. ReadableByteStreamControllerShiftPendingPullInto(controller);
  35940. const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
  35941. if (remainderSize > 0) {
  35942. const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
  35943. ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
  35944. }
  35945. pullIntoDescriptor.bytesFilled -= remainderSize;
  35946. ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
  35947. ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
  35948. }
  35949. function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
  35950. const firstDescriptor = controller._pendingPullIntos.peek();
  35951. ReadableByteStreamControllerInvalidateBYOBRequest(controller);
  35952. const state2 = controller._controlledReadableByteStream._state;
  35953. if (state2 === "closed") {
  35954. ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
  35955. } else {
  35956. ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
  35957. }
  35958. ReadableByteStreamControllerCallPullIfNeeded(controller);
  35959. }
  35960. function ReadableByteStreamControllerShiftPendingPullInto(controller) {
  35961. const descriptor = controller._pendingPullIntos.shift();
  35962. return descriptor;
  35963. }
  35964. function ReadableByteStreamControllerShouldCallPull(controller) {
  35965. const stream = controller._controlledReadableByteStream;
  35966. if (stream._state !== "readable") {
  35967. return false;
  35968. }
  35969. if (controller._closeRequested) {
  35970. return false;
  35971. }
  35972. if (!controller._started) {
  35973. return false;
  35974. }
  35975. if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
  35976. return true;
  35977. }
  35978. if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
  35979. return true;
  35980. }
  35981. const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
  35982. if (desiredSize > 0) {
  35983. return true;
  35984. }
  35985. return false;
  35986. }
  35987. function ReadableByteStreamControllerClearAlgorithms(controller) {
  35988. controller._pullAlgorithm = void 0;
  35989. controller._cancelAlgorithm = void 0;
  35990. }
  35991. function ReadableByteStreamControllerClose(controller) {
  35992. const stream = controller._controlledReadableByteStream;
  35993. if (controller._closeRequested || stream._state !== "readable") {
  35994. return;
  35995. }
  35996. if (controller._queueTotalSize > 0) {
  35997. controller._closeRequested = true;
  35998. return;
  35999. }
  36000. if (controller._pendingPullIntos.length > 0) {
  36001. const firstPendingPullInto = controller._pendingPullIntos.peek();
  36002. if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
  36003. const e4 = new TypeError("Insufficient bytes to fill elements in the given buffer");
  36004. ReadableByteStreamControllerError(controller, e4);
  36005. throw e4;
  36006. }
  36007. }
  36008. ReadableByteStreamControllerClearAlgorithms(controller);
  36009. ReadableStreamClose(stream);
  36010. }
  36011. function ReadableByteStreamControllerEnqueue(controller, chunk) {
  36012. const stream = controller._controlledReadableByteStream;
  36013. if (controller._closeRequested || stream._state !== "readable") {
  36014. return;
  36015. }
  36016. const { buffer, byteOffset, byteLength } = chunk;
  36017. if (IsDetachedBuffer(buffer)) {
  36018. throw new TypeError("chunk's buffer is detached and so cannot be enqueued");
  36019. }
  36020. const transferredBuffer = TransferArrayBuffer(buffer);
  36021. if (controller._pendingPullIntos.length > 0) {
  36022. const firstPendingPullInto = controller._pendingPullIntos.peek();
  36023. if (IsDetachedBuffer(firstPendingPullInto.buffer)) {
  36024. throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");
  36025. }
  36026. ReadableByteStreamControllerInvalidateBYOBRequest(controller);
  36027. firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
  36028. if (firstPendingPullInto.readerType === "none") {
  36029. ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
  36030. }
  36031. }
  36032. if (ReadableStreamHasDefaultReader(stream)) {
  36033. ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
  36034. if (ReadableStreamGetNumReadRequests(stream) === 0) {
  36035. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
  36036. } else {
  36037. if (controller._pendingPullIntos.length > 0) {
  36038. ReadableByteStreamControllerShiftPendingPullInto(controller);
  36039. }
  36040. const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
  36041. ReadableStreamFulfillReadRequest(stream, transferredView, false);
  36042. }
  36043. } else if (ReadableStreamHasBYOBReader(stream)) {
  36044. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
  36045. ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
  36046. } else {
  36047. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
  36048. }
  36049. ReadableByteStreamControllerCallPullIfNeeded(controller);
  36050. }
  36051. function ReadableByteStreamControllerError(controller, e4) {
  36052. const stream = controller._controlledReadableByteStream;
  36053. if (stream._state !== "readable") {
  36054. return;
  36055. }
  36056. ReadableByteStreamControllerClearPendingPullIntos(controller);
  36057. ResetQueue(controller);
  36058. ReadableByteStreamControllerClearAlgorithms(controller);
  36059. ReadableStreamError(stream, e4);
  36060. }
  36061. function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
  36062. const entry = controller._queue.shift();
  36063. controller._queueTotalSize -= entry.byteLength;
  36064. ReadableByteStreamControllerHandleQueueDrain(controller);
  36065. const view5 = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
  36066. readRequest._chunkSteps(view5);
  36067. }
  36068. function ReadableByteStreamControllerGetBYOBRequest(controller) {
  36069. if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
  36070. const firstDescriptor = controller._pendingPullIntos.peek();
  36071. const view5 = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
  36072. const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
  36073. SetUpReadableStreamBYOBRequest(byobRequest, controller, view5);
  36074. controller._byobRequest = byobRequest;
  36075. }
  36076. return controller._byobRequest;
  36077. }
  36078. function ReadableByteStreamControllerGetDesiredSize(controller) {
  36079. const state2 = controller._controlledReadableByteStream._state;
  36080. if (state2 === "errored") {
  36081. return null;
  36082. }
  36083. if (state2 === "closed") {
  36084. return 0;
  36085. }
  36086. return controller._strategyHWM - controller._queueTotalSize;
  36087. }
  36088. function ReadableByteStreamControllerRespond(controller, bytesWritten) {
  36089. const firstDescriptor = controller._pendingPullIntos.peek();
  36090. const state2 = controller._controlledReadableByteStream._state;
  36091. if (state2 === "closed") {
  36092. if (bytesWritten !== 0) {
  36093. throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");
  36094. }
  36095. } else {
  36096. if (bytesWritten === 0) {
  36097. throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");
  36098. }
  36099. if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
  36100. throw new RangeError("bytesWritten out of range");
  36101. }
  36102. }
  36103. firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
  36104. ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
  36105. }
  36106. function ReadableByteStreamControllerRespondWithNewView(controller, view5) {
  36107. const firstDescriptor = controller._pendingPullIntos.peek();
  36108. const state2 = controller._controlledReadableByteStream._state;
  36109. if (state2 === "closed") {
  36110. if (view5.byteLength !== 0) {
  36111. throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream");
  36112. }
  36113. } else {
  36114. if (view5.byteLength === 0) {
  36115. throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");
  36116. }
  36117. }
  36118. if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view5.byteOffset) {
  36119. throw new RangeError("The region specified by view does not match byobRequest");
  36120. }
  36121. if (firstDescriptor.bufferByteLength !== view5.buffer.byteLength) {
  36122. throw new RangeError("The buffer of view has different capacity than byobRequest");
  36123. }
  36124. if (firstDescriptor.bytesFilled + view5.byteLength > firstDescriptor.byteLength) {
  36125. throw new RangeError("The region specified by view is larger than byobRequest");
  36126. }
  36127. const viewByteLength = view5.byteLength;
  36128. firstDescriptor.buffer = TransferArrayBuffer(view5.buffer);
  36129. ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
  36130. }
  36131. function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
  36132. controller._controlledReadableByteStream = stream;
  36133. controller._pullAgain = false;
  36134. controller._pulling = false;
  36135. controller._byobRequest = null;
  36136. controller._queue = controller._queueTotalSize = void 0;
  36137. ResetQueue(controller);
  36138. controller._closeRequested = false;
  36139. controller._started = false;
  36140. controller._strategyHWM = highWaterMark;
  36141. controller._pullAlgorithm = pullAlgorithm;
  36142. controller._cancelAlgorithm = cancelAlgorithm;
  36143. controller._autoAllocateChunkSize = autoAllocateChunkSize;
  36144. controller._pendingPullIntos = new SimpleQueue();
  36145. stream._readableStreamController = controller;
  36146. const startResult = startAlgorithm();
  36147. uponPromise(promiseResolvedWith(startResult), () => {
  36148. controller._started = true;
  36149. ReadableByteStreamControllerCallPullIfNeeded(controller);
  36150. return null;
  36151. }, (r4) => {
  36152. ReadableByteStreamControllerError(controller, r4);
  36153. return null;
  36154. });
  36155. }
  36156. function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
  36157. const controller = Object.create(ReadableByteStreamController.prototype);
  36158. let startAlgorithm;
  36159. let pullAlgorithm;
  36160. let cancelAlgorithm;
  36161. if (underlyingByteSource.start !== void 0) {
  36162. startAlgorithm = () => underlyingByteSource.start(controller);
  36163. } else {
  36164. startAlgorithm = () => void 0;
  36165. }
  36166. if (underlyingByteSource.pull !== void 0) {
  36167. pullAlgorithm = () => underlyingByteSource.pull(controller);
  36168. } else {
  36169. pullAlgorithm = () => promiseResolvedWith(void 0);
  36170. }
  36171. if (underlyingByteSource.cancel !== void 0) {
  36172. cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason);
  36173. } else {
  36174. cancelAlgorithm = () => promiseResolvedWith(void 0);
  36175. }
  36176. const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
  36177. if (autoAllocateChunkSize === 0) {
  36178. throw new TypeError("autoAllocateChunkSize must be greater than 0");
  36179. }
  36180. SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
  36181. }
  36182. function SetUpReadableStreamBYOBRequest(request, controller, view5) {
  36183. request._associatedReadableByteStreamController = controller;
  36184. request._view = view5;
  36185. }
  36186. function byobRequestBrandCheckException(name) {
  36187. return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
  36188. }
  36189. function byteStreamControllerBrandCheckException(name) {
  36190. return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
  36191. }
  36192. function convertReaderOptions(options, context) {
  36193. assertDictionary(options, context);
  36194. const mode = options === null || options === void 0 ? void 0 : options.mode;
  36195. return {
  36196. mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
  36197. };
  36198. }
  36199. function convertReadableStreamReaderMode(mode, context) {
  36200. mode = `${mode}`;
  36201. if (mode !== "byob") {
  36202. throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
  36203. }
  36204. return mode;
  36205. }
  36206. function convertByobReadOptions(options, context) {
  36207. var _a3;
  36208. assertDictionary(options, context);
  36209. const min = (_a3 = options === null || options === void 0 ? void 0 : options.min) !== null && _a3 !== void 0 ? _a3 : 1;
  36210. return {
  36211. min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`)
  36212. };
  36213. }
  36214. function AcquireReadableStreamBYOBReader(stream) {
  36215. return new ReadableStreamBYOBReader(stream);
  36216. }
  36217. function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
  36218. stream._reader._readIntoRequests.push(readIntoRequest);
  36219. }
  36220. function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
  36221. const reader = stream._reader;
  36222. const readIntoRequest = reader._readIntoRequests.shift();
  36223. if (done) {
  36224. readIntoRequest._closeSteps(chunk);
  36225. } else {
  36226. readIntoRequest._chunkSteps(chunk);
  36227. }
  36228. }
  36229. function ReadableStreamGetNumReadIntoRequests(stream) {
  36230. return stream._reader._readIntoRequests.length;
  36231. }
  36232. function ReadableStreamHasBYOBReader(stream) {
  36233. const reader = stream._reader;
  36234. if (reader === void 0) {
  36235. return false;
  36236. }
  36237. if (!IsReadableStreamBYOBReader(reader)) {
  36238. return false;
  36239. }
  36240. return true;
  36241. }
  36242. class ReadableStreamBYOBReader {
  36243. constructor(stream) {
  36244. assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader");
  36245. assertReadableStream(stream, "First parameter");
  36246. if (IsReadableStreamLocked(stream)) {
  36247. throw new TypeError("This stream has already been locked for exclusive reading by another reader");
  36248. }
  36249. if (!IsReadableByteStreamController(stream._readableStreamController)) {
  36250. throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");
  36251. }
  36252. ReadableStreamReaderGenericInitialize(this, stream);
  36253. this._readIntoRequests = new SimpleQueue();
  36254. }
  36255. /**
  36256. * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
  36257. * the reader's lock is released before the stream finishes closing.
  36258. */
  36259. get closed() {
  36260. if (!IsReadableStreamBYOBReader(this)) {
  36261. return promiseRejectedWith(byobReaderBrandCheckException("closed"));
  36262. }
  36263. return this._closedPromise;
  36264. }
  36265. /**
  36266. * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
  36267. */
  36268. cancel(reason = void 0) {
  36269. if (!IsReadableStreamBYOBReader(this)) {
  36270. return promiseRejectedWith(byobReaderBrandCheckException("cancel"));
  36271. }
  36272. if (this._ownerReadableStream === void 0) {
  36273. return promiseRejectedWith(readerLockException("cancel"));
  36274. }
  36275. return ReadableStreamReaderGenericCancel(this, reason);
  36276. }
  36277. read(view5, rawOptions = {}) {
  36278. if (!IsReadableStreamBYOBReader(this)) {
  36279. return promiseRejectedWith(byobReaderBrandCheckException("read"));
  36280. }
  36281. if (!ArrayBuffer.isView(view5)) {
  36282. return promiseRejectedWith(new TypeError("view must be an array buffer view"));
  36283. }
  36284. if (view5.byteLength === 0) {
  36285. return promiseRejectedWith(new TypeError("view must have non-zero byteLength"));
  36286. }
  36287. if (view5.buffer.byteLength === 0) {
  36288. return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
  36289. }
  36290. if (IsDetachedBuffer(view5.buffer)) {
  36291. return promiseRejectedWith(new TypeError("view's buffer has been detached"));
  36292. }
  36293. let options;
  36294. try {
  36295. options = convertByobReadOptions(rawOptions, "options");
  36296. } catch (e4) {
  36297. return promiseRejectedWith(e4);
  36298. }
  36299. const min = options.min;
  36300. if (min === 0) {
  36301. return promiseRejectedWith(new TypeError("options.min must be greater than 0"));
  36302. }
  36303. if (!isDataView(view5)) {
  36304. if (min > view5.length) {
  36305. return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's length"));
  36306. }
  36307. } else if (min > view5.byteLength) {
  36308. return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's byteLength"));
  36309. }
  36310. if (this._ownerReadableStream === void 0) {
  36311. return promiseRejectedWith(readerLockException("read from"));
  36312. }
  36313. let resolvePromise;
  36314. let rejectPromise;
  36315. const promise = newPromise((resolve2, reject) => {
  36316. resolvePromise = resolve2;
  36317. rejectPromise = reject;
  36318. });
  36319. const readIntoRequest = {
  36320. _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }),
  36321. _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }),
  36322. _errorSteps: (e4) => rejectPromise(e4)
  36323. };
  36324. ReadableStreamBYOBReaderRead(this, view5, min, readIntoRequest);
  36325. return promise;
  36326. }
  36327. /**
  36328. * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
  36329. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
  36330. * from now on; otherwise, the reader will appear closed.
  36331. *
  36332. * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
  36333. * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
  36334. * do so will throw a `TypeError` and leave the reader locked to the stream.
  36335. */
  36336. releaseLock() {
  36337. if (!IsReadableStreamBYOBReader(this)) {
  36338. throw byobReaderBrandCheckException("releaseLock");
  36339. }
  36340. if (this._ownerReadableStream === void 0) {
  36341. return;
  36342. }
  36343. ReadableStreamBYOBReaderRelease(this);
  36344. }
  36345. }
  36346. Object.defineProperties(ReadableStreamBYOBReader.prototype, {
  36347. cancel: { enumerable: true },
  36348. read: { enumerable: true },
  36349. releaseLock: { enumerable: true },
  36350. closed: { enumerable: true }
  36351. });
  36352. setFunctionName(ReadableStreamBYOBReader.prototype.cancel, "cancel");
  36353. setFunctionName(ReadableStreamBYOBReader.prototype.read, "read");
  36354. setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, "releaseLock");
  36355. if (typeof Symbol.toStringTag === "symbol") {
  36356. Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {
  36357. value: "ReadableStreamBYOBReader",
  36358. configurable: true
  36359. });
  36360. }
  36361. function IsReadableStreamBYOBReader(x4) {
  36362. if (!typeIsObject(x4)) {
  36363. return false;
  36364. }
  36365. if (!Object.prototype.hasOwnProperty.call(x4, "_readIntoRequests")) {
  36366. return false;
  36367. }
  36368. return x4 instanceof ReadableStreamBYOBReader;
  36369. }
  36370. function ReadableStreamBYOBReaderRead(reader, view5, min, readIntoRequest) {
  36371. const stream = reader._ownerReadableStream;
  36372. stream._disturbed = true;
  36373. if (stream._state === "errored") {
  36374. readIntoRequest._errorSteps(stream._storedError);
  36375. } else {
  36376. ReadableByteStreamControllerPullInto(stream._readableStreamController, view5, min, readIntoRequest);
  36377. }
  36378. }
  36379. function ReadableStreamBYOBReaderRelease(reader) {
  36380. ReadableStreamReaderGenericRelease(reader);
  36381. const e4 = new TypeError("Reader was released");
  36382. ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4);
  36383. }
  36384. function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4) {
  36385. const readIntoRequests = reader._readIntoRequests;
  36386. reader._readIntoRequests = new SimpleQueue();
  36387. readIntoRequests.forEach((readIntoRequest) => {
  36388. readIntoRequest._errorSteps(e4);
  36389. });
  36390. }
  36391. function byobReaderBrandCheckException(name) {
  36392. return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
  36393. }
  36394. function ExtractHighWaterMark(strategy, defaultHWM) {
  36395. const { highWaterMark } = strategy;
  36396. if (highWaterMark === void 0) {
  36397. return defaultHWM;
  36398. }
  36399. if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
  36400. throw new RangeError("Invalid highWaterMark");
  36401. }
  36402. return highWaterMark;
  36403. }
  36404. function ExtractSizeAlgorithm(strategy) {
  36405. const { size } = strategy;
  36406. if (!size) {
  36407. return () => 1;
  36408. }
  36409. return size;
  36410. }
  36411. function convertQueuingStrategy(init2, context) {
  36412. assertDictionary(init2, context);
  36413. const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark;
  36414. const size = init2 === null || init2 === void 0 ? void 0 : init2.size;
  36415. return {
  36416. highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark),
  36417. size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${context} has member 'size' that`)
  36418. };
  36419. }
  36420. function convertQueuingStrategySize(fn, context) {
  36421. assertFunction(fn, context);
  36422. return (chunk) => convertUnrestrictedDouble(fn(chunk));
  36423. }
  36424. function convertUnderlyingSink(original, context) {
  36425. assertDictionary(original, context);
  36426. const abort = original === null || original === void 0 ? void 0 : original.abort;
  36427. const close = original === null || original === void 0 ? void 0 : original.close;
  36428. const start = original === null || original === void 0 ? void 0 : original.start;
  36429. const type = original === null || original === void 0 ? void 0 : original.type;
  36430. const write = original === null || original === void 0 ? void 0 : original.write;
  36431. return {
  36432. abort: abort === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
  36433. close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
  36434. start: start === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
  36435. write: write === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
  36436. type
  36437. };
  36438. }
  36439. function convertUnderlyingSinkAbortCallback(fn, original, context) {
  36440. assertFunction(fn, context);
  36441. return (reason) => promiseCall(fn, original, [reason]);
  36442. }
  36443. function convertUnderlyingSinkCloseCallback(fn, original, context) {
  36444. assertFunction(fn, context);
  36445. return () => promiseCall(fn, original, []);
  36446. }
  36447. function convertUnderlyingSinkStartCallback(fn, original, context) {
  36448. assertFunction(fn, context);
  36449. return (controller) => reflectCall(fn, original, [controller]);
  36450. }
  36451. function convertUnderlyingSinkWriteCallback(fn, original, context) {
  36452. assertFunction(fn, context);
  36453. return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
  36454. }
  36455. function assertWritableStream(x4, context) {
  36456. if (!IsWritableStream(x4)) {
  36457. throw new TypeError(`${context} is not a WritableStream.`);
  36458. }
  36459. }
  36460. function isAbortSignal2(value) {
  36461. if (typeof value !== "object" || value === null) {
  36462. return false;
  36463. }
  36464. try {
  36465. return typeof value.aborted === "boolean";
  36466. } catch (_a3) {
  36467. return false;
  36468. }
  36469. }
  36470. const supportsAbortController = typeof AbortController === "function";
  36471. function createAbortController() {
  36472. if (supportsAbortController) {
  36473. return new AbortController();
  36474. }
  36475. return void 0;
  36476. }
  36477. class WritableStream {
  36478. constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
  36479. if (rawUnderlyingSink === void 0) {
  36480. rawUnderlyingSink = null;
  36481. } else {
  36482. assertObject(rawUnderlyingSink, "First parameter");
  36483. }
  36484. const strategy = convertQueuingStrategy(rawStrategy, "Second parameter");
  36485. const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter");
  36486. InitializeWritableStream(this);
  36487. const type = underlyingSink.type;
  36488. if (type !== void 0) {
  36489. throw new RangeError("Invalid type is specified");
  36490. }
  36491. const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
  36492. const highWaterMark = ExtractHighWaterMark(strategy, 1);
  36493. SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
  36494. }
  36495. /**
  36496. * Returns whether or not the writable stream is locked to a writer.
  36497. */
  36498. get locked() {
  36499. if (!IsWritableStream(this)) {
  36500. throw streamBrandCheckException$2("locked");
  36501. }
  36502. return IsWritableStreamLocked(this);
  36503. }
  36504. /**
  36505. * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
  36506. * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
  36507. * mechanism of the underlying sink.
  36508. *
  36509. * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
  36510. * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
  36511. * the stream) if the stream is currently locked.
  36512. */
  36513. abort(reason = void 0) {
  36514. if (!IsWritableStream(this)) {
  36515. return promiseRejectedWith(streamBrandCheckException$2("abort"));
  36516. }
  36517. if (IsWritableStreamLocked(this)) {
  36518. return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer"));
  36519. }
  36520. return WritableStreamAbort(this, reason);
  36521. }
  36522. /**
  36523. * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
  36524. * close behavior. During this time any further attempts to write will fail (without erroring the stream).
  36525. *
  36526. * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
  36527. * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
  36528. * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
  36529. */
  36530. close() {
  36531. if (!IsWritableStream(this)) {
  36532. return promiseRejectedWith(streamBrandCheckException$2("close"));
  36533. }
  36534. if (IsWritableStreamLocked(this)) {
  36535. return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer"));
  36536. }
  36537. if (WritableStreamCloseQueuedOrInFlight(this)) {
  36538. return promiseRejectedWith(new TypeError("Cannot close an already-closing stream"));
  36539. }
  36540. return WritableStreamClose(this);
  36541. }
  36542. /**
  36543. * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
  36544. * is locked, no other writer can be acquired until this one is released.
  36545. *
  36546. * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
  36547. * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
  36548. * the same time, which would cause the resulting written data to be unpredictable and probably useless.
  36549. */
  36550. getWriter() {
  36551. if (!IsWritableStream(this)) {
  36552. throw streamBrandCheckException$2("getWriter");
  36553. }
  36554. return AcquireWritableStreamDefaultWriter(this);
  36555. }
  36556. }
  36557. Object.defineProperties(WritableStream.prototype, {
  36558. abort: { enumerable: true },
  36559. close: { enumerable: true },
  36560. getWriter: { enumerable: true },
  36561. locked: { enumerable: true }
  36562. });
  36563. setFunctionName(WritableStream.prototype.abort, "abort");
  36564. setFunctionName(WritableStream.prototype.close, "close");
  36565. setFunctionName(WritableStream.prototype.getWriter, "getWriter");
  36566. if (typeof Symbol.toStringTag === "symbol") {
  36567. Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {
  36568. value: "WritableStream",
  36569. configurable: true
  36570. });
  36571. }
  36572. function AcquireWritableStreamDefaultWriter(stream) {
  36573. return new WritableStreamDefaultWriter(stream);
  36574. }
  36575. function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
  36576. const stream = Object.create(WritableStream.prototype);
  36577. InitializeWritableStream(stream);
  36578. const controller = Object.create(WritableStreamDefaultController.prototype);
  36579. SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
  36580. return stream;
  36581. }
  36582. function InitializeWritableStream(stream) {
  36583. stream._state = "writable";
  36584. stream._storedError = void 0;
  36585. stream._writer = void 0;
  36586. stream._writableStreamController = void 0;
  36587. stream._writeRequests = new SimpleQueue();
  36588. stream._inFlightWriteRequest = void 0;
  36589. stream._closeRequest = void 0;
  36590. stream._inFlightCloseRequest = void 0;
  36591. stream._pendingAbortRequest = void 0;
  36592. stream._backpressure = false;
  36593. }
  36594. function IsWritableStream(x4) {
  36595. if (!typeIsObject(x4)) {
  36596. return false;
  36597. }
  36598. if (!Object.prototype.hasOwnProperty.call(x4, "_writableStreamController")) {
  36599. return false;
  36600. }
  36601. return x4 instanceof WritableStream;
  36602. }
  36603. function IsWritableStreamLocked(stream) {
  36604. if (stream._writer === void 0) {
  36605. return false;
  36606. }
  36607. return true;
  36608. }
  36609. function WritableStreamAbort(stream, reason) {
  36610. var _a3;
  36611. if (stream._state === "closed" || stream._state === "errored") {
  36612. return promiseResolvedWith(void 0);
  36613. }
  36614. stream._writableStreamController._abortReason = reason;
  36615. (_a3 = stream._writableStreamController._abortController) === null || _a3 === void 0 ? void 0 : _a3.abort(reason);
  36616. const state2 = stream._state;
  36617. if (state2 === "closed" || state2 === "errored") {
  36618. return promiseResolvedWith(void 0);
  36619. }
  36620. if (stream._pendingAbortRequest !== void 0) {
  36621. return stream._pendingAbortRequest._promise;
  36622. }
  36623. let wasAlreadyErroring = false;
  36624. if (state2 === "erroring") {
  36625. wasAlreadyErroring = true;
  36626. reason = void 0;
  36627. }
  36628. const promise = newPromise((resolve2, reject) => {
  36629. stream._pendingAbortRequest = {
  36630. _promise: void 0,
  36631. _resolve: resolve2,
  36632. _reject: reject,
  36633. _reason: reason,
  36634. _wasAlreadyErroring: wasAlreadyErroring
  36635. };
  36636. });
  36637. stream._pendingAbortRequest._promise = promise;
  36638. if (!wasAlreadyErroring) {
  36639. WritableStreamStartErroring(stream, reason);
  36640. }
  36641. return promise;
  36642. }
  36643. function WritableStreamClose(stream) {
  36644. const state2 = stream._state;
  36645. if (state2 === "closed" || state2 === "errored") {
  36646. return promiseRejectedWith(new TypeError(`The stream (in ${state2} state) is not in the writable state and cannot be closed`));
  36647. }
  36648. const promise = newPromise((resolve2, reject) => {
  36649. const closeRequest = {
  36650. _resolve: resolve2,
  36651. _reject: reject
  36652. };
  36653. stream._closeRequest = closeRequest;
  36654. });
  36655. const writer = stream._writer;
  36656. if (writer !== void 0 && stream._backpressure && state2 === "writable") {
  36657. defaultWriterReadyPromiseResolve(writer);
  36658. }
  36659. WritableStreamDefaultControllerClose(stream._writableStreamController);
  36660. return promise;
  36661. }
  36662. function WritableStreamAddWriteRequest(stream) {
  36663. const promise = newPromise((resolve2, reject) => {
  36664. const writeRequest = {
  36665. _resolve: resolve2,
  36666. _reject: reject
  36667. };
  36668. stream._writeRequests.push(writeRequest);
  36669. });
  36670. return promise;
  36671. }
  36672. function WritableStreamDealWithRejection(stream, error2) {
  36673. const state2 = stream._state;
  36674. if (state2 === "writable") {
  36675. WritableStreamStartErroring(stream, error2);
  36676. return;
  36677. }
  36678. WritableStreamFinishErroring(stream);
  36679. }
  36680. function WritableStreamStartErroring(stream, reason) {
  36681. const controller = stream._writableStreamController;
  36682. stream._state = "erroring";
  36683. stream._storedError = reason;
  36684. const writer = stream._writer;
  36685. if (writer !== void 0) {
  36686. WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
  36687. }
  36688. if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
  36689. WritableStreamFinishErroring(stream);
  36690. }
  36691. }
  36692. function WritableStreamFinishErroring(stream) {
  36693. stream._state = "errored";
  36694. stream._writableStreamController[ErrorSteps]();
  36695. const storedError = stream._storedError;
  36696. stream._writeRequests.forEach((writeRequest) => {
  36697. writeRequest._reject(storedError);
  36698. });
  36699. stream._writeRequests = new SimpleQueue();
  36700. if (stream._pendingAbortRequest === void 0) {
  36701. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  36702. return;
  36703. }
  36704. const abortRequest = stream._pendingAbortRequest;
  36705. stream._pendingAbortRequest = void 0;
  36706. if (abortRequest._wasAlreadyErroring) {
  36707. abortRequest._reject(storedError);
  36708. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  36709. return;
  36710. }
  36711. const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
  36712. uponPromise(promise, () => {
  36713. abortRequest._resolve();
  36714. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  36715. return null;
  36716. }, (reason) => {
  36717. abortRequest._reject(reason);
  36718. WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
  36719. return null;
  36720. });
  36721. }
  36722. function WritableStreamFinishInFlightWrite(stream) {
  36723. stream._inFlightWriteRequest._resolve(void 0);
  36724. stream._inFlightWriteRequest = void 0;
  36725. }
  36726. function WritableStreamFinishInFlightWriteWithError(stream, error2) {
  36727. stream._inFlightWriteRequest._reject(error2);
  36728. stream._inFlightWriteRequest = void 0;
  36729. WritableStreamDealWithRejection(stream, error2);
  36730. }
  36731. function WritableStreamFinishInFlightClose(stream) {
  36732. stream._inFlightCloseRequest._resolve(void 0);
  36733. stream._inFlightCloseRequest = void 0;
  36734. const state2 = stream._state;
  36735. if (state2 === "erroring") {
  36736. stream._storedError = void 0;
  36737. if (stream._pendingAbortRequest !== void 0) {
  36738. stream._pendingAbortRequest._resolve();
  36739. stream._pendingAbortRequest = void 0;
  36740. }
  36741. }
  36742. stream._state = "closed";
  36743. const writer = stream._writer;
  36744. if (writer !== void 0) {
  36745. defaultWriterClosedPromiseResolve(writer);
  36746. }
  36747. }
  36748. function WritableStreamFinishInFlightCloseWithError(stream, error2) {
  36749. stream._inFlightCloseRequest._reject(error2);
  36750. stream._inFlightCloseRequest = void 0;
  36751. if (stream._pendingAbortRequest !== void 0) {
  36752. stream._pendingAbortRequest._reject(error2);
  36753. stream._pendingAbortRequest = void 0;
  36754. }
  36755. WritableStreamDealWithRejection(stream, error2);
  36756. }
  36757. function WritableStreamCloseQueuedOrInFlight(stream) {
  36758. if (stream._closeRequest === void 0 && stream._inFlightCloseRequest === void 0) {
  36759. return false;
  36760. }
  36761. return true;
  36762. }
  36763. function WritableStreamHasOperationMarkedInFlight(stream) {
  36764. if (stream._inFlightWriteRequest === void 0 && stream._inFlightCloseRequest === void 0) {
  36765. return false;
  36766. }
  36767. return true;
  36768. }
  36769. function WritableStreamMarkCloseRequestInFlight(stream) {
  36770. stream._inFlightCloseRequest = stream._closeRequest;
  36771. stream._closeRequest = void 0;
  36772. }
  36773. function WritableStreamMarkFirstWriteRequestInFlight(stream) {
  36774. stream._inFlightWriteRequest = stream._writeRequests.shift();
  36775. }
  36776. function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
  36777. if (stream._closeRequest !== void 0) {
  36778. stream._closeRequest._reject(stream._storedError);
  36779. stream._closeRequest = void 0;
  36780. }
  36781. const writer = stream._writer;
  36782. if (writer !== void 0) {
  36783. defaultWriterClosedPromiseReject(writer, stream._storedError);
  36784. }
  36785. }
  36786. function WritableStreamUpdateBackpressure(stream, backpressure) {
  36787. const writer = stream._writer;
  36788. if (writer !== void 0 && backpressure !== stream._backpressure) {
  36789. if (backpressure) {
  36790. defaultWriterReadyPromiseReset(writer);
  36791. } else {
  36792. defaultWriterReadyPromiseResolve(writer);
  36793. }
  36794. }
  36795. stream._backpressure = backpressure;
  36796. }
  36797. class WritableStreamDefaultWriter {
  36798. constructor(stream) {
  36799. assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter");
  36800. assertWritableStream(stream, "First parameter");
  36801. if (IsWritableStreamLocked(stream)) {
  36802. throw new TypeError("This stream has already been locked for exclusive writing by another writer");
  36803. }
  36804. this._ownerWritableStream = stream;
  36805. stream._writer = this;
  36806. const state2 = stream._state;
  36807. if (state2 === "writable") {
  36808. if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
  36809. defaultWriterReadyPromiseInitialize(this);
  36810. } else {
  36811. defaultWriterReadyPromiseInitializeAsResolved(this);
  36812. }
  36813. defaultWriterClosedPromiseInitialize(this);
  36814. } else if (state2 === "erroring") {
  36815. defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
  36816. defaultWriterClosedPromiseInitialize(this);
  36817. } else if (state2 === "closed") {
  36818. defaultWriterReadyPromiseInitializeAsResolved(this);
  36819. defaultWriterClosedPromiseInitializeAsResolved(this);
  36820. } else {
  36821. const storedError = stream._storedError;
  36822. defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
  36823. defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
  36824. }
  36825. }
  36826. /**
  36827. * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
  36828. * the writer’s lock is released before the stream finishes closing.
  36829. */
  36830. get closed() {
  36831. if (!IsWritableStreamDefaultWriter(this)) {
  36832. return promiseRejectedWith(defaultWriterBrandCheckException("closed"));
  36833. }
  36834. return this._closedPromise;
  36835. }
  36836. /**
  36837. * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
  36838. * A producer can use this information to determine the right amount of data to write.
  36839. *
  36840. * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
  36841. * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
  36842. * the writer’s lock is released.
  36843. */
  36844. get desiredSize() {
  36845. if (!IsWritableStreamDefaultWriter(this)) {
  36846. throw defaultWriterBrandCheckException("desiredSize");
  36847. }
  36848. if (this._ownerWritableStream === void 0) {
  36849. throw defaultWriterLockException("desiredSize");
  36850. }
  36851. return WritableStreamDefaultWriterGetDesiredSize(this);
  36852. }
  36853. /**
  36854. * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
  36855. * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
  36856. * back to zero or below, the getter will return a new promise that stays pending until the next transition.
  36857. *
  36858. * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
  36859. * rejected.
  36860. */
  36861. get ready() {
  36862. if (!IsWritableStreamDefaultWriter(this)) {
  36863. return promiseRejectedWith(defaultWriterBrandCheckException("ready"));
  36864. }
  36865. return this._readyPromise;
  36866. }
  36867. /**
  36868. * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
  36869. */
  36870. abort(reason = void 0) {
  36871. if (!IsWritableStreamDefaultWriter(this)) {
  36872. return promiseRejectedWith(defaultWriterBrandCheckException("abort"));
  36873. }
  36874. if (this._ownerWritableStream === void 0) {
  36875. return promiseRejectedWith(defaultWriterLockException("abort"));
  36876. }
  36877. return WritableStreamDefaultWriterAbort(this, reason);
  36878. }
  36879. /**
  36880. * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
  36881. */
  36882. close() {
  36883. if (!IsWritableStreamDefaultWriter(this)) {
  36884. return promiseRejectedWith(defaultWriterBrandCheckException("close"));
  36885. }
  36886. const stream = this._ownerWritableStream;
  36887. if (stream === void 0) {
  36888. return promiseRejectedWith(defaultWriterLockException("close"));
  36889. }
  36890. if (WritableStreamCloseQueuedOrInFlight(stream)) {
  36891. return promiseRejectedWith(new TypeError("Cannot close an already-closing stream"));
  36892. }
  36893. return WritableStreamDefaultWriterClose(this);
  36894. }
  36895. /**
  36896. * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
  36897. * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
  36898. * now on; otherwise, the writer will appear closed.
  36899. *
  36900. * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
  36901. * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
  36902. * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
  36903. * other producers from writing in an interleaved manner.
  36904. */
  36905. releaseLock() {
  36906. if (!IsWritableStreamDefaultWriter(this)) {
  36907. throw defaultWriterBrandCheckException("releaseLock");
  36908. }
  36909. const stream = this._ownerWritableStream;
  36910. if (stream === void 0) {
  36911. return;
  36912. }
  36913. WritableStreamDefaultWriterRelease(this);
  36914. }
  36915. write(chunk = void 0) {
  36916. if (!IsWritableStreamDefaultWriter(this)) {
  36917. return promiseRejectedWith(defaultWriterBrandCheckException("write"));
  36918. }
  36919. if (this._ownerWritableStream === void 0) {
  36920. return promiseRejectedWith(defaultWriterLockException("write to"));
  36921. }
  36922. return WritableStreamDefaultWriterWrite(this, chunk);
  36923. }
  36924. }
  36925. Object.defineProperties(WritableStreamDefaultWriter.prototype, {
  36926. abort: { enumerable: true },
  36927. close: { enumerable: true },
  36928. releaseLock: { enumerable: true },
  36929. write: { enumerable: true },
  36930. closed: { enumerable: true },
  36931. desiredSize: { enumerable: true },
  36932. ready: { enumerable: true }
  36933. });
  36934. setFunctionName(WritableStreamDefaultWriter.prototype.abort, "abort");
  36935. setFunctionName(WritableStreamDefaultWriter.prototype.close, "close");
  36936. setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, "releaseLock");
  36937. setFunctionName(WritableStreamDefaultWriter.prototype.write, "write");
  36938. if (typeof Symbol.toStringTag === "symbol") {
  36939. Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {
  36940. value: "WritableStreamDefaultWriter",
  36941. configurable: true
  36942. });
  36943. }
  36944. function IsWritableStreamDefaultWriter(x4) {
  36945. if (!typeIsObject(x4)) {
  36946. return false;
  36947. }
  36948. if (!Object.prototype.hasOwnProperty.call(x4, "_ownerWritableStream")) {
  36949. return false;
  36950. }
  36951. return x4 instanceof WritableStreamDefaultWriter;
  36952. }
  36953. function WritableStreamDefaultWriterAbort(writer, reason) {
  36954. const stream = writer._ownerWritableStream;
  36955. return WritableStreamAbort(stream, reason);
  36956. }
  36957. function WritableStreamDefaultWriterClose(writer) {
  36958. const stream = writer._ownerWritableStream;
  36959. return WritableStreamClose(stream);
  36960. }
  36961. function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
  36962. const stream = writer._ownerWritableStream;
  36963. const state2 = stream._state;
  36964. if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") {
  36965. return promiseResolvedWith(void 0);
  36966. }
  36967. if (state2 === "errored") {
  36968. return promiseRejectedWith(stream._storedError);
  36969. }
  36970. return WritableStreamDefaultWriterClose(writer);
  36971. }
  36972. function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error2) {
  36973. if (writer._closedPromiseState === "pending") {
  36974. defaultWriterClosedPromiseReject(writer, error2);
  36975. } else {
  36976. defaultWriterClosedPromiseResetToRejected(writer, error2);
  36977. }
  36978. }
  36979. function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error2) {
  36980. if (writer._readyPromiseState === "pending") {
  36981. defaultWriterReadyPromiseReject(writer, error2);
  36982. } else {
  36983. defaultWriterReadyPromiseResetToRejected(writer, error2);
  36984. }
  36985. }
  36986. function WritableStreamDefaultWriterGetDesiredSize(writer) {
  36987. const stream = writer._ownerWritableStream;
  36988. const state2 = stream._state;
  36989. if (state2 === "errored" || state2 === "erroring") {
  36990. return null;
  36991. }
  36992. if (state2 === "closed") {
  36993. return 0;
  36994. }
  36995. return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
  36996. }
  36997. function WritableStreamDefaultWriterRelease(writer) {
  36998. const stream = writer._ownerWritableStream;
  36999. const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
  37000. WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
  37001. WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
  37002. stream._writer = void 0;
  37003. writer._ownerWritableStream = void 0;
  37004. }
  37005. function WritableStreamDefaultWriterWrite(writer, chunk) {
  37006. const stream = writer._ownerWritableStream;
  37007. const controller = stream._writableStreamController;
  37008. const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
  37009. if (stream !== writer._ownerWritableStream) {
  37010. return promiseRejectedWith(defaultWriterLockException("write to"));
  37011. }
  37012. const state2 = stream._state;
  37013. if (state2 === "errored") {
  37014. return promiseRejectedWith(stream._storedError);
  37015. }
  37016. if (WritableStreamCloseQueuedOrInFlight(stream) || state2 === "closed") {
  37017. return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to"));
  37018. }
  37019. if (state2 === "erroring") {
  37020. return promiseRejectedWith(stream._storedError);
  37021. }
  37022. const promise = WritableStreamAddWriteRequest(stream);
  37023. WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
  37024. return promise;
  37025. }
  37026. const closeSentinel = {};
  37027. class WritableStreamDefaultController {
  37028. constructor() {
  37029. throw new TypeError("Illegal constructor");
  37030. }
  37031. /**
  37032. * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
  37033. *
  37034. * @deprecated
  37035. * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
  37036. * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
  37037. */
  37038. get abortReason() {
  37039. if (!IsWritableStreamDefaultController(this)) {
  37040. throw defaultControllerBrandCheckException$2("abortReason");
  37041. }
  37042. return this._abortReason;
  37043. }
  37044. /**
  37045. * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
  37046. */
  37047. get signal() {
  37048. if (!IsWritableStreamDefaultController(this)) {
  37049. throw defaultControllerBrandCheckException$2("signal");
  37050. }
  37051. if (this._abortController === void 0) {
  37052. throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");
  37053. }
  37054. return this._abortController.signal;
  37055. }
  37056. /**
  37057. * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
  37058. *
  37059. * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
  37060. * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
  37061. * normal lifecycle of interactions with the underlying sink.
  37062. */
  37063. error(e4 = void 0) {
  37064. if (!IsWritableStreamDefaultController(this)) {
  37065. throw defaultControllerBrandCheckException$2("error");
  37066. }
  37067. const state2 = this._controlledWritableStream._state;
  37068. if (state2 !== "writable") {
  37069. return;
  37070. }
  37071. WritableStreamDefaultControllerError(this, e4);
  37072. }
  37073. /** @internal */
  37074. [AbortSteps](reason) {
  37075. const result = this._abortAlgorithm(reason);
  37076. WritableStreamDefaultControllerClearAlgorithms(this);
  37077. return result;
  37078. }
  37079. /** @internal */
  37080. [ErrorSteps]() {
  37081. ResetQueue(this);
  37082. }
  37083. }
  37084. Object.defineProperties(WritableStreamDefaultController.prototype, {
  37085. abortReason: { enumerable: true },
  37086. signal: { enumerable: true },
  37087. error: { enumerable: true }
  37088. });
  37089. if (typeof Symbol.toStringTag === "symbol") {
  37090. Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {
  37091. value: "WritableStreamDefaultController",
  37092. configurable: true
  37093. });
  37094. }
  37095. function IsWritableStreamDefaultController(x4) {
  37096. if (!typeIsObject(x4)) {
  37097. return false;
  37098. }
  37099. if (!Object.prototype.hasOwnProperty.call(x4, "_controlledWritableStream")) {
  37100. return false;
  37101. }
  37102. return x4 instanceof WritableStreamDefaultController;
  37103. }
  37104. function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
  37105. controller._controlledWritableStream = stream;
  37106. stream._writableStreamController = controller;
  37107. controller._queue = void 0;
  37108. controller._queueTotalSize = void 0;
  37109. ResetQueue(controller);
  37110. controller._abortReason = void 0;
  37111. controller._abortController = createAbortController();
  37112. controller._started = false;
  37113. controller._strategySizeAlgorithm = sizeAlgorithm;
  37114. controller._strategyHWM = highWaterMark;
  37115. controller._writeAlgorithm = writeAlgorithm;
  37116. controller._closeAlgorithm = closeAlgorithm;
  37117. controller._abortAlgorithm = abortAlgorithm;
  37118. const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
  37119. WritableStreamUpdateBackpressure(stream, backpressure);
  37120. const startResult = startAlgorithm();
  37121. const startPromise = promiseResolvedWith(startResult);
  37122. uponPromise(startPromise, () => {
  37123. controller._started = true;
  37124. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  37125. return null;
  37126. }, (r4) => {
  37127. controller._started = true;
  37128. WritableStreamDealWithRejection(stream, r4);
  37129. return null;
  37130. });
  37131. }
  37132. function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
  37133. const controller = Object.create(WritableStreamDefaultController.prototype);
  37134. let startAlgorithm;
  37135. let writeAlgorithm;
  37136. let closeAlgorithm;
  37137. let abortAlgorithm;
  37138. if (underlyingSink.start !== void 0) {
  37139. startAlgorithm = () => underlyingSink.start(controller);
  37140. } else {
  37141. startAlgorithm = () => void 0;
  37142. }
  37143. if (underlyingSink.write !== void 0) {
  37144. writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller);
  37145. } else {
  37146. writeAlgorithm = () => promiseResolvedWith(void 0);
  37147. }
  37148. if (underlyingSink.close !== void 0) {
  37149. closeAlgorithm = () => underlyingSink.close();
  37150. } else {
  37151. closeAlgorithm = () => promiseResolvedWith(void 0);
  37152. }
  37153. if (underlyingSink.abort !== void 0) {
  37154. abortAlgorithm = (reason) => underlyingSink.abort(reason);
  37155. } else {
  37156. abortAlgorithm = () => promiseResolvedWith(void 0);
  37157. }
  37158. SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
  37159. }
  37160. function WritableStreamDefaultControllerClearAlgorithms(controller) {
  37161. controller._writeAlgorithm = void 0;
  37162. controller._closeAlgorithm = void 0;
  37163. controller._abortAlgorithm = void 0;
  37164. controller._strategySizeAlgorithm = void 0;
  37165. }
  37166. function WritableStreamDefaultControllerClose(controller) {
  37167. EnqueueValueWithSize(controller, closeSentinel, 0);
  37168. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  37169. }
  37170. function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
  37171. try {
  37172. return controller._strategySizeAlgorithm(chunk);
  37173. } catch (chunkSizeE) {
  37174. WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
  37175. return 1;
  37176. }
  37177. }
  37178. function WritableStreamDefaultControllerGetDesiredSize(controller) {
  37179. return controller._strategyHWM - controller._queueTotalSize;
  37180. }
  37181. function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
  37182. try {
  37183. EnqueueValueWithSize(controller, chunk, chunkSize);
  37184. } catch (enqueueE) {
  37185. WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
  37186. return;
  37187. }
  37188. const stream = controller._controlledWritableStream;
  37189. if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") {
  37190. const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
  37191. WritableStreamUpdateBackpressure(stream, backpressure);
  37192. }
  37193. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  37194. }
  37195. function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
  37196. const stream = controller._controlledWritableStream;
  37197. if (!controller._started) {
  37198. return;
  37199. }
  37200. if (stream._inFlightWriteRequest !== void 0) {
  37201. return;
  37202. }
  37203. const state2 = stream._state;
  37204. if (state2 === "erroring") {
  37205. WritableStreamFinishErroring(stream);
  37206. return;
  37207. }
  37208. if (controller._queue.length === 0) {
  37209. return;
  37210. }
  37211. const value = PeekQueueValue(controller);
  37212. if (value === closeSentinel) {
  37213. WritableStreamDefaultControllerProcessClose(controller);
  37214. } else {
  37215. WritableStreamDefaultControllerProcessWrite(controller, value);
  37216. }
  37217. }
  37218. function WritableStreamDefaultControllerErrorIfNeeded(controller, error2) {
  37219. if (controller._controlledWritableStream._state === "writable") {
  37220. WritableStreamDefaultControllerError(controller, error2);
  37221. }
  37222. }
  37223. function WritableStreamDefaultControllerProcessClose(controller) {
  37224. const stream = controller._controlledWritableStream;
  37225. WritableStreamMarkCloseRequestInFlight(stream);
  37226. DequeueValue(controller);
  37227. const sinkClosePromise = controller._closeAlgorithm();
  37228. WritableStreamDefaultControllerClearAlgorithms(controller);
  37229. uponPromise(sinkClosePromise, () => {
  37230. WritableStreamFinishInFlightClose(stream);
  37231. return null;
  37232. }, (reason) => {
  37233. WritableStreamFinishInFlightCloseWithError(stream, reason);
  37234. return null;
  37235. });
  37236. }
  37237. function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
  37238. const stream = controller._controlledWritableStream;
  37239. WritableStreamMarkFirstWriteRequestInFlight(stream);
  37240. const sinkWritePromise = controller._writeAlgorithm(chunk);
  37241. uponPromise(sinkWritePromise, () => {
  37242. WritableStreamFinishInFlightWrite(stream);
  37243. const state2 = stream._state;
  37244. DequeueValue(controller);
  37245. if (!WritableStreamCloseQueuedOrInFlight(stream) && state2 === "writable") {
  37246. const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
  37247. WritableStreamUpdateBackpressure(stream, backpressure);
  37248. }
  37249. WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
  37250. return null;
  37251. }, (reason) => {
  37252. if (stream._state === "writable") {
  37253. WritableStreamDefaultControllerClearAlgorithms(controller);
  37254. }
  37255. WritableStreamFinishInFlightWriteWithError(stream, reason);
  37256. return null;
  37257. });
  37258. }
  37259. function WritableStreamDefaultControllerGetBackpressure(controller) {
  37260. const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
  37261. return desiredSize <= 0;
  37262. }
  37263. function WritableStreamDefaultControllerError(controller, error2) {
  37264. const stream = controller._controlledWritableStream;
  37265. WritableStreamDefaultControllerClearAlgorithms(controller);
  37266. WritableStreamStartErroring(stream, error2);
  37267. }
  37268. function streamBrandCheckException$2(name) {
  37269. return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
  37270. }
  37271. function defaultControllerBrandCheckException$2(name) {
  37272. return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);
  37273. }
  37274. function defaultWriterBrandCheckException(name) {
  37275. return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
  37276. }
  37277. function defaultWriterLockException(name) {
  37278. return new TypeError("Cannot " + name + " a stream using a released writer");
  37279. }
  37280. function defaultWriterClosedPromiseInitialize(writer) {
  37281. writer._closedPromise = newPromise((resolve2, reject) => {
  37282. writer._closedPromise_resolve = resolve2;
  37283. writer._closedPromise_reject = reject;
  37284. writer._closedPromiseState = "pending";
  37285. });
  37286. }
  37287. function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
  37288. defaultWriterClosedPromiseInitialize(writer);
  37289. defaultWriterClosedPromiseReject(writer, reason);
  37290. }
  37291. function defaultWriterClosedPromiseInitializeAsResolved(writer) {
  37292. defaultWriterClosedPromiseInitialize(writer);
  37293. defaultWriterClosedPromiseResolve(writer);
  37294. }
  37295. function defaultWriterClosedPromiseReject(writer, reason) {
  37296. if (writer._closedPromise_reject === void 0) {
  37297. return;
  37298. }
  37299. setPromiseIsHandledToTrue(writer._closedPromise);
  37300. writer._closedPromise_reject(reason);
  37301. writer._closedPromise_resolve = void 0;
  37302. writer._closedPromise_reject = void 0;
  37303. writer._closedPromiseState = "rejected";
  37304. }
  37305. function defaultWriterClosedPromiseResetToRejected(writer, reason) {
  37306. defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
  37307. }
  37308. function defaultWriterClosedPromiseResolve(writer) {
  37309. if (writer._closedPromise_resolve === void 0) {
  37310. return;
  37311. }
  37312. writer._closedPromise_resolve(void 0);
  37313. writer._closedPromise_resolve = void 0;
  37314. writer._closedPromise_reject = void 0;
  37315. writer._closedPromiseState = "resolved";
  37316. }
  37317. function defaultWriterReadyPromiseInitialize(writer) {
  37318. writer._readyPromise = newPromise((resolve2, reject) => {
  37319. writer._readyPromise_resolve = resolve2;
  37320. writer._readyPromise_reject = reject;
  37321. });
  37322. writer._readyPromiseState = "pending";
  37323. }
  37324. function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
  37325. defaultWriterReadyPromiseInitialize(writer);
  37326. defaultWriterReadyPromiseReject(writer, reason);
  37327. }
  37328. function defaultWriterReadyPromiseInitializeAsResolved(writer) {
  37329. defaultWriterReadyPromiseInitialize(writer);
  37330. defaultWriterReadyPromiseResolve(writer);
  37331. }
  37332. function defaultWriterReadyPromiseReject(writer, reason) {
  37333. if (writer._readyPromise_reject === void 0) {
  37334. return;
  37335. }
  37336. setPromiseIsHandledToTrue(writer._readyPromise);
  37337. writer._readyPromise_reject(reason);
  37338. writer._readyPromise_resolve = void 0;
  37339. writer._readyPromise_reject = void 0;
  37340. writer._readyPromiseState = "rejected";
  37341. }
  37342. function defaultWriterReadyPromiseReset(writer) {
  37343. defaultWriterReadyPromiseInitialize(writer);
  37344. }
  37345. function defaultWriterReadyPromiseResetToRejected(writer, reason) {
  37346. defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
  37347. }
  37348. function defaultWriterReadyPromiseResolve(writer) {
  37349. if (writer._readyPromise_resolve === void 0) {
  37350. return;
  37351. }
  37352. writer._readyPromise_resolve(void 0);
  37353. writer._readyPromise_resolve = void 0;
  37354. writer._readyPromise_reject = void 0;
  37355. writer._readyPromiseState = "fulfilled";
  37356. }
  37357. function getGlobals() {
  37358. if (typeof globalThis !== "undefined") {
  37359. return globalThis;
  37360. } else if (typeof self !== "undefined") {
  37361. return self;
  37362. } else if (typeof global !== "undefined") {
  37363. return global;
  37364. }
  37365. return void 0;
  37366. }
  37367. const globals = getGlobals();
  37368. function isDOMExceptionConstructor(ctor) {
  37369. if (!(typeof ctor === "function" || typeof ctor === "object")) {
  37370. return false;
  37371. }
  37372. if (ctor.name !== "DOMException") {
  37373. return false;
  37374. }
  37375. try {
  37376. new ctor();
  37377. return true;
  37378. } catch (_a3) {
  37379. return false;
  37380. }
  37381. }
  37382. function getFromGlobal() {
  37383. const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
  37384. return isDOMExceptionConstructor(ctor) ? ctor : void 0;
  37385. }
  37386. function createPolyfill() {
  37387. const ctor = function DOMException3(message, name) {
  37388. this.message = message || "";
  37389. this.name = name || "Error";
  37390. if (Error.captureStackTrace) {
  37391. Error.captureStackTrace(this, this.constructor);
  37392. }
  37393. };
  37394. setFunctionName(ctor, "DOMException");
  37395. ctor.prototype = Object.create(Error.prototype);
  37396. Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true });
  37397. return ctor;
  37398. }
  37399. const DOMException2 = getFromGlobal() || createPolyfill();
  37400. function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
  37401. const reader = AcquireReadableStreamDefaultReader(source);
  37402. const writer = AcquireWritableStreamDefaultWriter(dest);
  37403. source._disturbed = true;
  37404. let shuttingDown = false;
  37405. let currentWrite = promiseResolvedWith(void 0);
  37406. return newPromise((resolve2, reject) => {
  37407. let abortAlgorithm;
  37408. if (signal !== void 0) {
  37409. abortAlgorithm = () => {
  37410. const error2 = signal.reason !== void 0 ? signal.reason : new DOMException2("Aborted", "AbortError");
  37411. const actions = [];
  37412. if (!preventAbort) {
  37413. actions.push(() => {
  37414. if (dest._state === "writable") {
  37415. return WritableStreamAbort(dest, error2);
  37416. }
  37417. return promiseResolvedWith(void 0);
  37418. });
  37419. }
  37420. if (!preventCancel) {
  37421. actions.push(() => {
  37422. if (source._state === "readable") {
  37423. return ReadableStreamCancel(source, error2);
  37424. }
  37425. return promiseResolvedWith(void 0);
  37426. });
  37427. }
  37428. shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error2);
  37429. };
  37430. if (signal.aborted) {
  37431. abortAlgorithm();
  37432. return;
  37433. }
  37434. signal.addEventListener("abort", abortAlgorithm);
  37435. }
  37436. function pipeLoop() {
  37437. return newPromise((resolveLoop, rejectLoop) => {
  37438. function next(done) {
  37439. if (done) {
  37440. resolveLoop();
  37441. } else {
  37442. PerformPromiseThen(pipeStep(), next, rejectLoop);
  37443. }
  37444. }
  37445. next(false);
  37446. });
  37447. }
  37448. function pipeStep() {
  37449. if (shuttingDown) {
  37450. return promiseResolvedWith(true);
  37451. }
  37452. return PerformPromiseThen(writer._readyPromise, () => {
  37453. return newPromise((resolveRead, rejectRead) => {
  37454. ReadableStreamDefaultReaderRead(reader, {
  37455. _chunkSteps: (chunk) => {
  37456. currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop2);
  37457. resolveRead(false);
  37458. },
  37459. _closeSteps: () => resolveRead(true),
  37460. _errorSteps: rejectRead
  37461. });
  37462. });
  37463. });
  37464. }
  37465. isOrBecomesErrored(source, reader._closedPromise, (storedError) => {
  37466. if (!preventAbort) {
  37467. shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
  37468. } else {
  37469. shutdown(true, storedError);
  37470. }
  37471. return null;
  37472. });
  37473. isOrBecomesErrored(dest, writer._closedPromise, (storedError) => {
  37474. if (!preventCancel) {
  37475. shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
  37476. } else {
  37477. shutdown(true, storedError);
  37478. }
  37479. return null;
  37480. });
  37481. isOrBecomesClosed(source, reader._closedPromise, () => {
  37482. if (!preventClose) {
  37483. shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
  37484. } else {
  37485. shutdown();
  37486. }
  37487. return null;
  37488. });
  37489. if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") {
  37490. const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it");
  37491. if (!preventCancel) {
  37492. shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
  37493. } else {
  37494. shutdown(true, destClosed);
  37495. }
  37496. }
  37497. setPromiseIsHandledToTrue(pipeLoop());
  37498. function waitForWritesToFinish() {
  37499. const oldCurrentWrite = currentWrite;
  37500. return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0);
  37501. }
  37502. function isOrBecomesErrored(stream, promise, action) {
  37503. if (stream._state === "errored") {
  37504. action(stream._storedError);
  37505. } else {
  37506. uponRejection(promise, action);
  37507. }
  37508. }
  37509. function isOrBecomesClosed(stream, promise, action) {
  37510. if (stream._state === "closed") {
  37511. action();
  37512. } else {
  37513. uponFulfillment(promise, action);
  37514. }
  37515. }
  37516. function shutdownWithAction(action, originalIsError, originalError) {
  37517. if (shuttingDown) {
  37518. return;
  37519. }
  37520. shuttingDown = true;
  37521. if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
  37522. uponFulfillment(waitForWritesToFinish(), doTheRest);
  37523. } else {
  37524. doTheRest();
  37525. }
  37526. function doTheRest() {
  37527. uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError));
  37528. return null;
  37529. }
  37530. }
  37531. function shutdown(isError, error2) {
  37532. if (shuttingDown) {
  37533. return;
  37534. }
  37535. shuttingDown = true;
  37536. if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
  37537. uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error2));
  37538. } else {
  37539. finalize(isError, error2);
  37540. }
  37541. }
  37542. function finalize(isError, error2) {
  37543. WritableStreamDefaultWriterRelease(writer);
  37544. ReadableStreamReaderGenericRelease(reader);
  37545. if (signal !== void 0) {
  37546. signal.removeEventListener("abort", abortAlgorithm);
  37547. }
  37548. if (isError) {
  37549. reject(error2);
  37550. } else {
  37551. resolve2(void 0);
  37552. }
  37553. return null;
  37554. }
  37555. });
  37556. }
  37557. class ReadableStreamDefaultController {
  37558. constructor() {
  37559. throw new TypeError("Illegal constructor");
  37560. }
  37561. /**
  37562. * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
  37563. * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
  37564. */
  37565. get desiredSize() {
  37566. if (!IsReadableStreamDefaultController(this)) {
  37567. throw defaultControllerBrandCheckException$1("desiredSize");
  37568. }
  37569. return ReadableStreamDefaultControllerGetDesiredSize(this);
  37570. }
  37571. /**
  37572. * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
  37573. * the stream, but once those are read, the stream will become closed.
  37574. */
  37575. close() {
  37576. if (!IsReadableStreamDefaultController(this)) {
  37577. throw defaultControllerBrandCheckException$1("close");
  37578. }
  37579. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
  37580. throw new TypeError("The stream is not in a state that permits close");
  37581. }
  37582. ReadableStreamDefaultControllerClose(this);
  37583. }
  37584. enqueue(chunk = void 0) {
  37585. if (!IsReadableStreamDefaultController(this)) {
  37586. throw defaultControllerBrandCheckException$1("enqueue");
  37587. }
  37588. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
  37589. throw new TypeError("The stream is not in a state that permits enqueue");
  37590. }
  37591. return ReadableStreamDefaultControllerEnqueue(this, chunk);
  37592. }
  37593. /**
  37594. * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
  37595. */
  37596. error(e4 = void 0) {
  37597. if (!IsReadableStreamDefaultController(this)) {
  37598. throw defaultControllerBrandCheckException$1("error");
  37599. }
  37600. ReadableStreamDefaultControllerError(this, e4);
  37601. }
  37602. /** @internal */
  37603. [CancelSteps](reason) {
  37604. ResetQueue(this);
  37605. const result = this._cancelAlgorithm(reason);
  37606. ReadableStreamDefaultControllerClearAlgorithms(this);
  37607. return result;
  37608. }
  37609. /** @internal */
  37610. [PullSteps](readRequest) {
  37611. const stream = this._controlledReadableStream;
  37612. if (this._queue.length > 0) {
  37613. const chunk = DequeueValue(this);
  37614. if (this._closeRequested && this._queue.length === 0) {
  37615. ReadableStreamDefaultControllerClearAlgorithms(this);
  37616. ReadableStreamClose(stream);
  37617. } else {
  37618. ReadableStreamDefaultControllerCallPullIfNeeded(this);
  37619. }
  37620. readRequest._chunkSteps(chunk);
  37621. } else {
  37622. ReadableStreamAddReadRequest(stream, readRequest);
  37623. ReadableStreamDefaultControllerCallPullIfNeeded(this);
  37624. }
  37625. }
  37626. /** @internal */
  37627. [ReleaseSteps]() {
  37628. }
  37629. }
  37630. Object.defineProperties(ReadableStreamDefaultController.prototype, {
  37631. close: { enumerable: true },
  37632. enqueue: { enumerable: true },
  37633. error: { enumerable: true },
  37634. desiredSize: { enumerable: true }
  37635. });
  37636. setFunctionName(ReadableStreamDefaultController.prototype.close, "close");
  37637. setFunctionName(ReadableStreamDefaultController.prototype.enqueue, "enqueue");
  37638. setFunctionName(ReadableStreamDefaultController.prototype.error, "error");
  37639. if (typeof Symbol.toStringTag === "symbol") {
  37640. Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {
  37641. value: "ReadableStreamDefaultController",
  37642. configurable: true
  37643. });
  37644. }
  37645. function IsReadableStreamDefaultController(x4) {
  37646. if (!typeIsObject(x4)) {
  37647. return false;
  37648. }
  37649. if (!Object.prototype.hasOwnProperty.call(x4, "_controlledReadableStream")) {
  37650. return false;
  37651. }
  37652. return x4 instanceof ReadableStreamDefaultController;
  37653. }
  37654. function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
  37655. const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
  37656. if (!shouldPull) {
  37657. return;
  37658. }
  37659. if (controller._pulling) {
  37660. controller._pullAgain = true;
  37661. return;
  37662. }
  37663. controller._pulling = true;
  37664. const pullPromise = controller._pullAlgorithm();
  37665. uponPromise(pullPromise, () => {
  37666. controller._pulling = false;
  37667. if (controller._pullAgain) {
  37668. controller._pullAgain = false;
  37669. ReadableStreamDefaultControllerCallPullIfNeeded(controller);
  37670. }
  37671. return null;
  37672. }, (e4) => {
  37673. ReadableStreamDefaultControllerError(controller, e4);
  37674. return null;
  37675. });
  37676. }
  37677. function ReadableStreamDefaultControllerShouldCallPull(controller) {
  37678. const stream = controller._controlledReadableStream;
  37679. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
  37680. return false;
  37681. }
  37682. if (!controller._started) {
  37683. return false;
  37684. }
  37685. if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
  37686. return true;
  37687. }
  37688. const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
  37689. if (desiredSize > 0) {
  37690. return true;
  37691. }
  37692. return false;
  37693. }
  37694. function ReadableStreamDefaultControllerClearAlgorithms(controller) {
  37695. controller._pullAlgorithm = void 0;
  37696. controller._cancelAlgorithm = void 0;
  37697. controller._strategySizeAlgorithm = void 0;
  37698. }
  37699. function ReadableStreamDefaultControllerClose(controller) {
  37700. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
  37701. return;
  37702. }
  37703. const stream = controller._controlledReadableStream;
  37704. controller._closeRequested = true;
  37705. if (controller._queue.length === 0) {
  37706. ReadableStreamDefaultControllerClearAlgorithms(controller);
  37707. ReadableStreamClose(stream);
  37708. }
  37709. }
  37710. function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
  37711. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
  37712. return;
  37713. }
  37714. const stream = controller._controlledReadableStream;
  37715. if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
  37716. ReadableStreamFulfillReadRequest(stream, chunk, false);
  37717. } else {
  37718. let chunkSize;
  37719. try {
  37720. chunkSize = controller._strategySizeAlgorithm(chunk);
  37721. } catch (chunkSizeE) {
  37722. ReadableStreamDefaultControllerError(controller, chunkSizeE);
  37723. throw chunkSizeE;
  37724. }
  37725. try {
  37726. EnqueueValueWithSize(controller, chunk, chunkSize);
  37727. } catch (enqueueE) {
  37728. ReadableStreamDefaultControllerError(controller, enqueueE);
  37729. throw enqueueE;
  37730. }
  37731. }
  37732. ReadableStreamDefaultControllerCallPullIfNeeded(controller);
  37733. }
  37734. function ReadableStreamDefaultControllerError(controller, e4) {
  37735. const stream = controller._controlledReadableStream;
  37736. if (stream._state !== "readable") {
  37737. return;
  37738. }
  37739. ResetQueue(controller);
  37740. ReadableStreamDefaultControllerClearAlgorithms(controller);
  37741. ReadableStreamError(stream, e4);
  37742. }
  37743. function ReadableStreamDefaultControllerGetDesiredSize(controller) {
  37744. const state2 = controller._controlledReadableStream._state;
  37745. if (state2 === "errored") {
  37746. return null;
  37747. }
  37748. if (state2 === "closed") {
  37749. return 0;
  37750. }
  37751. return controller._strategyHWM - controller._queueTotalSize;
  37752. }
  37753. function ReadableStreamDefaultControllerHasBackpressure(controller) {
  37754. if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
  37755. return false;
  37756. }
  37757. return true;
  37758. }
  37759. function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
  37760. const state2 = controller._controlledReadableStream._state;
  37761. if (!controller._closeRequested && state2 === "readable") {
  37762. return true;
  37763. }
  37764. return false;
  37765. }
  37766. function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
  37767. controller._controlledReadableStream = stream;
  37768. controller._queue = void 0;
  37769. controller._queueTotalSize = void 0;
  37770. ResetQueue(controller);
  37771. controller._started = false;
  37772. controller._closeRequested = false;
  37773. controller._pullAgain = false;
  37774. controller._pulling = false;
  37775. controller._strategySizeAlgorithm = sizeAlgorithm;
  37776. controller._strategyHWM = highWaterMark;
  37777. controller._pullAlgorithm = pullAlgorithm;
  37778. controller._cancelAlgorithm = cancelAlgorithm;
  37779. stream._readableStreamController = controller;
  37780. const startResult = startAlgorithm();
  37781. uponPromise(promiseResolvedWith(startResult), () => {
  37782. controller._started = true;
  37783. ReadableStreamDefaultControllerCallPullIfNeeded(controller);
  37784. return null;
  37785. }, (r4) => {
  37786. ReadableStreamDefaultControllerError(controller, r4);
  37787. return null;
  37788. });
  37789. }
  37790. function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
  37791. const controller = Object.create(ReadableStreamDefaultController.prototype);
  37792. let startAlgorithm;
  37793. let pullAlgorithm;
  37794. let cancelAlgorithm;
  37795. if (underlyingSource.start !== void 0) {
  37796. startAlgorithm = () => underlyingSource.start(controller);
  37797. } else {
  37798. startAlgorithm = () => void 0;
  37799. }
  37800. if (underlyingSource.pull !== void 0) {
  37801. pullAlgorithm = () => underlyingSource.pull(controller);
  37802. } else {
  37803. pullAlgorithm = () => promiseResolvedWith(void 0);
  37804. }
  37805. if (underlyingSource.cancel !== void 0) {
  37806. cancelAlgorithm = (reason) => underlyingSource.cancel(reason);
  37807. } else {
  37808. cancelAlgorithm = () => promiseResolvedWith(void 0);
  37809. }
  37810. SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
  37811. }
  37812. function defaultControllerBrandCheckException$1(name) {
  37813. return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
  37814. }
  37815. function ReadableStreamTee(stream, cloneForBranch2) {
  37816. if (IsReadableByteStreamController(stream._readableStreamController)) {
  37817. return ReadableByteStreamTee(stream);
  37818. }
  37819. return ReadableStreamDefaultTee(stream);
  37820. }
  37821. function ReadableStreamDefaultTee(stream, cloneForBranch2) {
  37822. const reader = AcquireReadableStreamDefaultReader(stream);
  37823. let reading = false;
  37824. let readAgain = false;
  37825. let canceled1 = false;
  37826. let canceled2 = false;
  37827. let reason1;
  37828. let reason2;
  37829. let branch1;
  37830. let branch2;
  37831. let resolveCancelPromise;
  37832. const cancelPromise = newPromise((resolve2) => {
  37833. resolveCancelPromise = resolve2;
  37834. });
  37835. function pullAlgorithm() {
  37836. if (reading) {
  37837. readAgain = true;
  37838. return promiseResolvedWith(void 0);
  37839. }
  37840. reading = true;
  37841. const readRequest = {
  37842. _chunkSteps: (chunk) => {
  37843. _queueMicrotask(() => {
  37844. readAgain = false;
  37845. const chunk1 = chunk;
  37846. const chunk2 = chunk;
  37847. if (!canceled1) {
  37848. ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
  37849. }
  37850. if (!canceled2) {
  37851. ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
  37852. }
  37853. reading = false;
  37854. if (readAgain) {
  37855. pullAlgorithm();
  37856. }
  37857. });
  37858. },
  37859. _closeSteps: () => {
  37860. reading = false;
  37861. if (!canceled1) {
  37862. ReadableStreamDefaultControllerClose(branch1._readableStreamController);
  37863. }
  37864. if (!canceled2) {
  37865. ReadableStreamDefaultControllerClose(branch2._readableStreamController);
  37866. }
  37867. if (!canceled1 || !canceled2) {
  37868. resolveCancelPromise(void 0);
  37869. }
  37870. },
  37871. _errorSteps: () => {
  37872. reading = false;
  37873. }
  37874. };
  37875. ReadableStreamDefaultReaderRead(reader, readRequest);
  37876. return promiseResolvedWith(void 0);
  37877. }
  37878. function cancel1Algorithm(reason) {
  37879. canceled1 = true;
  37880. reason1 = reason;
  37881. if (canceled2) {
  37882. const compositeReason = CreateArrayFromList([reason1, reason2]);
  37883. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  37884. resolveCancelPromise(cancelResult);
  37885. }
  37886. return cancelPromise;
  37887. }
  37888. function cancel2Algorithm(reason) {
  37889. canceled2 = true;
  37890. reason2 = reason;
  37891. if (canceled1) {
  37892. const compositeReason = CreateArrayFromList([reason1, reason2]);
  37893. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  37894. resolveCancelPromise(cancelResult);
  37895. }
  37896. return cancelPromise;
  37897. }
  37898. function startAlgorithm() {
  37899. }
  37900. branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
  37901. branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
  37902. uponRejection(reader._closedPromise, (r4) => {
  37903. ReadableStreamDefaultControllerError(branch1._readableStreamController, r4);
  37904. ReadableStreamDefaultControllerError(branch2._readableStreamController, r4);
  37905. if (!canceled1 || !canceled2) {
  37906. resolveCancelPromise(void 0);
  37907. }
  37908. return null;
  37909. });
  37910. return [branch1, branch2];
  37911. }
  37912. function ReadableByteStreamTee(stream) {
  37913. let reader = AcquireReadableStreamDefaultReader(stream);
  37914. let reading = false;
  37915. let readAgainForBranch1 = false;
  37916. let readAgainForBranch2 = false;
  37917. let canceled1 = false;
  37918. let canceled2 = false;
  37919. let reason1;
  37920. let reason2;
  37921. let branch1;
  37922. let branch2;
  37923. let resolveCancelPromise;
  37924. const cancelPromise = newPromise((resolve2) => {
  37925. resolveCancelPromise = resolve2;
  37926. });
  37927. function forwardReaderError(thisReader) {
  37928. uponRejection(thisReader._closedPromise, (r4) => {
  37929. if (thisReader !== reader) {
  37930. return null;
  37931. }
  37932. ReadableByteStreamControllerError(branch1._readableStreamController, r4);
  37933. ReadableByteStreamControllerError(branch2._readableStreamController, r4);
  37934. if (!canceled1 || !canceled2) {
  37935. resolveCancelPromise(void 0);
  37936. }
  37937. return null;
  37938. });
  37939. }
  37940. function pullWithDefaultReader() {
  37941. if (IsReadableStreamBYOBReader(reader)) {
  37942. ReadableStreamReaderGenericRelease(reader);
  37943. reader = AcquireReadableStreamDefaultReader(stream);
  37944. forwardReaderError(reader);
  37945. }
  37946. const readRequest = {
  37947. _chunkSteps: (chunk) => {
  37948. _queueMicrotask(() => {
  37949. readAgainForBranch1 = false;
  37950. readAgainForBranch2 = false;
  37951. const chunk1 = chunk;
  37952. let chunk2 = chunk;
  37953. if (!canceled1 && !canceled2) {
  37954. try {
  37955. chunk2 = CloneAsUint8Array(chunk);
  37956. } catch (cloneE) {
  37957. ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);
  37958. ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);
  37959. resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
  37960. return;
  37961. }
  37962. }
  37963. if (!canceled1) {
  37964. ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);
  37965. }
  37966. if (!canceled2) {
  37967. ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);
  37968. }
  37969. reading = false;
  37970. if (readAgainForBranch1) {
  37971. pull1Algorithm();
  37972. } else if (readAgainForBranch2) {
  37973. pull2Algorithm();
  37974. }
  37975. });
  37976. },
  37977. _closeSteps: () => {
  37978. reading = false;
  37979. if (!canceled1) {
  37980. ReadableByteStreamControllerClose(branch1._readableStreamController);
  37981. }
  37982. if (!canceled2) {
  37983. ReadableByteStreamControllerClose(branch2._readableStreamController);
  37984. }
  37985. if (branch1._readableStreamController._pendingPullIntos.length > 0) {
  37986. ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);
  37987. }
  37988. if (branch2._readableStreamController._pendingPullIntos.length > 0) {
  37989. ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);
  37990. }
  37991. if (!canceled1 || !canceled2) {
  37992. resolveCancelPromise(void 0);
  37993. }
  37994. },
  37995. _errorSteps: () => {
  37996. reading = false;
  37997. }
  37998. };
  37999. ReadableStreamDefaultReaderRead(reader, readRequest);
  38000. }
  38001. function pullWithBYOBReader(view5, forBranch2) {
  38002. if (IsReadableStreamDefaultReader(reader)) {
  38003. ReadableStreamReaderGenericRelease(reader);
  38004. reader = AcquireReadableStreamBYOBReader(stream);
  38005. forwardReaderError(reader);
  38006. }
  38007. const byobBranch = forBranch2 ? branch2 : branch1;
  38008. const otherBranch = forBranch2 ? branch1 : branch2;
  38009. const readIntoRequest = {
  38010. _chunkSteps: (chunk) => {
  38011. _queueMicrotask(() => {
  38012. readAgainForBranch1 = false;
  38013. readAgainForBranch2 = false;
  38014. const byobCanceled = forBranch2 ? canceled2 : canceled1;
  38015. const otherCanceled = forBranch2 ? canceled1 : canceled2;
  38016. if (!otherCanceled) {
  38017. let clonedChunk;
  38018. try {
  38019. clonedChunk = CloneAsUint8Array(chunk);
  38020. } catch (cloneE) {
  38021. ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);
  38022. ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);
  38023. resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
  38024. return;
  38025. }
  38026. if (!byobCanceled) {
  38027. ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
  38028. }
  38029. ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);
  38030. } else if (!byobCanceled) {
  38031. ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
  38032. }
  38033. reading = false;
  38034. if (readAgainForBranch1) {
  38035. pull1Algorithm();
  38036. } else if (readAgainForBranch2) {
  38037. pull2Algorithm();
  38038. }
  38039. });
  38040. },
  38041. _closeSteps: (chunk) => {
  38042. reading = false;
  38043. const byobCanceled = forBranch2 ? canceled2 : canceled1;
  38044. const otherCanceled = forBranch2 ? canceled1 : canceled2;
  38045. if (!byobCanceled) {
  38046. ReadableByteStreamControllerClose(byobBranch._readableStreamController);
  38047. }
  38048. if (!otherCanceled) {
  38049. ReadableByteStreamControllerClose(otherBranch._readableStreamController);
  38050. }
  38051. if (chunk !== void 0) {
  38052. if (!byobCanceled) {
  38053. ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
  38054. }
  38055. if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {
  38056. ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);
  38057. }
  38058. }
  38059. if (!byobCanceled || !otherCanceled) {
  38060. resolveCancelPromise(void 0);
  38061. }
  38062. },
  38063. _errorSteps: () => {
  38064. reading = false;
  38065. }
  38066. };
  38067. ReadableStreamBYOBReaderRead(reader, view5, 1, readIntoRequest);
  38068. }
  38069. function pull1Algorithm() {
  38070. if (reading) {
  38071. readAgainForBranch1 = true;
  38072. return promiseResolvedWith(void 0);
  38073. }
  38074. reading = true;
  38075. const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);
  38076. if (byobRequest === null) {
  38077. pullWithDefaultReader();
  38078. } else {
  38079. pullWithBYOBReader(byobRequest._view, false);
  38080. }
  38081. return promiseResolvedWith(void 0);
  38082. }
  38083. function pull2Algorithm() {
  38084. if (reading) {
  38085. readAgainForBranch2 = true;
  38086. return promiseResolvedWith(void 0);
  38087. }
  38088. reading = true;
  38089. const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);
  38090. if (byobRequest === null) {
  38091. pullWithDefaultReader();
  38092. } else {
  38093. pullWithBYOBReader(byobRequest._view, true);
  38094. }
  38095. return promiseResolvedWith(void 0);
  38096. }
  38097. function cancel1Algorithm(reason) {
  38098. canceled1 = true;
  38099. reason1 = reason;
  38100. if (canceled2) {
  38101. const compositeReason = CreateArrayFromList([reason1, reason2]);
  38102. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  38103. resolveCancelPromise(cancelResult);
  38104. }
  38105. return cancelPromise;
  38106. }
  38107. function cancel2Algorithm(reason) {
  38108. canceled2 = true;
  38109. reason2 = reason;
  38110. if (canceled1) {
  38111. const compositeReason = CreateArrayFromList([reason1, reason2]);
  38112. const cancelResult = ReadableStreamCancel(stream, compositeReason);
  38113. resolveCancelPromise(cancelResult);
  38114. }
  38115. return cancelPromise;
  38116. }
  38117. function startAlgorithm() {
  38118. return;
  38119. }
  38120. branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);
  38121. branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);
  38122. forwardReaderError(reader);
  38123. return [branch1, branch2];
  38124. }
  38125. function isReadableStreamLike(stream) {
  38126. return typeIsObject(stream) && typeof stream.getReader !== "undefined";
  38127. }
  38128. function ReadableStreamFrom(source) {
  38129. if (isReadableStreamLike(source)) {
  38130. return ReadableStreamFromDefaultReader(source.getReader());
  38131. }
  38132. return ReadableStreamFromIterable(source);
  38133. }
  38134. function ReadableStreamFromIterable(asyncIterable) {
  38135. let stream;
  38136. const iteratorRecord = GetIterator(asyncIterable, "async");
  38137. const startAlgorithm = noop2;
  38138. function pullAlgorithm() {
  38139. let nextResult;
  38140. try {
  38141. nextResult = IteratorNext(iteratorRecord);
  38142. } catch (e4) {
  38143. return promiseRejectedWith(e4);
  38144. }
  38145. const nextPromise = promiseResolvedWith(nextResult);
  38146. return transformPromiseWith(nextPromise, (iterResult) => {
  38147. if (!typeIsObject(iterResult)) {
  38148. throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");
  38149. }
  38150. const done = IteratorComplete(iterResult);
  38151. if (done) {
  38152. ReadableStreamDefaultControllerClose(stream._readableStreamController);
  38153. } else {
  38154. const value = IteratorValue(iterResult);
  38155. ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
  38156. }
  38157. });
  38158. }
  38159. function cancelAlgorithm(reason) {
  38160. const iterator = iteratorRecord.iterator;
  38161. let returnMethod;
  38162. try {
  38163. returnMethod = GetMethod(iterator, "return");
  38164. } catch (e4) {
  38165. return promiseRejectedWith(e4);
  38166. }
  38167. if (returnMethod === void 0) {
  38168. return promiseResolvedWith(void 0);
  38169. }
  38170. let returnResult;
  38171. try {
  38172. returnResult = reflectCall(returnMethod, iterator, [reason]);
  38173. } catch (e4) {
  38174. return promiseRejectedWith(e4);
  38175. }
  38176. const returnPromise = promiseResolvedWith(returnResult);
  38177. return transformPromiseWith(returnPromise, (iterResult) => {
  38178. if (!typeIsObject(iterResult)) {
  38179. throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object");
  38180. }
  38181. return void 0;
  38182. });
  38183. }
  38184. stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
  38185. return stream;
  38186. }
  38187. function ReadableStreamFromDefaultReader(reader) {
  38188. let stream;
  38189. const startAlgorithm = noop2;
  38190. function pullAlgorithm() {
  38191. let readPromise;
  38192. try {
  38193. readPromise = reader.read();
  38194. } catch (e4) {
  38195. return promiseRejectedWith(e4);
  38196. }
  38197. return transformPromiseWith(readPromise, (readResult) => {
  38198. if (!typeIsObject(readResult)) {
  38199. throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");
  38200. }
  38201. if (readResult.done) {
  38202. ReadableStreamDefaultControllerClose(stream._readableStreamController);
  38203. } else {
  38204. const value = readResult.value;
  38205. ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
  38206. }
  38207. });
  38208. }
  38209. function cancelAlgorithm(reason) {
  38210. try {
  38211. return promiseResolvedWith(reader.cancel(reason));
  38212. } catch (e4) {
  38213. return promiseRejectedWith(e4);
  38214. }
  38215. }
  38216. stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
  38217. return stream;
  38218. }
  38219. function convertUnderlyingDefaultOrByteSource(source, context) {
  38220. assertDictionary(source, context);
  38221. const original = source;
  38222. const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
  38223. const cancel = original === null || original === void 0 ? void 0 : original.cancel;
  38224. const pull2 = original === null || original === void 0 ? void 0 : original.pull;
  38225. const start = original === null || original === void 0 ? void 0 : original.start;
  38226. const type = original === null || original === void 0 ? void 0 : original.type;
  38227. return {
  38228. autoAllocateChunkSize: autoAllocateChunkSize === void 0 ? void 0 : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
  38229. cancel: cancel === void 0 ? void 0 : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
  38230. pull: pull2 === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull2, original, `${context} has member 'pull' that`),
  38231. start: start === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
  38232. type: type === void 0 ? void 0 : convertReadableStreamType(type, `${context} has member 'type' that`)
  38233. };
  38234. }
  38235. function convertUnderlyingSourceCancelCallback(fn, original, context) {
  38236. assertFunction(fn, context);
  38237. return (reason) => promiseCall(fn, original, [reason]);
  38238. }
  38239. function convertUnderlyingSourcePullCallback(fn, original, context) {
  38240. assertFunction(fn, context);
  38241. return (controller) => promiseCall(fn, original, [controller]);
  38242. }
  38243. function convertUnderlyingSourceStartCallback(fn, original, context) {
  38244. assertFunction(fn, context);
  38245. return (controller) => reflectCall(fn, original, [controller]);
  38246. }
  38247. function convertReadableStreamType(type, context) {
  38248. type = `${type}`;
  38249. if (type !== "bytes") {
  38250. throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
  38251. }
  38252. return type;
  38253. }
  38254. function convertIteratorOptions(options, context) {
  38255. assertDictionary(options, context);
  38256. const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
  38257. return { preventCancel: Boolean(preventCancel) };
  38258. }
  38259. function convertPipeOptions(options, context) {
  38260. assertDictionary(options, context);
  38261. const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
  38262. const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
  38263. const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
  38264. const signal = options === null || options === void 0 ? void 0 : options.signal;
  38265. if (signal !== void 0) {
  38266. assertAbortSignal(signal, `${context} has member 'signal' that`);
  38267. }
  38268. return {
  38269. preventAbort: Boolean(preventAbort),
  38270. preventCancel: Boolean(preventCancel),
  38271. preventClose: Boolean(preventClose),
  38272. signal
  38273. };
  38274. }
  38275. function assertAbortSignal(signal, context) {
  38276. if (!isAbortSignal2(signal)) {
  38277. throw new TypeError(`${context} is not an AbortSignal.`);
  38278. }
  38279. }
  38280. function convertReadableWritablePair(pair, context) {
  38281. assertDictionary(pair, context);
  38282. const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
  38283. assertRequiredField(readable, "readable", "ReadableWritablePair");
  38284. assertReadableStream(readable, `${context} has member 'readable' that`);
  38285. const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
  38286. assertRequiredField(writable, "writable", "ReadableWritablePair");
  38287. assertWritableStream(writable, `${context} has member 'writable' that`);
  38288. return { readable, writable };
  38289. }
  38290. class ReadableStream2 {
  38291. constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
  38292. if (rawUnderlyingSource === void 0) {
  38293. rawUnderlyingSource = null;
  38294. } else {
  38295. assertObject(rawUnderlyingSource, "First parameter");
  38296. }
  38297. const strategy = convertQueuingStrategy(rawStrategy, "Second parameter");
  38298. const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter");
  38299. InitializeReadableStream(this);
  38300. if (underlyingSource.type === "bytes") {
  38301. if (strategy.size !== void 0) {
  38302. throw new RangeError("The strategy for a byte stream cannot have a size function");
  38303. }
  38304. const highWaterMark = ExtractHighWaterMark(strategy, 0);
  38305. SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
  38306. } else {
  38307. const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
  38308. const highWaterMark = ExtractHighWaterMark(strategy, 1);
  38309. SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
  38310. }
  38311. }
  38312. /**
  38313. * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
  38314. */
  38315. get locked() {
  38316. if (!IsReadableStream(this)) {
  38317. throw streamBrandCheckException$1("locked");
  38318. }
  38319. return IsReadableStreamLocked(this);
  38320. }
  38321. /**
  38322. * Cancels the stream, signaling a loss of interest in the stream by a consumer.
  38323. *
  38324. * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
  38325. * method, which might or might not use it.
  38326. */
  38327. cancel(reason = void 0) {
  38328. if (!IsReadableStream(this)) {
  38329. return promiseRejectedWith(streamBrandCheckException$1("cancel"));
  38330. }
  38331. if (IsReadableStreamLocked(this)) {
  38332. return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader"));
  38333. }
  38334. return ReadableStreamCancel(this, reason);
  38335. }
  38336. getReader(rawOptions = void 0) {
  38337. if (!IsReadableStream(this)) {
  38338. throw streamBrandCheckException$1("getReader");
  38339. }
  38340. const options = convertReaderOptions(rawOptions, "First parameter");
  38341. if (options.mode === void 0) {
  38342. return AcquireReadableStreamDefaultReader(this);
  38343. }
  38344. return AcquireReadableStreamBYOBReader(this);
  38345. }
  38346. pipeThrough(rawTransform, rawOptions = {}) {
  38347. if (!IsReadableStream(this)) {
  38348. throw streamBrandCheckException$1("pipeThrough");
  38349. }
  38350. assertRequiredArgument(rawTransform, 1, "pipeThrough");
  38351. const transform = convertReadableWritablePair(rawTransform, "First parameter");
  38352. const options = convertPipeOptions(rawOptions, "Second parameter");
  38353. if (IsReadableStreamLocked(this)) {
  38354. throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");
  38355. }
  38356. if (IsWritableStreamLocked(transform.writable)) {
  38357. throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");
  38358. }
  38359. const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
  38360. setPromiseIsHandledToTrue(promise);
  38361. return transform.readable;
  38362. }
  38363. pipeTo(destination, rawOptions = {}) {
  38364. if (!IsReadableStream(this)) {
  38365. return promiseRejectedWith(streamBrandCheckException$1("pipeTo"));
  38366. }
  38367. if (destination === void 0) {
  38368. return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
  38369. }
  38370. if (!IsWritableStream(destination)) {
  38371. return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
  38372. }
  38373. let options;
  38374. try {
  38375. options = convertPipeOptions(rawOptions, "Second parameter");
  38376. } catch (e4) {
  38377. return promiseRejectedWith(e4);
  38378. }
  38379. if (IsReadableStreamLocked(this)) {
  38380. return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));
  38381. }
  38382. if (IsWritableStreamLocked(destination)) {
  38383. return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));
  38384. }
  38385. return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
  38386. }
  38387. /**
  38388. * Tees this readable stream, returning a two-element array containing the two resulting branches as
  38389. * new {@link ReadableStream} instances.
  38390. *
  38391. * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
  38392. * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
  38393. * propagated to the stream's underlying source.
  38394. *
  38395. * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
  38396. * this could allow interference between the two branches.
  38397. */
  38398. tee() {
  38399. if (!IsReadableStream(this)) {
  38400. throw streamBrandCheckException$1("tee");
  38401. }
  38402. const branches = ReadableStreamTee(this);
  38403. return CreateArrayFromList(branches);
  38404. }
  38405. values(rawOptions = void 0) {
  38406. if (!IsReadableStream(this)) {
  38407. throw streamBrandCheckException$1("values");
  38408. }
  38409. const options = convertIteratorOptions(rawOptions, "First parameter");
  38410. return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
  38411. }
  38412. [SymbolAsyncIterator](options) {
  38413. return this.values(options);
  38414. }
  38415. /**
  38416. * Creates a new ReadableStream wrapping the provided iterable or async iterable.
  38417. *
  38418. * This can be used to adapt various kinds of objects into a readable stream,
  38419. * such as an array, an async generator, or a Node.js readable stream.
  38420. */
  38421. static from(asyncIterable) {
  38422. return ReadableStreamFrom(asyncIterable);
  38423. }
  38424. }
  38425. Object.defineProperties(ReadableStream2, {
  38426. from: { enumerable: true }
  38427. });
  38428. Object.defineProperties(ReadableStream2.prototype, {
  38429. cancel: { enumerable: true },
  38430. getReader: { enumerable: true },
  38431. pipeThrough: { enumerable: true },
  38432. pipeTo: { enumerable: true },
  38433. tee: { enumerable: true },
  38434. values: { enumerable: true },
  38435. locked: { enumerable: true }
  38436. });
  38437. setFunctionName(ReadableStream2.from, "from");
  38438. setFunctionName(ReadableStream2.prototype.cancel, "cancel");
  38439. setFunctionName(ReadableStream2.prototype.getReader, "getReader");
  38440. setFunctionName(ReadableStream2.prototype.pipeThrough, "pipeThrough");
  38441. setFunctionName(ReadableStream2.prototype.pipeTo, "pipeTo");
  38442. setFunctionName(ReadableStream2.prototype.tee, "tee");
  38443. setFunctionName(ReadableStream2.prototype.values, "values");
  38444. if (typeof Symbol.toStringTag === "symbol") {
  38445. Object.defineProperty(ReadableStream2.prototype, Symbol.toStringTag, {
  38446. value: "ReadableStream",
  38447. configurable: true
  38448. });
  38449. }
  38450. Object.defineProperty(ReadableStream2.prototype, SymbolAsyncIterator, {
  38451. value: ReadableStream2.prototype.values,
  38452. writable: true,
  38453. configurable: true
  38454. });
  38455. function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
  38456. const stream = Object.create(ReadableStream2.prototype);
  38457. InitializeReadableStream(stream);
  38458. const controller = Object.create(ReadableStreamDefaultController.prototype);
  38459. SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
  38460. return stream;
  38461. }
  38462. function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
  38463. const stream = Object.create(ReadableStream2.prototype);
  38464. InitializeReadableStream(stream);
  38465. const controller = Object.create(ReadableByteStreamController.prototype);
  38466. SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0);
  38467. return stream;
  38468. }
  38469. function InitializeReadableStream(stream) {
  38470. stream._state = "readable";
  38471. stream._reader = void 0;
  38472. stream._storedError = void 0;
  38473. stream._disturbed = false;
  38474. }
  38475. function IsReadableStream(x4) {
  38476. if (!typeIsObject(x4)) {
  38477. return false;
  38478. }
  38479. if (!Object.prototype.hasOwnProperty.call(x4, "_readableStreamController")) {
  38480. return false;
  38481. }
  38482. return x4 instanceof ReadableStream2;
  38483. }
  38484. function IsReadableStreamLocked(stream) {
  38485. if (stream._reader === void 0) {
  38486. return false;
  38487. }
  38488. return true;
  38489. }
  38490. function ReadableStreamCancel(stream, reason) {
  38491. stream._disturbed = true;
  38492. if (stream._state === "closed") {
  38493. return promiseResolvedWith(void 0);
  38494. }
  38495. if (stream._state === "errored") {
  38496. return promiseRejectedWith(stream._storedError);
  38497. }
  38498. ReadableStreamClose(stream);
  38499. const reader = stream._reader;
  38500. if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) {
  38501. const readIntoRequests = reader._readIntoRequests;
  38502. reader._readIntoRequests = new SimpleQueue();
  38503. readIntoRequests.forEach((readIntoRequest) => {
  38504. readIntoRequest._closeSteps(void 0);
  38505. });
  38506. }
  38507. const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
  38508. return transformPromiseWith(sourceCancelPromise, noop2);
  38509. }
  38510. function ReadableStreamClose(stream) {
  38511. stream._state = "closed";
  38512. const reader = stream._reader;
  38513. if (reader === void 0) {
  38514. return;
  38515. }
  38516. defaultReaderClosedPromiseResolve(reader);
  38517. if (IsReadableStreamDefaultReader(reader)) {
  38518. const readRequests = reader._readRequests;
  38519. reader._readRequests = new SimpleQueue();
  38520. readRequests.forEach((readRequest) => {
  38521. readRequest._closeSteps();
  38522. });
  38523. }
  38524. }
  38525. function ReadableStreamError(stream, e4) {
  38526. stream._state = "errored";
  38527. stream._storedError = e4;
  38528. const reader = stream._reader;
  38529. if (reader === void 0) {
  38530. return;
  38531. }
  38532. defaultReaderClosedPromiseReject(reader, e4);
  38533. if (IsReadableStreamDefaultReader(reader)) {
  38534. ReadableStreamDefaultReaderErrorReadRequests(reader, e4);
  38535. } else {
  38536. ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e4);
  38537. }
  38538. }
  38539. function streamBrandCheckException$1(name) {
  38540. return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
  38541. }
  38542. function convertQueuingStrategyInit(init2, context) {
  38543. assertDictionary(init2, context);
  38544. const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark;
  38545. assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit");
  38546. return {
  38547. highWaterMark: convertUnrestrictedDouble(highWaterMark)
  38548. };
  38549. }
  38550. const byteLengthSizeFunction = (chunk) => {
  38551. return chunk.byteLength;
  38552. };
  38553. setFunctionName(byteLengthSizeFunction, "size");
  38554. class ByteLengthQueuingStrategy {
  38555. constructor(options) {
  38556. assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy");
  38557. options = convertQueuingStrategyInit(options, "First parameter");
  38558. this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
  38559. }
  38560. /**
  38561. * Returns the high water mark provided to the constructor.
  38562. */
  38563. get highWaterMark() {
  38564. if (!IsByteLengthQueuingStrategy(this)) {
  38565. throw byteLengthBrandCheckException("highWaterMark");
  38566. }
  38567. return this._byteLengthQueuingStrategyHighWaterMark;
  38568. }
  38569. /**
  38570. * Measures the size of `chunk` by returning the value of its `byteLength` property.
  38571. */
  38572. get size() {
  38573. if (!IsByteLengthQueuingStrategy(this)) {
  38574. throw byteLengthBrandCheckException("size");
  38575. }
  38576. return byteLengthSizeFunction;
  38577. }
  38578. }
  38579. Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
  38580. highWaterMark: { enumerable: true },
  38581. size: { enumerable: true }
  38582. });
  38583. if (typeof Symbol.toStringTag === "symbol") {
  38584. Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {
  38585. value: "ByteLengthQueuingStrategy",
  38586. configurable: true
  38587. });
  38588. }
  38589. function byteLengthBrandCheckException(name) {
  38590. return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
  38591. }
  38592. function IsByteLengthQueuingStrategy(x4) {
  38593. if (!typeIsObject(x4)) {
  38594. return false;
  38595. }
  38596. if (!Object.prototype.hasOwnProperty.call(x4, "_byteLengthQueuingStrategyHighWaterMark")) {
  38597. return false;
  38598. }
  38599. return x4 instanceof ByteLengthQueuingStrategy;
  38600. }
  38601. const countSizeFunction = () => {
  38602. return 1;
  38603. };
  38604. setFunctionName(countSizeFunction, "size");
  38605. class CountQueuingStrategy {
  38606. constructor(options) {
  38607. assertRequiredArgument(options, 1, "CountQueuingStrategy");
  38608. options = convertQueuingStrategyInit(options, "First parameter");
  38609. this._countQueuingStrategyHighWaterMark = options.highWaterMark;
  38610. }
  38611. /**
  38612. * Returns the high water mark provided to the constructor.
  38613. */
  38614. get highWaterMark() {
  38615. if (!IsCountQueuingStrategy(this)) {
  38616. throw countBrandCheckException("highWaterMark");
  38617. }
  38618. return this._countQueuingStrategyHighWaterMark;
  38619. }
  38620. /**
  38621. * Measures the size of `chunk` by always returning 1.
  38622. * This ensures that the total queue size is a count of the number of chunks in the queue.
  38623. */
  38624. get size() {
  38625. if (!IsCountQueuingStrategy(this)) {
  38626. throw countBrandCheckException("size");
  38627. }
  38628. return countSizeFunction;
  38629. }
  38630. }
  38631. Object.defineProperties(CountQueuingStrategy.prototype, {
  38632. highWaterMark: { enumerable: true },
  38633. size: { enumerable: true }
  38634. });
  38635. if (typeof Symbol.toStringTag === "symbol") {
  38636. Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {
  38637. value: "CountQueuingStrategy",
  38638. configurable: true
  38639. });
  38640. }
  38641. function countBrandCheckException(name) {
  38642. return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
  38643. }
  38644. function IsCountQueuingStrategy(x4) {
  38645. if (!typeIsObject(x4)) {
  38646. return false;
  38647. }
  38648. if (!Object.prototype.hasOwnProperty.call(x4, "_countQueuingStrategyHighWaterMark")) {
  38649. return false;
  38650. }
  38651. return x4 instanceof CountQueuingStrategy;
  38652. }
  38653. function convertTransformer(original, context) {
  38654. assertDictionary(original, context);
  38655. const cancel = original === null || original === void 0 ? void 0 : original.cancel;
  38656. const flush = original === null || original === void 0 ? void 0 : original.flush;
  38657. const readableType = original === null || original === void 0 ? void 0 : original.readableType;
  38658. const start = original === null || original === void 0 ? void 0 : original.start;
  38659. const transform = original === null || original === void 0 ? void 0 : original.transform;
  38660. const writableType = original === null || original === void 0 ? void 0 : original.writableType;
  38661. return {
  38662. cancel: cancel === void 0 ? void 0 : convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`),
  38663. flush: flush === void 0 ? void 0 : convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
  38664. readableType,
  38665. start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
  38666. transform: transform === void 0 ? void 0 : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
  38667. writableType
  38668. };
  38669. }
  38670. function convertTransformerFlushCallback(fn, original, context) {
  38671. assertFunction(fn, context);
  38672. return (controller) => promiseCall(fn, original, [controller]);
  38673. }
  38674. function convertTransformerStartCallback(fn, original, context) {
  38675. assertFunction(fn, context);
  38676. return (controller) => reflectCall(fn, original, [controller]);
  38677. }
  38678. function convertTransformerTransformCallback(fn, original, context) {
  38679. assertFunction(fn, context);
  38680. return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
  38681. }
  38682. function convertTransformerCancelCallback(fn, original, context) {
  38683. assertFunction(fn, context);
  38684. return (reason) => promiseCall(fn, original, [reason]);
  38685. }
  38686. class TransformStream2 {
  38687. constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
  38688. if (rawTransformer === void 0) {
  38689. rawTransformer = null;
  38690. }
  38691. const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter");
  38692. const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter");
  38693. const transformer = convertTransformer(rawTransformer, "First parameter");
  38694. if (transformer.readableType !== void 0) {
  38695. throw new RangeError("Invalid readableType specified");
  38696. }
  38697. if (transformer.writableType !== void 0) {
  38698. throw new RangeError("Invalid writableType specified");
  38699. }
  38700. const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
  38701. const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
  38702. const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
  38703. const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
  38704. let startPromise_resolve;
  38705. const startPromise = newPromise((resolve2) => {
  38706. startPromise_resolve = resolve2;
  38707. });
  38708. InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
  38709. SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
  38710. if (transformer.start !== void 0) {
  38711. startPromise_resolve(transformer.start(this._transformStreamController));
  38712. } else {
  38713. startPromise_resolve(void 0);
  38714. }
  38715. }
  38716. /**
  38717. * The readable side of the transform stream.
  38718. */
  38719. get readable() {
  38720. if (!IsTransformStream(this)) {
  38721. throw streamBrandCheckException("readable");
  38722. }
  38723. return this._readable;
  38724. }
  38725. /**
  38726. * The writable side of the transform stream.
  38727. */
  38728. get writable() {
  38729. if (!IsTransformStream(this)) {
  38730. throw streamBrandCheckException("writable");
  38731. }
  38732. return this._writable;
  38733. }
  38734. }
  38735. Object.defineProperties(TransformStream2.prototype, {
  38736. readable: { enumerable: true },
  38737. writable: { enumerable: true }
  38738. });
  38739. if (typeof Symbol.toStringTag === "symbol") {
  38740. Object.defineProperty(TransformStream2.prototype, Symbol.toStringTag, {
  38741. value: "TransformStream",
  38742. configurable: true
  38743. });
  38744. }
  38745. function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
  38746. function startAlgorithm() {
  38747. return startPromise;
  38748. }
  38749. function writeAlgorithm(chunk) {
  38750. return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
  38751. }
  38752. function abortAlgorithm(reason) {
  38753. return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
  38754. }
  38755. function closeAlgorithm() {
  38756. return TransformStreamDefaultSinkCloseAlgorithm(stream);
  38757. }
  38758. stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
  38759. function pullAlgorithm() {
  38760. return TransformStreamDefaultSourcePullAlgorithm(stream);
  38761. }
  38762. function cancelAlgorithm(reason) {
  38763. return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);
  38764. }
  38765. stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
  38766. stream._backpressure = void 0;
  38767. stream._backpressureChangePromise = void 0;
  38768. stream._backpressureChangePromise_resolve = void 0;
  38769. TransformStreamSetBackpressure(stream, true);
  38770. stream._transformStreamController = void 0;
  38771. }
  38772. function IsTransformStream(x4) {
  38773. if (!typeIsObject(x4)) {
  38774. return false;
  38775. }
  38776. if (!Object.prototype.hasOwnProperty.call(x4, "_transformStreamController")) {
  38777. return false;
  38778. }
  38779. return x4 instanceof TransformStream2;
  38780. }
  38781. function TransformStreamError(stream, e4) {
  38782. ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e4);
  38783. TransformStreamErrorWritableAndUnblockWrite(stream, e4);
  38784. }
  38785. function TransformStreamErrorWritableAndUnblockWrite(stream, e4) {
  38786. TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
  38787. WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e4);
  38788. TransformStreamUnblockWrite(stream);
  38789. }
  38790. function TransformStreamUnblockWrite(stream) {
  38791. if (stream._backpressure) {
  38792. TransformStreamSetBackpressure(stream, false);
  38793. }
  38794. }
  38795. function TransformStreamSetBackpressure(stream, backpressure) {
  38796. if (stream._backpressureChangePromise !== void 0) {
  38797. stream._backpressureChangePromise_resolve();
  38798. }
  38799. stream._backpressureChangePromise = newPromise((resolve2) => {
  38800. stream._backpressureChangePromise_resolve = resolve2;
  38801. });
  38802. stream._backpressure = backpressure;
  38803. }
  38804. class TransformStreamDefaultController {
  38805. constructor() {
  38806. throw new TypeError("Illegal constructor");
  38807. }
  38808. /**
  38809. * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
  38810. */
  38811. get desiredSize() {
  38812. if (!IsTransformStreamDefaultController(this)) {
  38813. throw defaultControllerBrandCheckException("desiredSize");
  38814. }
  38815. const readableController = this._controlledTransformStream._readable._readableStreamController;
  38816. return ReadableStreamDefaultControllerGetDesiredSize(readableController);
  38817. }
  38818. enqueue(chunk = void 0) {
  38819. if (!IsTransformStreamDefaultController(this)) {
  38820. throw defaultControllerBrandCheckException("enqueue");
  38821. }
  38822. TransformStreamDefaultControllerEnqueue(this, chunk);
  38823. }
  38824. /**
  38825. * Errors both the readable side and the writable side of the controlled transform stream, making all future
  38826. * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
  38827. */
  38828. error(reason = void 0) {
  38829. if (!IsTransformStreamDefaultController(this)) {
  38830. throw defaultControllerBrandCheckException("error");
  38831. }
  38832. TransformStreamDefaultControllerError(this, reason);
  38833. }
  38834. /**
  38835. * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
  38836. * transformer only needs to consume a portion of the chunks written to the writable side.
  38837. */
  38838. terminate() {
  38839. if (!IsTransformStreamDefaultController(this)) {
  38840. throw defaultControllerBrandCheckException("terminate");
  38841. }
  38842. TransformStreamDefaultControllerTerminate(this);
  38843. }
  38844. }
  38845. Object.defineProperties(TransformStreamDefaultController.prototype, {
  38846. enqueue: { enumerable: true },
  38847. error: { enumerable: true },
  38848. terminate: { enumerable: true },
  38849. desiredSize: { enumerable: true }
  38850. });
  38851. setFunctionName(TransformStreamDefaultController.prototype.enqueue, "enqueue");
  38852. setFunctionName(TransformStreamDefaultController.prototype.error, "error");
  38853. setFunctionName(TransformStreamDefaultController.prototype.terminate, "terminate");
  38854. if (typeof Symbol.toStringTag === "symbol") {
  38855. Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {
  38856. value: "TransformStreamDefaultController",
  38857. configurable: true
  38858. });
  38859. }
  38860. function IsTransformStreamDefaultController(x4) {
  38861. if (!typeIsObject(x4)) {
  38862. return false;
  38863. }
  38864. if (!Object.prototype.hasOwnProperty.call(x4, "_controlledTransformStream")) {
  38865. return false;
  38866. }
  38867. return x4 instanceof TransformStreamDefaultController;
  38868. }
  38869. function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
  38870. controller._controlledTransformStream = stream;
  38871. stream._transformStreamController = controller;
  38872. controller._transformAlgorithm = transformAlgorithm;
  38873. controller._flushAlgorithm = flushAlgorithm;
  38874. controller._cancelAlgorithm = cancelAlgorithm;
  38875. controller._finishPromise = void 0;
  38876. controller._finishPromise_resolve = void 0;
  38877. controller._finishPromise_reject = void 0;
  38878. }
  38879. function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
  38880. const controller = Object.create(TransformStreamDefaultController.prototype);
  38881. let transformAlgorithm;
  38882. let flushAlgorithm;
  38883. let cancelAlgorithm;
  38884. if (transformer.transform !== void 0) {
  38885. transformAlgorithm = (chunk) => transformer.transform(chunk, controller);
  38886. } else {
  38887. transformAlgorithm = (chunk) => {
  38888. try {
  38889. TransformStreamDefaultControllerEnqueue(controller, chunk);
  38890. return promiseResolvedWith(void 0);
  38891. } catch (transformResultE) {
  38892. return promiseRejectedWith(transformResultE);
  38893. }
  38894. };
  38895. }
  38896. if (transformer.flush !== void 0) {
  38897. flushAlgorithm = () => transformer.flush(controller);
  38898. } else {
  38899. flushAlgorithm = () => promiseResolvedWith(void 0);
  38900. }
  38901. if (transformer.cancel !== void 0) {
  38902. cancelAlgorithm = (reason) => transformer.cancel(reason);
  38903. } else {
  38904. cancelAlgorithm = () => promiseResolvedWith(void 0);
  38905. }
  38906. SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
  38907. }
  38908. function TransformStreamDefaultControllerClearAlgorithms(controller) {
  38909. controller._transformAlgorithm = void 0;
  38910. controller._flushAlgorithm = void 0;
  38911. controller._cancelAlgorithm = void 0;
  38912. }
  38913. function TransformStreamDefaultControllerEnqueue(controller, chunk) {
  38914. const stream = controller._controlledTransformStream;
  38915. const readableController = stream._readable._readableStreamController;
  38916. if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
  38917. throw new TypeError("Readable side is not in a state that permits enqueue");
  38918. }
  38919. try {
  38920. ReadableStreamDefaultControllerEnqueue(readableController, chunk);
  38921. } catch (e4) {
  38922. TransformStreamErrorWritableAndUnblockWrite(stream, e4);
  38923. throw stream._readable._storedError;
  38924. }
  38925. const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
  38926. if (backpressure !== stream._backpressure) {
  38927. TransformStreamSetBackpressure(stream, true);
  38928. }
  38929. }
  38930. function TransformStreamDefaultControllerError(controller, e4) {
  38931. TransformStreamError(controller._controlledTransformStream, e4);
  38932. }
  38933. function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
  38934. const transformPromise = controller._transformAlgorithm(chunk);
  38935. return transformPromiseWith(transformPromise, void 0, (r4) => {
  38936. TransformStreamError(controller._controlledTransformStream, r4);
  38937. throw r4;
  38938. });
  38939. }
  38940. function TransformStreamDefaultControllerTerminate(controller) {
  38941. const stream = controller._controlledTransformStream;
  38942. const readableController = stream._readable._readableStreamController;
  38943. ReadableStreamDefaultControllerClose(readableController);
  38944. const error2 = new TypeError("TransformStream terminated");
  38945. TransformStreamErrorWritableAndUnblockWrite(stream, error2);
  38946. }
  38947. function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
  38948. const controller = stream._transformStreamController;
  38949. if (stream._backpressure) {
  38950. const backpressureChangePromise = stream._backpressureChangePromise;
  38951. return transformPromiseWith(backpressureChangePromise, () => {
  38952. const writable = stream._writable;
  38953. const state2 = writable._state;
  38954. if (state2 === "erroring") {
  38955. throw writable._storedError;
  38956. }
  38957. return TransformStreamDefaultControllerPerformTransform(controller, chunk);
  38958. });
  38959. }
  38960. return TransformStreamDefaultControllerPerformTransform(controller, chunk);
  38961. }
  38962. function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
  38963. const controller = stream._transformStreamController;
  38964. if (controller._finishPromise !== void 0) {
  38965. return controller._finishPromise;
  38966. }
  38967. const readable = stream._readable;
  38968. controller._finishPromise = newPromise((resolve2, reject) => {
  38969. controller._finishPromise_resolve = resolve2;
  38970. controller._finishPromise_reject = reject;
  38971. });
  38972. const cancelPromise = controller._cancelAlgorithm(reason);
  38973. TransformStreamDefaultControllerClearAlgorithms(controller);
  38974. uponPromise(cancelPromise, () => {
  38975. if (readable._state === "errored") {
  38976. defaultControllerFinishPromiseReject(controller, readable._storedError);
  38977. } else {
  38978. ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
  38979. defaultControllerFinishPromiseResolve(controller);
  38980. }
  38981. return null;
  38982. }, (r4) => {
  38983. ReadableStreamDefaultControllerError(readable._readableStreamController, r4);
  38984. defaultControllerFinishPromiseReject(controller, r4);
  38985. return null;
  38986. });
  38987. return controller._finishPromise;
  38988. }
  38989. function TransformStreamDefaultSinkCloseAlgorithm(stream) {
  38990. const controller = stream._transformStreamController;
  38991. if (controller._finishPromise !== void 0) {
  38992. return controller._finishPromise;
  38993. }
  38994. const readable = stream._readable;
  38995. controller._finishPromise = newPromise((resolve2, reject) => {
  38996. controller._finishPromise_resolve = resolve2;
  38997. controller._finishPromise_reject = reject;
  38998. });
  38999. const flushPromise = controller._flushAlgorithm();
  39000. TransformStreamDefaultControllerClearAlgorithms(controller);
  39001. uponPromise(flushPromise, () => {
  39002. if (readable._state === "errored") {
  39003. defaultControllerFinishPromiseReject(controller, readable._storedError);
  39004. } else {
  39005. ReadableStreamDefaultControllerClose(readable._readableStreamController);
  39006. defaultControllerFinishPromiseResolve(controller);
  39007. }
  39008. return null;
  39009. }, (r4) => {
  39010. ReadableStreamDefaultControllerError(readable._readableStreamController, r4);
  39011. defaultControllerFinishPromiseReject(controller, r4);
  39012. return null;
  39013. });
  39014. return controller._finishPromise;
  39015. }
  39016. function TransformStreamDefaultSourcePullAlgorithm(stream) {
  39017. TransformStreamSetBackpressure(stream, false);
  39018. return stream._backpressureChangePromise;
  39019. }
  39020. function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) {
  39021. const controller = stream._transformStreamController;
  39022. if (controller._finishPromise !== void 0) {
  39023. return controller._finishPromise;
  39024. }
  39025. const writable = stream._writable;
  39026. controller._finishPromise = newPromise((resolve2, reject) => {
  39027. controller._finishPromise_resolve = resolve2;
  39028. controller._finishPromise_reject = reject;
  39029. });
  39030. const cancelPromise = controller._cancelAlgorithm(reason);
  39031. TransformStreamDefaultControllerClearAlgorithms(controller);
  39032. uponPromise(cancelPromise, () => {
  39033. if (writable._state === "errored") {
  39034. defaultControllerFinishPromiseReject(controller, writable._storedError);
  39035. } else {
  39036. WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
  39037. TransformStreamUnblockWrite(stream);
  39038. defaultControllerFinishPromiseResolve(controller);
  39039. }
  39040. return null;
  39041. }, (r4) => {
  39042. WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r4);
  39043. TransformStreamUnblockWrite(stream);
  39044. defaultControllerFinishPromiseReject(controller, r4);
  39045. return null;
  39046. });
  39047. return controller._finishPromise;
  39048. }
  39049. function defaultControllerBrandCheckException(name) {
  39050. return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
  39051. }
  39052. function defaultControllerFinishPromiseResolve(controller) {
  39053. if (controller._finishPromise_resolve === void 0) {
  39054. return;
  39055. }
  39056. controller._finishPromise_resolve();
  39057. controller._finishPromise_resolve = void 0;
  39058. controller._finishPromise_reject = void 0;
  39059. }
  39060. function defaultControllerFinishPromiseReject(controller, reason) {
  39061. if (controller._finishPromise_reject === void 0) {
  39062. return;
  39063. }
  39064. setPromiseIsHandledToTrue(controller._finishPromise);
  39065. controller._finishPromise_reject(reason);
  39066. controller._finishPromise_resolve = void 0;
  39067. controller._finishPromise_reject = void 0;
  39068. }
  39069. function streamBrandCheckException(name) {
  39070. return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
  39071. }
  39072. exports3.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy;
  39073. exports3.CountQueuingStrategy = CountQueuingStrategy;
  39074. exports3.ReadableByteStreamController = ReadableByteStreamController;
  39075. exports3.ReadableStream = ReadableStream2;
  39076. exports3.ReadableStreamBYOBReader = ReadableStreamBYOBReader;
  39077. exports3.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
  39078. exports3.ReadableStreamDefaultController = ReadableStreamDefaultController;
  39079. exports3.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
  39080. exports3.TransformStream = TransformStream2;
  39081. exports3.TransformStreamDefaultController = TransformStreamDefaultController;
  39082. exports3.WritableStream = WritableStream;
  39083. exports3.WritableStreamDefaultController = WritableStreamDefaultController;
  39084. exports3.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
  39085. });
  39086. }
  39087. });
  39088. // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs
  39089. var require_streams = __commonJS({
  39090. "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs"() {
  39091. var POOL_SIZE2 = 65536;
  39092. if (!globalThis.ReadableStream) {
  39093. try {
  39094. const process4 = require("node:process");
  39095. const { emitWarning } = process4;
  39096. try {
  39097. process4.emitWarning = () => {
  39098. };
  39099. Object.assign(globalThis, require("node:stream/web"));
  39100. process4.emitWarning = emitWarning;
  39101. } catch (error2) {
  39102. process4.emitWarning = emitWarning;
  39103. throw error2;
  39104. }
  39105. } catch (error2) {
  39106. Object.assign(globalThis, require_ponyfill_es2018());
  39107. }
  39108. }
  39109. try {
  39110. const { Blob: Blob4 } = require("buffer");
  39111. if (Blob4 && !Blob4.prototype.stream) {
  39112. Blob4.prototype.stream = function name(params) {
  39113. let position = 0;
  39114. const blob = this;
  39115. return new ReadableStream({
  39116. type: "bytes",
  39117. async pull(ctrl) {
  39118. const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE2));
  39119. const buffer = await chunk.arrayBuffer();
  39120. position += buffer.byteLength;
  39121. ctrl.enqueue(new Uint8Array(buffer));
  39122. if (position === blob.size) {
  39123. ctrl.close();
  39124. }
  39125. }
  39126. });
  39127. };
  39128. }
  39129. } catch (error2) {
  39130. }
  39131. }
  39132. });
  39133. // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js
  39134. async function* toIterator(parts, clone2 = true) {
  39135. for (const part of parts) {
  39136. if ("stream" in part) {
  39137. yield* (
  39138. /** @type {AsyncIterableIterator<Uint8Array>} */
  39139. part.stream()
  39140. );
  39141. } else if (ArrayBuffer.isView(part)) {
  39142. if (clone2) {
  39143. let position = part.byteOffset;
  39144. const end = part.byteOffset + part.byteLength;
  39145. while (position !== end) {
  39146. const size = Math.min(end - position, POOL_SIZE);
  39147. const chunk = part.buffer.slice(position, position + size);
  39148. position += chunk.byteLength;
  39149. yield new Uint8Array(chunk);
  39150. }
  39151. } else {
  39152. yield part;
  39153. }
  39154. } else {
  39155. let position = 0, b3 = (
  39156. /** @type {Blob} */
  39157. part
  39158. );
  39159. while (position !== b3.size) {
  39160. const chunk = b3.slice(position, Math.min(b3.size, position + POOL_SIZE));
  39161. const buffer = await chunk.arrayBuffer();
  39162. position += buffer.byteLength;
  39163. yield new Uint8Array(buffer);
  39164. }
  39165. }
  39166. }
  39167. }
  39168. var import_streams, POOL_SIZE, _Blob, Blob3, fetch_blob_default;
  39169. var init_fetch_blob = __esm({
  39170. "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js"() {
  39171. import_streams = __toESM(require_streams(), 1);
  39172. POOL_SIZE = 65536;
  39173. _Blob = class Blob2 {
  39174. /** @type {Array.<(Blob|Uint8Array)>} */
  39175. #parts = [];
  39176. #type = "";
  39177. #size = 0;
  39178. #endings = "transparent";
  39179. /**
  39180. * The Blob() constructor returns a new Blob object. The content
  39181. * of the blob consists of the concatenation of the values given
  39182. * in the parameter array.
  39183. *
  39184. * @param {*} blobParts
  39185. * @param {{ type?: string, endings?: string }} [options]
  39186. */
  39187. constructor(blobParts = [], options = {}) {
  39188. if (typeof blobParts !== "object" || blobParts === null) {
  39189. throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");
  39190. }
  39191. if (typeof blobParts[Symbol.iterator] !== "function") {
  39192. throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");
  39193. }
  39194. if (typeof options !== "object" && typeof options !== "function") {
  39195. throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");
  39196. }
  39197. if (options === null) options = {};
  39198. const encoder = new TextEncoder();
  39199. for (const element of blobParts) {
  39200. let part;
  39201. if (ArrayBuffer.isView(element)) {
  39202. part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength));
  39203. } else if (element instanceof ArrayBuffer) {
  39204. part = new Uint8Array(element.slice(0));
  39205. } else if (element instanceof Blob2) {
  39206. part = element;
  39207. } else {
  39208. part = encoder.encode(`${element}`);
  39209. }
  39210. this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size;
  39211. this.#parts.push(part);
  39212. }
  39213. this.#endings = `${options.endings === void 0 ? "transparent" : options.endings}`;
  39214. const type = options.type === void 0 ? "" : String(options.type);
  39215. this.#type = /^[\x20-\x7E]*$/.test(type) ? type : "";
  39216. }
  39217. /**
  39218. * The Blob interface's size property returns the
  39219. * size of the Blob in bytes.
  39220. */
  39221. get size() {
  39222. return this.#size;
  39223. }
  39224. /**
  39225. * The type property of a Blob object returns the MIME type of the file.
  39226. */
  39227. get type() {
  39228. return this.#type;
  39229. }
  39230. /**
  39231. * The text() method in the Blob interface returns a Promise
  39232. * that resolves with a string containing the contents of
  39233. * the blob, interpreted as UTF-8.
  39234. *
  39235. * @return {Promise<string>}
  39236. */
  39237. async text() {
  39238. const decoder = new TextDecoder();
  39239. let str = "";
  39240. for await (const part of toIterator(this.#parts, false)) {
  39241. str += decoder.decode(part, { stream: true });
  39242. }
  39243. str += decoder.decode();
  39244. return str;
  39245. }
  39246. /**
  39247. * The arrayBuffer() method in the Blob interface returns a
  39248. * Promise that resolves with the contents of the blob as
  39249. * binary data contained in an ArrayBuffer.
  39250. *
  39251. * @return {Promise<ArrayBuffer>}
  39252. */
  39253. async arrayBuffer() {
  39254. const data = new Uint8Array(this.size);
  39255. let offset = 0;
  39256. for await (const chunk of toIterator(this.#parts, false)) {
  39257. data.set(chunk, offset);
  39258. offset += chunk.length;
  39259. }
  39260. return data.buffer;
  39261. }
  39262. stream() {
  39263. const it = toIterator(this.#parts, true);
  39264. return new globalThis.ReadableStream({
  39265. // @ts-ignore
  39266. type: "bytes",
  39267. async pull(ctrl) {
  39268. const chunk = await it.next();
  39269. chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value);
  39270. },
  39271. async cancel() {
  39272. await it.return();
  39273. }
  39274. });
  39275. }
  39276. /**
  39277. * The Blob interface's slice() method creates and returns a
  39278. * new Blob object which contains data from a subset of the
  39279. * blob on which it's called.
  39280. *
  39281. * @param {number} [start]
  39282. * @param {number} [end]
  39283. * @param {string} [type]
  39284. */
  39285. slice(start = 0, end = this.size, type = "") {
  39286. const { size } = this;
  39287. let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size);
  39288. let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size);
  39289. const span = Math.max(relativeEnd - relativeStart, 0);
  39290. const parts = this.#parts;
  39291. const blobParts = [];
  39292. let added = 0;
  39293. for (const part of parts) {
  39294. if (added >= span) {
  39295. break;
  39296. }
  39297. const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size;
  39298. if (relativeStart && size2 <= relativeStart) {
  39299. relativeStart -= size2;
  39300. relativeEnd -= size2;
  39301. } else {
  39302. let chunk;
  39303. if (ArrayBuffer.isView(part)) {
  39304. chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd));
  39305. added += chunk.byteLength;
  39306. } else {
  39307. chunk = part.slice(relativeStart, Math.min(size2, relativeEnd));
  39308. added += chunk.size;
  39309. }
  39310. relativeEnd -= size2;
  39311. blobParts.push(chunk);
  39312. relativeStart = 0;
  39313. }
  39314. }
  39315. const blob = new Blob2([], { type: String(type).toLowerCase() });
  39316. blob.#size = span;
  39317. blob.#parts = blobParts;
  39318. return blob;
  39319. }
  39320. get [Symbol.toStringTag]() {
  39321. return "Blob";
  39322. }
  39323. static [Symbol.hasInstance](object) {
  39324. return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]);
  39325. }
  39326. };
  39327. Object.defineProperties(_Blob.prototype, {
  39328. size: { enumerable: true },
  39329. type: { enumerable: true },
  39330. slice: { enumerable: true }
  39331. });
  39332. Blob3 = _Blob;
  39333. fetch_blob_default = Blob3;
  39334. }
  39335. });
  39336. // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js
  39337. var _File, File3, file_default;
  39338. var init_file = __esm({
  39339. "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js"() {
  39340. init_fetch_blob();
  39341. _File = class File2 extends fetch_blob_default {
  39342. #lastModified = 0;
  39343. #name = "";
  39344. /**
  39345. * @param {*[]} fileBits
  39346. * @param {string} fileName
  39347. * @param {{lastModified?: number, type?: string}} options
  39348. */
  39349. // @ts-ignore
  39350. constructor(fileBits, fileName, options = {}) {
  39351. if (arguments.length < 2) {
  39352. throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);
  39353. }
  39354. super(fileBits, options);
  39355. if (options === null) options = {};
  39356. const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified);
  39357. if (!Number.isNaN(lastModified)) {
  39358. this.#lastModified = lastModified;
  39359. }
  39360. this.#name = String(fileName);
  39361. }
  39362. get name() {
  39363. return this.#name;
  39364. }
  39365. get lastModified() {
  39366. return this.#lastModified;
  39367. }
  39368. get [Symbol.toStringTag]() {
  39369. return "File";
  39370. }
  39371. static [Symbol.hasInstance](object) {
  39372. return !!object && object instanceof fetch_blob_default && /^(File)$/.test(object[Symbol.toStringTag]);
  39373. }
  39374. };
  39375. File3 = _File;
  39376. file_default = File3;
  39377. }
  39378. });
  39379. // ../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js
  39380. function formDataToBlob(F3, B2 = fetch_blob_default) {
  39381. var b3 = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c3 = [], p3 = `--${b3}\r
  39382. Content-Disposition: form-data; name="`;
  39383. F3.forEach((v6, n3) => typeof v6 == "string" ? c3.push(p3 + e(n3) + `"\r
  39384. \r
  39385. ${v6.replace(/\r(?!\n)|(?<!\r)\n/g, "\r\n")}\r
  39386. `) : c3.push(p3 + e(n3) + `"; filename="${e(v6.name, 1)}"\r
  39387. Content-Type: ${v6.type || "application/octet-stream"}\r
  39388. \r
  39389. `, v6, "\r\n"));
  39390. c3.push(`--${b3}--`);
  39391. return new B2(c3, { type: "multipart/form-data; boundary=" + b3 });
  39392. }
  39393. var t, i, h, r, m, f, e, x, FormData;
  39394. var init_esm_min = __esm({
  39395. "../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js"() {
  39396. init_fetch_blob();
  39397. init_file();
  39398. ({ toStringTag: t, iterator: i, hasInstance: h } = Symbol);
  39399. r = Math.random;
  39400. m = "append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(",");
  39401. f = (a3, b3, c3) => (a3 += "", /^(Blob|File)$/.test(b3 && b3[t]) ? [(c3 = c3 !== void 0 ? c3 + "" : b3[t] == "File" ? b3.name : "blob", a3), b3.name !== c3 || b3[t] == "blob" ? new file_default([b3], c3, b3) : b3] : [a3, b3 + ""]);
  39402. e = (c3, f5) => (f5 ? c3 : c3.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
  39403. x = (n3, a3, e4) => {
  39404. if (a3.length < e4) {
  39405. throw new TypeError(`Failed to execute '${n3}' on 'FormData': ${e4} arguments required, but only ${a3.length} present.`);
  39406. }
  39407. };
  39408. FormData = class FormData2 {
  39409. #d = [];
  39410. constructor(...a3) {
  39411. if (a3.length) throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`);
  39412. }
  39413. get [t]() {
  39414. return "FormData";
  39415. }
  39416. [i]() {
  39417. return this.entries();
  39418. }
  39419. static [h](o3) {
  39420. return o3 && typeof o3 === "object" && o3[t] === "FormData" && !m.some((m4) => typeof o3[m4] != "function");
  39421. }
  39422. append(...a3) {
  39423. x("append", arguments, 2);
  39424. this.#d.push(f(...a3));
  39425. }
  39426. delete(a3) {
  39427. x("delete", arguments, 1);
  39428. a3 += "";
  39429. this.#d = this.#d.filter(([b3]) => b3 !== a3);
  39430. }
  39431. get(a3) {
  39432. x("get", arguments, 1);
  39433. a3 += "";
  39434. for (var b3 = this.#d, l3 = b3.length, c3 = 0; c3 < l3; c3++) if (b3[c3][0] === a3) return b3[c3][1];
  39435. return null;
  39436. }
  39437. getAll(a3, b3) {
  39438. x("getAll", arguments, 1);
  39439. b3 = [];
  39440. a3 += "";
  39441. this.#d.forEach((c3) => c3[0] === a3 && b3.push(c3[1]));
  39442. return b3;
  39443. }
  39444. has(a3) {
  39445. x("has", arguments, 1);
  39446. a3 += "";
  39447. return this.#d.some((b3) => b3[0] === a3);
  39448. }
  39449. forEach(a3, b3) {
  39450. x("forEach", arguments, 1);
  39451. for (var [c3, d3] of this) a3.call(b3, d3, c3, this);
  39452. }
  39453. set(...a3) {
  39454. x("set", arguments, 2);
  39455. var b3 = [], c3 = true;
  39456. a3 = f(...a3);
  39457. this.#d.forEach((d3) => {
  39458. d3[0] === a3[0] ? c3 && (c3 = !b3.push(a3)) : b3.push(d3);
  39459. });
  39460. c3 && b3.push(a3);
  39461. this.#d = b3;
  39462. }
  39463. *entries() {
  39464. yield* this.#d;
  39465. }
  39466. *keys() {
  39467. for (var [a3] of this) yield a3;
  39468. }
  39469. *values() {
  39470. for (var [, a3] of this) yield a3;
  39471. }
  39472. };
  39473. }
  39474. });
  39475. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js
  39476. var FetchBaseError;
  39477. var init_base = __esm({
  39478. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js"() {
  39479. FetchBaseError = class extends Error {
  39480. constructor(message, type) {
  39481. super(message);
  39482. Error.captureStackTrace(this, this.constructor);
  39483. this.type = type;
  39484. }
  39485. get name() {
  39486. return this.constructor.name;
  39487. }
  39488. get [Symbol.toStringTag]() {
  39489. return this.constructor.name;
  39490. }
  39491. };
  39492. }
  39493. });
  39494. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js
  39495. var FetchError;
  39496. var init_fetch_error = __esm({
  39497. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js"() {
  39498. init_base();
  39499. FetchError = class extends FetchBaseError {
  39500. /**
  39501. * @param {string} message - Error message for human
  39502. * @param {string} [type] - Error type for machine
  39503. * @param {SystemError} [systemError] - For Node.js system error
  39504. */
  39505. constructor(message, type, systemError) {
  39506. super(message, type);
  39507. if (systemError) {
  39508. this.code = this.errno = systemError.code;
  39509. this.erroredSysCall = systemError.syscall;
  39510. }
  39511. }
  39512. };
  39513. }
  39514. });
  39515. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js
  39516. var NAME, isURLSearchParameters, isBlob2, isAbortSignal, isDomainOrSubdomain, isSameProtocol;
  39517. var init_is = __esm({
  39518. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js"() {
  39519. NAME = Symbol.toStringTag;
  39520. isURLSearchParameters = (object) => {
  39521. return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams";
  39522. };
  39523. isBlob2 = (object) => {
  39524. return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]);
  39525. };
  39526. isAbortSignal = (object) => {
  39527. return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget");
  39528. };
  39529. isDomainOrSubdomain = (destination, original) => {
  39530. const orig = new URL(original).hostname;
  39531. const dest = new URL(destination).hostname;
  39532. return orig === dest || orig.endsWith(`.${dest}`);
  39533. };
  39534. isSameProtocol = (destination, original) => {
  39535. const orig = new URL(original).protocol;
  39536. const dest = new URL(destination).protocol;
  39537. return orig === dest;
  39538. };
  39539. }
  39540. });
  39541. // ../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js
  39542. var require_node_domexception = __commonJS({
  39543. "../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js"(exports2, module2) {
  39544. if (!globalThis.DOMException) {
  39545. try {
  39546. const { MessageChannel } = require("worker_threads"), port = new MessageChannel().port1, ab = new ArrayBuffer();
  39547. port.postMessage(ab, [ab, ab]);
  39548. } catch (err2) {
  39549. err2.constructor.name === "DOMException" && (globalThis.DOMException = err2.constructor);
  39550. }
  39551. }
  39552. module2.exports = globalThis.DOMException;
  39553. }
  39554. });
  39555. // ../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js
  39556. var import_node_fs, import_node_domexception, stat;
  39557. var init_from = __esm({
  39558. "../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js"() {
  39559. import_node_fs = require("node:fs");
  39560. import_node_domexception = __toESM(require_node_domexception(), 1);
  39561. init_file();
  39562. init_fetch_blob();
  39563. ({ stat } = import_node_fs.promises);
  39564. }
  39565. });
  39566. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js
  39567. var multipart_parser_exports = {};
  39568. __export(multipart_parser_exports, {
  39569. toFormData: () => toFormData
  39570. });
  39571. function _fileName(headerValue) {
  39572. const m4 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);
  39573. if (!m4) {
  39574. return;
  39575. }
  39576. const match2 = m4[2] || m4[3] || "";
  39577. let filename = match2.slice(match2.lastIndexOf("\\") + 1);
  39578. filename = filename.replace(/%22/g, '"');
  39579. filename = filename.replace(/&#(\d{4});/g, (m5, code) => {
  39580. return String.fromCharCode(code);
  39581. });
  39582. return filename;
  39583. }
  39584. async function toFormData(Body2, ct) {
  39585. if (!/multipart/i.test(ct)) {
  39586. throw new TypeError("Failed to fetch");
  39587. }
  39588. const m4 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
  39589. if (!m4) {
  39590. throw new TypeError("no or bad content-type header, no multipart boundary");
  39591. }
  39592. const parser = new MultipartParser(m4[1] || m4[2]);
  39593. let headerField;
  39594. let headerValue;
  39595. let entryValue;
  39596. let entryName;
  39597. let contentType;
  39598. let filename;
  39599. const entryChunks = [];
  39600. const formData = new FormData();
  39601. const onPartData = (ui8a) => {
  39602. entryValue += decoder.decode(ui8a, { stream: true });
  39603. };
  39604. const appendToFile = (ui8a) => {
  39605. entryChunks.push(ui8a);
  39606. };
  39607. const appendFileToFormData = () => {
  39608. const file = new file_default(entryChunks, filename, { type: contentType });
  39609. formData.append(entryName, file);
  39610. };
  39611. const appendEntryToFormData = () => {
  39612. formData.append(entryName, entryValue);
  39613. };
  39614. const decoder = new TextDecoder("utf-8");
  39615. decoder.decode();
  39616. parser.onPartBegin = function() {
  39617. parser.onPartData = onPartData;
  39618. parser.onPartEnd = appendEntryToFormData;
  39619. headerField = "";
  39620. headerValue = "";
  39621. entryValue = "";
  39622. entryName = "";
  39623. contentType = "";
  39624. filename = null;
  39625. entryChunks.length = 0;
  39626. };
  39627. parser.onHeaderField = function(ui8a) {
  39628. headerField += decoder.decode(ui8a, { stream: true });
  39629. };
  39630. parser.onHeaderValue = function(ui8a) {
  39631. headerValue += decoder.decode(ui8a, { stream: true });
  39632. };
  39633. parser.onHeaderEnd = function() {
  39634. headerValue += decoder.decode();
  39635. headerField = headerField.toLowerCase();
  39636. if (headerField === "content-disposition") {
  39637. const m5 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);
  39638. if (m5) {
  39639. entryName = m5[2] || m5[3] || "";
  39640. }
  39641. filename = _fileName(headerValue);
  39642. if (filename) {
  39643. parser.onPartData = appendToFile;
  39644. parser.onPartEnd = appendFileToFormData;
  39645. }
  39646. } else if (headerField === "content-type") {
  39647. contentType = headerValue;
  39648. }
  39649. headerValue = "";
  39650. headerField = "";
  39651. };
  39652. for await (const chunk of Body2) {
  39653. parser.write(chunk);
  39654. }
  39655. parser.end();
  39656. return formData;
  39657. }
  39658. var s, S, f2, F, LF, CR, SPACE, HYPHEN, COLON, A, Z, lower, noop, MultipartParser;
  39659. var init_multipart_parser = __esm({
  39660. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js"() {
  39661. init_from();
  39662. init_esm_min();
  39663. s = 0;
  39664. S = {
  39665. START_BOUNDARY: s++,
  39666. HEADER_FIELD_START: s++,
  39667. HEADER_FIELD: s++,
  39668. HEADER_VALUE_START: s++,
  39669. HEADER_VALUE: s++,
  39670. HEADER_VALUE_ALMOST_DONE: s++,
  39671. HEADERS_ALMOST_DONE: s++,
  39672. PART_DATA_START: s++,
  39673. PART_DATA: s++,
  39674. END: s++
  39675. };
  39676. f2 = 1;
  39677. F = {
  39678. PART_BOUNDARY: f2,
  39679. LAST_BOUNDARY: f2 *= 2
  39680. };
  39681. LF = 10;
  39682. CR = 13;
  39683. SPACE = 32;
  39684. HYPHEN = 45;
  39685. COLON = 58;
  39686. A = 97;
  39687. Z = 122;
  39688. lower = (c3) => c3 | 32;
  39689. noop = () => {
  39690. };
  39691. MultipartParser = class {
  39692. /**
  39693. * @param {string} boundary
  39694. */
  39695. constructor(boundary) {
  39696. this.index = 0;
  39697. this.flags = 0;
  39698. this.onHeaderEnd = noop;
  39699. this.onHeaderField = noop;
  39700. this.onHeadersEnd = noop;
  39701. this.onHeaderValue = noop;
  39702. this.onPartBegin = noop;
  39703. this.onPartData = noop;
  39704. this.onPartEnd = noop;
  39705. this.boundaryChars = {};
  39706. boundary = "\r\n--" + boundary;
  39707. const ui8a = new Uint8Array(boundary.length);
  39708. for (let i4 = 0; i4 < boundary.length; i4++) {
  39709. ui8a[i4] = boundary.charCodeAt(i4);
  39710. this.boundaryChars[ui8a[i4]] = true;
  39711. }
  39712. this.boundary = ui8a;
  39713. this.lookbehind = new Uint8Array(this.boundary.length + 8);
  39714. this.state = S.START_BOUNDARY;
  39715. }
  39716. /**
  39717. * @param {Uint8Array} data
  39718. */
  39719. write(data) {
  39720. let i4 = 0;
  39721. const length_ = data.length;
  39722. let previousIndex = this.index;
  39723. let { lookbehind, boundary, boundaryChars, index: index6, state: state2, flags } = this;
  39724. const boundaryLength = this.boundary.length;
  39725. const boundaryEnd = boundaryLength - 1;
  39726. const bufferLength = data.length;
  39727. let c3;
  39728. let cl;
  39729. const mark = (name) => {
  39730. this[name + "Mark"] = i4;
  39731. };
  39732. const clear = (name) => {
  39733. delete this[name + "Mark"];
  39734. };
  39735. const callback = (callbackSymbol, start, end, ui8a) => {
  39736. if (start === void 0 || start !== end) {
  39737. this[callbackSymbol](ui8a && ui8a.subarray(start, end));
  39738. }
  39739. };
  39740. const dataCallback = (name, clear2) => {
  39741. const markSymbol = name + "Mark";
  39742. if (!(markSymbol in this)) {
  39743. return;
  39744. }
  39745. if (clear2) {
  39746. callback(name, this[markSymbol], i4, data);
  39747. delete this[markSymbol];
  39748. } else {
  39749. callback(name, this[markSymbol], data.length, data);
  39750. this[markSymbol] = 0;
  39751. }
  39752. };
  39753. for (i4 = 0; i4 < length_; i4++) {
  39754. c3 = data[i4];
  39755. switch (state2) {
  39756. case S.START_BOUNDARY:
  39757. if (index6 === boundary.length - 2) {
  39758. if (c3 === HYPHEN) {
  39759. flags |= F.LAST_BOUNDARY;
  39760. } else if (c3 !== CR) {
  39761. return;
  39762. }
  39763. index6++;
  39764. break;
  39765. } else if (index6 - 1 === boundary.length - 2) {
  39766. if (flags & F.LAST_BOUNDARY && c3 === HYPHEN) {
  39767. state2 = S.END;
  39768. flags = 0;
  39769. } else if (!(flags & F.LAST_BOUNDARY) && c3 === LF) {
  39770. index6 = 0;
  39771. callback("onPartBegin");
  39772. state2 = S.HEADER_FIELD_START;
  39773. } else {
  39774. return;
  39775. }
  39776. break;
  39777. }
  39778. if (c3 !== boundary[index6 + 2]) {
  39779. index6 = -2;
  39780. }
  39781. if (c3 === boundary[index6 + 2]) {
  39782. index6++;
  39783. }
  39784. break;
  39785. case S.HEADER_FIELD_START:
  39786. state2 = S.HEADER_FIELD;
  39787. mark("onHeaderField");
  39788. index6 = 0;
  39789. // falls through
  39790. case S.HEADER_FIELD:
  39791. if (c3 === CR) {
  39792. clear("onHeaderField");
  39793. state2 = S.HEADERS_ALMOST_DONE;
  39794. break;
  39795. }
  39796. index6++;
  39797. if (c3 === HYPHEN) {
  39798. break;
  39799. }
  39800. if (c3 === COLON) {
  39801. if (index6 === 1) {
  39802. return;
  39803. }
  39804. dataCallback("onHeaderField", true);
  39805. state2 = S.HEADER_VALUE_START;
  39806. break;
  39807. }
  39808. cl = lower(c3);
  39809. if (cl < A || cl > Z) {
  39810. return;
  39811. }
  39812. break;
  39813. case S.HEADER_VALUE_START:
  39814. if (c3 === SPACE) {
  39815. break;
  39816. }
  39817. mark("onHeaderValue");
  39818. state2 = S.HEADER_VALUE;
  39819. // falls through
  39820. case S.HEADER_VALUE:
  39821. if (c3 === CR) {
  39822. dataCallback("onHeaderValue", true);
  39823. callback("onHeaderEnd");
  39824. state2 = S.HEADER_VALUE_ALMOST_DONE;
  39825. }
  39826. break;
  39827. case S.HEADER_VALUE_ALMOST_DONE:
  39828. if (c3 !== LF) {
  39829. return;
  39830. }
  39831. state2 = S.HEADER_FIELD_START;
  39832. break;
  39833. case S.HEADERS_ALMOST_DONE:
  39834. if (c3 !== LF) {
  39835. return;
  39836. }
  39837. callback("onHeadersEnd");
  39838. state2 = S.PART_DATA_START;
  39839. break;
  39840. case S.PART_DATA_START:
  39841. state2 = S.PART_DATA;
  39842. mark("onPartData");
  39843. // falls through
  39844. case S.PART_DATA:
  39845. previousIndex = index6;
  39846. if (index6 === 0) {
  39847. i4 += boundaryEnd;
  39848. while (i4 < bufferLength && !(data[i4] in boundaryChars)) {
  39849. i4 += boundaryLength;
  39850. }
  39851. i4 -= boundaryEnd;
  39852. c3 = data[i4];
  39853. }
  39854. if (index6 < boundary.length) {
  39855. if (boundary[index6] === c3) {
  39856. if (index6 === 0) {
  39857. dataCallback("onPartData", true);
  39858. }
  39859. index6++;
  39860. } else {
  39861. index6 = 0;
  39862. }
  39863. } else if (index6 === boundary.length) {
  39864. index6++;
  39865. if (c3 === CR) {
  39866. flags |= F.PART_BOUNDARY;
  39867. } else if (c3 === HYPHEN) {
  39868. flags |= F.LAST_BOUNDARY;
  39869. } else {
  39870. index6 = 0;
  39871. }
  39872. } else if (index6 - 1 === boundary.length) {
  39873. if (flags & F.PART_BOUNDARY) {
  39874. index6 = 0;
  39875. if (c3 === LF) {
  39876. flags &= ~F.PART_BOUNDARY;
  39877. callback("onPartEnd");
  39878. callback("onPartBegin");
  39879. state2 = S.HEADER_FIELD_START;
  39880. break;
  39881. }
  39882. } else if (flags & F.LAST_BOUNDARY) {
  39883. if (c3 === HYPHEN) {
  39884. callback("onPartEnd");
  39885. state2 = S.END;
  39886. flags = 0;
  39887. } else {
  39888. index6 = 0;
  39889. }
  39890. } else {
  39891. index6 = 0;
  39892. }
  39893. }
  39894. if (index6 > 0) {
  39895. lookbehind[index6 - 1] = c3;
  39896. } else if (previousIndex > 0) {
  39897. const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);
  39898. callback("onPartData", 0, previousIndex, _lookbehind);
  39899. previousIndex = 0;
  39900. mark("onPartData");
  39901. i4--;
  39902. }
  39903. break;
  39904. case S.END:
  39905. break;
  39906. default:
  39907. throw new Error(`Unexpected state entered: ${state2}`);
  39908. }
  39909. }
  39910. dataCallback("onHeaderField");
  39911. dataCallback("onHeaderValue");
  39912. dataCallback("onPartData");
  39913. this.index = index6;
  39914. this.state = state2;
  39915. this.flags = flags;
  39916. }
  39917. end() {
  39918. if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) {
  39919. this.onPartEnd();
  39920. } else if (this.state !== S.END) {
  39921. throw new Error("MultipartParser.end(): stream ended unexpectedly");
  39922. }
  39923. }
  39924. };
  39925. }
  39926. });
  39927. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js
  39928. async function consumeBody(data) {
  39929. if (data[INTERNALS].disturbed) {
  39930. throw new TypeError(`body used already for: ${data.url}`);
  39931. }
  39932. data[INTERNALS].disturbed = true;
  39933. if (data[INTERNALS].error) {
  39934. throw data[INTERNALS].error;
  39935. }
  39936. const { body } = data;
  39937. if (body === null) {
  39938. return import_node_buffer.Buffer.alloc(0);
  39939. }
  39940. if (!(body instanceof import_node_stream.default)) {
  39941. return import_node_buffer.Buffer.alloc(0);
  39942. }
  39943. const accum = [];
  39944. let accumBytes = 0;
  39945. try {
  39946. for await (const chunk of body) {
  39947. if (data.size > 0 && accumBytes + chunk.length > data.size) {
  39948. const error2 = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size");
  39949. body.destroy(error2);
  39950. throw error2;
  39951. }
  39952. accumBytes += chunk.length;
  39953. accum.push(chunk);
  39954. }
  39955. } catch (error2) {
  39956. const error_ = error2 instanceof FetchBaseError ? error2 : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error2.message}`, "system", error2);
  39957. throw error_;
  39958. }
  39959. if (body.readableEnded === true || body._readableState.ended === true) {
  39960. try {
  39961. if (accum.every((c3) => typeof c3 === "string")) {
  39962. return import_node_buffer.Buffer.from(accum.join(""));
  39963. }
  39964. return import_node_buffer.Buffer.concat(accum, accumBytes);
  39965. } catch (error2) {
  39966. throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error2.message}`, "system", error2);
  39967. }
  39968. } else {
  39969. throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
  39970. }
  39971. }
  39972. var import_node_stream, import_node_util, import_node_buffer, pipeline, INTERNALS, Body, clone, getNonSpecFormDataBoundary, extractContentType, getTotalBytes, writeToStream;
  39973. var init_body = __esm({
  39974. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js"() {
  39975. import_node_stream = __toESM(require("node:stream"), 1);
  39976. import_node_util = require("node:util");
  39977. import_node_buffer = require("node:buffer");
  39978. init_fetch_blob();
  39979. init_esm_min();
  39980. init_fetch_error();
  39981. init_base();
  39982. init_is();
  39983. pipeline = (0, import_node_util.promisify)(import_node_stream.default.pipeline);
  39984. INTERNALS = Symbol("Body internals");
  39985. Body = class {
  39986. constructor(body, {
  39987. size = 0
  39988. } = {}) {
  39989. let boundary = null;
  39990. if (body === null) {
  39991. body = null;
  39992. } else if (isURLSearchParameters(body)) {
  39993. body = import_node_buffer.Buffer.from(body.toString());
  39994. } else if (isBlob2(body)) {
  39995. } else if (import_node_buffer.Buffer.isBuffer(body)) {
  39996. } else if (import_node_util.types.isAnyArrayBuffer(body)) {
  39997. body = import_node_buffer.Buffer.from(body);
  39998. } else if (ArrayBuffer.isView(body)) {
  39999. body = import_node_buffer.Buffer.from(body.buffer, body.byteOffset, body.byteLength);
  40000. } else if (body instanceof import_node_stream.default) {
  40001. } else if (body instanceof FormData) {
  40002. body = formDataToBlob(body);
  40003. boundary = body.type.split("=")[1];
  40004. } else {
  40005. body = import_node_buffer.Buffer.from(String(body));
  40006. }
  40007. let stream = body;
  40008. if (import_node_buffer.Buffer.isBuffer(body)) {
  40009. stream = import_node_stream.default.Readable.from(body);
  40010. } else if (isBlob2(body)) {
  40011. stream = import_node_stream.default.Readable.from(body.stream());
  40012. }
  40013. this[INTERNALS] = {
  40014. body,
  40015. stream,
  40016. boundary,
  40017. disturbed: false,
  40018. error: null
  40019. };
  40020. this.size = size;
  40021. if (body instanceof import_node_stream.default) {
  40022. body.on("error", (error_) => {
  40023. const error2 = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
  40024. this[INTERNALS].error = error2;
  40025. });
  40026. }
  40027. }
  40028. get body() {
  40029. return this[INTERNALS].stream;
  40030. }
  40031. get bodyUsed() {
  40032. return this[INTERNALS].disturbed;
  40033. }
  40034. /**
  40035. * Decode response as ArrayBuffer
  40036. *
  40037. * @return Promise
  40038. */
  40039. async arrayBuffer() {
  40040. const { buffer, byteOffset, byteLength } = await consumeBody(this);
  40041. return buffer.slice(byteOffset, byteOffset + byteLength);
  40042. }
  40043. async formData() {
  40044. const ct = this.headers.get("content-type");
  40045. if (ct.startsWith("application/x-www-form-urlencoded")) {
  40046. const formData = new FormData();
  40047. const parameters = new URLSearchParams(await this.text());
  40048. for (const [name, value] of parameters) {
  40049. formData.append(name, value);
  40050. }
  40051. return formData;
  40052. }
  40053. const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports));
  40054. return toFormData2(this.body, ct);
  40055. }
  40056. /**
  40057. * Return raw response as Blob
  40058. *
  40059. * @return Promise
  40060. */
  40061. async blob() {
  40062. const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || "";
  40063. const buf = await this.arrayBuffer();
  40064. return new fetch_blob_default([buf], {
  40065. type: ct
  40066. });
  40067. }
  40068. /**
  40069. * Decode response as json
  40070. *
  40071. * @return Promise
  40072. */
  40073. async json() {
  40074. const text = await this.text();
  40075. return JSON.parse(text);
  40076. }
  40077. /**
  40078. * Decode response as text
  40079. *
  40080. * @return Promise
  40081. */
  40082. async text() {
  40083. const buffer = await consumeBody(this);
  40084. return new TextDecoder().decode(buffer);
  40085. }
  40086. /**
  40087. * Decode response as buffer (non-spec api)
  40088. *
  40089. * @return Promise
  40090. */
  40091. buffer() {
  40092. return consumeBody(this);
  40093. }
  40094. };
  40095. Body.prototype.buffer = (0, import_node_util.deprecate)(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer");
  40096. Object.defineProperties(Body.prototype, {
  40097. body: { enumerable: true },
  40098. bodyUsed: { enumerable: true },
  40099. arrayBuffer: { enumerable: true },
  40100. blob: { enumerable: true },
  40101. json: { enumerable: true },
  40102. text: { enumerable: true },
  40103. data: { get: (0, import_node_util.deprecate)(
  40104. () => {
  40105. },
  40106. "data doesn't exist, use json(), text(), arrayBuffer(), or body instead",
  40107. "https://github.com/node-fetch/node-fetch/issues/1000 (response)"
  40108. ) }
  40109. });
  40110. clone = (instance, highWaterMark) => {
  40111. let p1;
  40112. let p22;
  40113. let { body } = instance[INTERNALS];
  40114. if (instance.bodyUsed) {
  40115. throw new Error("cannot clone body after it is used");
  40116. }
  40117. if (body instanceof import_node_stream.default && typeof body.getBoundary !== "function") {
  40118. p1 = new import_node_stream.PassThrough({ highWaterMark });
  40119. p22 = new import_node_stream.PassThrough({ highWaterMark });
  40120. body.pipe(p1);
  40121. body.pipe(p22);
  40122. instance[INTERNALS].stream = p1;
  40123. body = p22;
  40124. }
  40125. return body;
  40126. };
  40127. getNonSpecFormDataBoundary = (0, import_node_util.deprecate)(
  40128. (body) => body.getBoundary(),
  40129. "form-data doesn't follow the spec and requires special treatment. Use alternative package",
  40130. "https://github.com/node-fetch/node-fetch/issues/1167"
  40131. );
  40132. extractContentType = (body, request) => {
  40133. if (body === null) {
  40134. return null;
  40135. }
  40136. if (typeof body === "string") {
  40137. return "text/plain;charset=UTF-8";
  40138. }
  40139. if (isURLSearchParameters(body)) {
  40140. return "application/x-www-form-urlencoded;charset=UTF-8";
  40141. }
  40142. if (isBlob2(body)) {
  40143. return body.type || null;
  40144. }
  40145. if (import_node_buffer.Buffer.isBuffer(body) || import_node_util.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
  40146. return null;
  40147. }
  40148. if (body instanceof FormData) {
  40149. return `multipart/form-data; boundary=${request[INTERNALS].boundary}`;
  40150. }
  40151. if (body && typeof body.getBoundary === "function") {
  40152. return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
  40153. }
  40154. if (body instanceof import_node_stream.default) {
  40155. return null;
  40156. }
  40157. return "text/plain;charset=UTF-8";
  40158. };
  40159. getTotalBytes = (request) => {
  40160. const { body } = request[INTERNALS];
  40161. if (body === null) {
  40162. return 0;
  40163. }
  40164. if (isBlob2(body)) {
  40165. return body.size;
  40166. }
  40167. if (import_node_buffer.Buffer.isBuffer(body)) {
  40168. return body.length;
  40169. }
  40170. if (body && typeof body.getLengthSync === "function") {
  40171. return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
  40172. }
  40173. return null;
  40174. };
  40175. writeToStream = async (dest, { body }) => {
  40176. if (body === null) {
  40177. dest.end();
  40178. } else {
  40179. await pipeline(body, dest);
  40180. }
  40181. };
  40182. }
  40183. });
  40184. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js
  40185. function fromRawHeaders(headers = []) {
  40186. return new Headers2(
  40187. headers.reduce((result, value, index6, array2) => {
  40188. if (index6 % 2 === 0) {
  40189. result.push(array2.slice(index6, index6 + 2));
  40190. }
  40191. return result;
  40192. }, []).filter(([name, value]) => {
  40193. try {
  40194. validateHeaderName(name);
  40195. validateHeaderValue(name, String(value));
  40196. return true;
  40197. } catch {
  40198. return false;
  40199. }
  40200. })
  40201. );
  40202. }
  40203. var import_node_util2, import_node_http, validateHeaderName, validateHeaderValue, Headers2;
  40204. var init_headers = __esm({
  40205. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js"() {
  40206. import_node_util2 = require("node:util");
  40207. import_node_http = __toESM(require("node:http"), 1);
  40208. validateHeaderName = typeof import_node_http.default.validateHeaderName === "function" ? import_node_http.default.validateHeaderName : (name) => {
  40209. if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
  40210. const error2 = new TypeError(`Header name must be a valid HTTP token [${name}]`);
  40211. Object.defineProperty(error2, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
  40212. throw error2;
  40213. }
  40214. };
  40215. validateHeaderValue = typeof import_node_http.default.validateHeaderValue === "function" ? import_node_http.default.validateHeaderValue : (name, value) => {
  40216. if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
  40217. const error2 = new TypeError(`Invalid character in header content ["${name}"]`);
  40218. Object.defineProperty(error2, "code", { value: "ERR_INVALID_CHAR" });
  40219. throw error2;
  40220. }
  40221. };
  40222. Headers2 = class _Headers extends URLSearchParams {
  40223. /**
  40224. * Headers class
  40225. *
  40226. * @constructor
  40227. * @param {HeadersInit} [init] - Response headers
  40228. */
  40229. constructor(init2) {
  40230. let result = [];
  40231. if (init2 instanceof _Headers) {
  40232. const raw2 = init2.raw();
  40233. for (const [name, values] of Object.entries(raw2)) {
  40234. result.push(...values.map((value) => [name, value]));
  40235. }
  40236. } else if (init2 == null) {
  40237. } else if (typeof init2 === "object" && !import_node_util2.types.isBoxedPrimitive(init2)) {
  40238. const method = init2[Symbol.iterator];
  40239. if (method == null) {
  40240. result.push(...Object.entries(init2));
  40241. } else {
  40242. if (typeof method !== "function") {
  40243. throw new TypeError("Header pairs must be iterable");
  40244. }
  40245. result = [...init2].map((pair) => {
  40246. if (typeof pair !== "object" || import_node_util2.types.isBoxedPrimitive(pair)) {
  40247. throw new TypeError("Each header pair must be an iterable object");
  40248. }
  40249. return [...pair];
  40250. }).map((pair) => {
  40251. if (pair.length !== 2) {
  40252. throw new TypeError("Each header pair must be a name/value tuple");
  40253. }
  40254. return [...pair];
  40255. });
  40256. }
  40257. } else {
  40258. throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");
  40259. }
  40260. result = result.length > 0 ? result.map(([name, value]) => {
  40261. validateHeaderName(name);
  40262. validateHeaderValue(name, String(value));
  40263. return [String(name).toLowerCase(), String(value)];
  40264. }) : void 0;
  40265. super(result);
  40266. return new Proxy(this, {
  40267. get(target, p3, receiver) {
  40268. switch (p3) {
  40269. case "append":
  40270. case "set":
  40271. return (name, value) => {
  40272. validateHeaderName(name);
  40273. validateHeaderValue(name, String(value));
  40274. return URLSearchParams.prototype[p3].call(
  40275. target,
  40276. String(name).toLowerCase(),
  40277. String(value)
  40278. );
  40279. };
  40280. case "delete":
  40281. case "has":
  40282. case "getAll":
  40283. return (name) => {
  40284. validateHeaderName(name);
  40285. return URLSearchParams.prototype[p3].call(
  40286. target,
  40287. String(name).toLowerCase()
  40288. );
  40289. };
  40290. case "keys":
  40291. return () => {
  40292. target.sort();
  40293. return new Set(URLSearchParams.prototype.keys.call(target)).keys();
  40294. };
  40295. default:
  40296. return Reflect.get(target, p3, receiver);
  40297. }
  40298. }
  40299. });
  40300. }
  40301. get [Symbol.toStringTag]() {
  40302. return this.constructor.name;
  40303. }
  40304. toString() {
  40305. return Object.prototype.toString.call(this);
  40306. }
  40307. get(name) {
  40308. const values = this.getAll(name);
  40309. if (values.length === 0) {
  40310. return null;
  40311. }
  40312. let value = values.join(", ");
  40313. if (/^content-encoding$/i.test(name)) {
  40314. value = value.toLowerCase();
  40315. }
  40316. return value;
  40317. }
  40318. forEach(callback, thisArg = void 0) {
  40319. for (const name of this.keys()) {
  40320. Reflect.apply(callback, thisArg, [this.get(name), name, this]);
  40321. }
  40322. }
  40323. *values() {
  40324. for (const name of this.keys()) {
  40325. yield this.get(name);
  40326. }
  40327. }
  40328. /**
  40329. * @type {() => IterableIterator<[string, string]>}
  40330. */
  40331. *entries() {
  40332. for (const name of this.keys()) {
  40333. yield [name, this.get(name)];
  40334. }
  40335. }
  40336. [Symbol.iterator]() {
  40337. return this.entries();
  40338. }
  40339. /**
  40340. * Node-fetch non-spec method
  40341. * returning all headers and their values as array
  40342. * @returns {Record<string, string[]>}
  40343. */
  40344. raw() {
  40345. return [...this.keys()].reduce((result, key) => {
  40346. result[key] = this.getAll(key);
  40347. return result;
  40348. }, {});
  40349. }
  40350. /**
  40351. * For better console.log(headers) and also to convert Headers into Node.js Request compatible format
  40352. */
  40353. [Symbol.for("nodejs.util.inspect.custom")]() {
  40354. return [...this.keys()].reduce((result, key) => {
  40355. const values = this.getAll(key);
  40356. if (key === "host") {
  40357. result[key] = values[0];
  40358. } else {
  40359. result[key] = values.length > 1 ? values : values[0];
  40360. }
  40361. return result;
  40362. }, {});
  40363. }
  40364. };
  40365. Object.defineProperties(
  40366. Headers2.prototype,
  40367. ["get", "entries", "forEach", "values"].reduce((result, property) => {
  40368. result[property] = { enumerable: true };
  40369. return result;
  40370. }, {})
  40371. );
  40372. }
  40373. });
  40374. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js
  40375. var redirectStatus, isRedirect;
  40376. var init_is_redirect = __esm({
  40377. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js"() {
  40378. redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
  40379. isRedirect = (code) => {
  40380. return redirectStatus.has(code);
  40381. };
  40382. }
  40383. });
  40384. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js
  40385. var INTERNALS2, Response2;
  40386. var init_response = __esm({
  40387. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js"() {
  40388. init_headers();
  40389. init_body();
  40390. init_is_redirect();
  40391. INTERNALS2 = Symbol("Response internals");
  40392. Response2 = class _Response2 extends Body {
  40393. constructor(body = null, options = {}) {
  40394. super(body, options);
  40395. const status = options.status != null ? options.status : 200;
  40396. const headers = new Headers2(options.headers);
  40397. if (body !== null && !headers.has("Content-Type")) {
  40398. const contentType = extractContentType(body, this);
  40399. if (contentType) {
  40400. headers.append("Content-Type", contentType);
  40401. }
  40402. }
  40403. this[INTERNALS2] = {
  40404. type: "default",
  40405. url: options.url,
  40406. status,
  40407. statusText: options.statusText || "",
  40408. headers,
  40409. counter: options.counter,
  40410. highWaterMark: options.highWaterMark
  40411. };
  40412. }
  40413. get type() {
  40414. return this[INTERNALS2].type;
  40415. }
  40416. get url() {
  40417. return this[INTERNALS2].url || "";
  40418. }
  40419. get status() {
  40420. return this[INTERNALS2].status;
  40421. }
  40422. /**
  40423. * Convenience property representing if the request ended normally
  40424. */
  40425. get ok() {
  40426. return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300;
  40427. }
  40428. get redirected() {
  40429. return this[INTERNALS2].counter > 0;
  40430. }
  40431. get statusText() {
  40432. return this[INTERNALS2].statusText;
  40433. }
  40434. get headers() {
  40435. return this[INTERNALS2].headers;
  40436. }
  40437. get highWaterMark() {
  40438. return this[INTERNALS2].highWaterMark;
  40439. }
  40440. /**
  40441. * Clone this response
  40442. *
  40443. * @return Response
  40444. */
  40445. clone() {
  40446. return new _Response2(clone(this, this.highWaterMark), {
  40447. type: this.type,
  40448. url: this.url,
  40449. status: this.status,
  40450. statusText: this.statusText,
  40451. headers: this.headers,
  40452. ok: this.ok,
  40453. redirected: this.redirected,
  40454. size: this.size,
  40455. highWaterMark: this.highWaterMark
  40456. });
  40457. }
  40458. /**
  40459. * @param {string} url The URL that the new response is to originate from.
  40460. * @param {number} status An optional status code for the response (e.g., 302.)
  40461. * @returns {Response} A Response object.
  40462. */
  40463. static redirect(url, status = 302) {
  40464. if (!isRedirect(status)) {
  40465. throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
  40466. }
  40467. return new _Response2(null, {
  40468. headers: {
  40469. location: new URL(url).toString()
  40470. },
  40471. status
  40472. });
  40473. }
  40474. static error() {
  40475. const response = new _Response2(null, { status: 0, statusText: "" });
  40476. response[INTERNALS2].type = "error";
  40477. return response;
  40478. }
  40479. static json(data = void 0, init2 = {}) {
  40480. const body = JSON.stringify(data);
  40481. if (body === void 0) {
  40482. throw new TypeError("data is not JSON serializable");
  40483. }
  40484. const headers = new Headers2(init2 && init2.headers);
  40485. if (!headers.has("content-type")) {
  40486. headers.set("content-type", "application/json");
  40487. }
  40488. return new _Response2(body, {
  40489. ...init2,
  40490. headers
  40491. });
  40492. }
  40493. get [Symbol.toStringTag]() {
  40494. return "Response";
  40495. }
  40496. };
  40497. Object.defineProperties(Response2.prototype, {
  40498. type: { enumerable: true },
  40499. url: { enumerable: true },
  40500. status: { enumerable: true },
  40501. ok: { enumerable: true },
  40502. redirected: { enumerable: true },
  40503. statusText: { enumerable: true },
  40504. headers: { enumerable: true },
  40505. clone: { enumerable: true }
  40506. });
  40507. }
  40508. });
  40509. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js
  40510. var getSearch;
  40511. var init_get_search = __esm({
  40512. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js"() {
  40513. getSearch = (parsedURL) => {
  40514. if (parsedURL.search) {
  40515. return parsedURL.search;
  40516. }
  40517. const lastOffset = parsedURL.href.length - 1;
  40518. const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
  40519. return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : "";
  40520. };
  40521. }
  40522. });
  40523. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js
  40524. function stripURLForUseAsAReferrer(url, originOnly = false) {
  40525. if (url == null) {
  40526. return "no-referrer";
  40527. }
  40528. url = new URL(url);
  40529. if (/^(about|blob|data):$/.test(url.protocol)) {
  40530. return "no-referrer";
  40531. }
  40532. url.username = "";
  40533. url.password = "";
  40534. url.hash = "";
  40535. if (originOnly) {
  40536. url.pathname = "";
  40537. url.search = "";
  40538. }
  40539. return url;
  40540. }
  40541. function validateReferrerPolicy(referrerPolicy) {
  40542. if (!ReferrerPolicy.has(referrerPolicy)) {
  40543. throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
  40544. }
  40545. return referrerPolicy;
  40546. }
  40547. function isOriginPotentiallyTrustworthy(url) {
  40548. if (/^(http|ws)s:$/.test(url.protocol)) {
  40549. return true;
  40550. }
  40551. const hostIp = url.host.replace(/(^\[)|(]$)/g, "");
  40552. const hostIPVersion = (0, import_node_net.isIP)(hostIp);
  40553. if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
  40554. return true;
  40555. }
  40556. if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
  40557. return true;
  40558. }
  40559. if (url.host === "localhost" || url.host.endsWith(".localhost")) {
  40560. return false;
  40561. }
  40562. if (url.protocol === "file:") {
  40563. return true;
  40564. }
  40565. return false;
  40566. }
  40567. function isUrlPotentiallyTrustworthy(url) {
  40568. if (/^about:(blank|srcdoc)$/.test(url)) {
  40569. return true;
  40570. }
  40571. if (url.protocol === "data:") {
  40572. return true;
  40573. }
  40574. if (/^(blob|filesystem):$/.test(url.protocol)) {
  40575. return true;
  40576. }
  40577. return isOriginPotentiallyTrustworthy(url);
  40578. }
  40579. function determineRequestsReferrer(request, { referrerURLCallback, referrerOriginCallback } = {}) {
  40580. if (request.referrer === "no-referrer" || request.referrerPolicy === "") {
  40581. return null;
  40582. }
  40583. const policy5 = request.referrerPolicy;
  40584. if (request.referrer === "about:client") {
  40585. return "no-referrer";
  40586. }
  40587. const referrerSource = request.referrer;
  40588. let referrerURL = stripURLForUseAsAReferrer(referrerSource);
  40589. let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
  40590. if (referrerURL.toString().length > 4096) {
  40591. referrerURL = referrerOrigin;
  40592. }
  40593. if (referrerURLCallback) {
  40594. referrerURL = referrerURLCallback(referrerURL);
  40595. }
  40596. if (referrerOriginCallback) {
  40597. referrerOrigin = referrerOriginCallback(referrerOrigin);
  40598. }
  40599. const currentURL = new URL(request.url);
  40600. switch (policy5) {
  40601. case "no-referrer":
  40602. return "no-referrer";
  40603. case "origin":
  40604. return referrerOrigin;
  40605. case "unsafe-url":
  40606. return referrerURL;
  40607. case "strict-origin":
  40608. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
  40609. return "no-referrer";
  40610. }
  40611. return referrerOrigin.toString();
  40612. case "strict-origin-when-cross-origin":
  40613. if (referrerURL.origin === currentURL.origin) {
  40614. return referrerURL;
  40615. }
  40616. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
  40617. return "no-referrer";
  40618. }
  40619. return referrerOrigin;
  40620. case "same-origin":
  40621. if (referrerURL.origin === currentURL.origin) {
  40622. return referrerURL;
  40623. }
  40624. return "no-referrer";
  40625. case "origin-when-cross-origin":
  40626. if (referrerURL.origin === currentURL.origin) {
  40627. return referrerURL;
  40628. }
  40629. return referrerOrigin;
  40630. case "no-referrer-when-downgrade":
  40631. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
  40632. return "no-referrer";
  40633. }
  40634. return referrerURL;
  40635. default:
  40636. throw new TypeError(`Invalid referrerPolicy: ${policy5}`);
  40637. }
  40638. }
  40639. function parseReferrerPolicyFromHeader(headers) {
  40640. const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
  40641. let policy5 = "";
  40642. for (const token of policyTokens) {
  40643. if (token && ReferrerPolicy.has(token)) {
  40644. policy5 = token;
  40645. }
  40646. }
  40647. return policy5;
  40648. }
  40649. var import_node_net, ReferrerPolicy, DEFAULT_REFERRER_POLICY;
  40650. var init_referrer = __esm({
  40651. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js"() {
  40652. import_node_net = require("node:net");
  40653. ReferrerPolicy = /* @__PURE__ */ new Set([
  40654. "",
  40655. "no-referrer",
  40656. "no-referrer-when-downgrade",
  40657. "same-origin",
  40658. "origin",
  40659. "strict-origin",
  40660. "origin-when-cross-origin",
  40661. "strict-origin-when-cross-origin",
  40662. "unsafe-url"
  40663. ]);
  40664. DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin";
  40665. }
  40666. });
  40667. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js
  40668. var import_node_url, import_node_util3, INTERNALS3, isRequest, doBadDataWarn, Request2, getNodeRequestOptions;
  40669. var init_request = __esm({
  40670. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js"() {
  40671. import_node_url = require("node:url");
  40672. import_node_util3 = require("node:util");
  40673. init_headers();
  40674. init_body();
  40675. init_is();
  40676. init_get_search();
  40677. init_referrer();
  40678. INTERNALS3 = Symbol("Request internals");
  40679. isRequest = (object) => {
  40680. return typeof object === "object" && typeof object[INTERNALS3] === "object";
  40681. };
  40682. doBadDataWarn = (0, import_node_util3.deprecate)(
  40683. () => {
  40684. },
  40685. ".data is not a valid RequestInit property, use .body instead",
  40686. "https://github.com/node-fetch/node-fetch/issues/1000 (request)"
  40687. );
  40688. Request2 = class _Request extends Body {
  40689. constructor(input, init2 = {}) {
  40690. let parsedURL;
  40691. if (isRequest(input)) {
  40692. parsedURL = new URL(input.url);
  40693. } else {
  40694. parsedURL = new URL(input);
  40695. input = {};
  40696. }
  40697. if (parsedURL.username !== "" || parsedURL.password !== "") {
  40698. throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
  40699. }
  40700. let method = init2.method || input.method || "GET";
  40701. if (/^(delete|get|head|options|post|put)$/i.test(method)) {
  40702. method = method.toUpperCase();
  40703. }
  40704. if (!isRequest(init2) && "data" in init2) {
  40705. doBadDataWarn();
  40706. }
  40707. if ((init2.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
  40708. throw new TypeError("Request with GET/HEAD method cannot have body");
  40709. }
  40710. const inputBody = init2.body ? init2.body : isRequest(input) && input.body !== null ? clone(input) : null;
  40711. super(inputBody, {
  40712. size: init2.size || input.size || 0
  40713. });
  40714. const headers = new Headers2(init2.headers || input.headers || {});
  40715. if (inputBody !== null && !headers.has("Content-Type")) {
  40716. const contentType = extractContentType(inputBody, this);
  40717. if (contentType) {
  40718. headers.set("Content-Type", contentType);
  40719. }
  40720. }
  40721. let signal = isRequest(input) ? input.signal : null;
  40722. if ("signal" in init2) {
  40723. signal = init2.signal;
  40724. }
  40725. if (signal != null && !isAbortSignal(signal)) {
  40726. throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");
  40727. }
  40728. let referrer = init2.referrer == null ? input.referrer : init2.referrer;
  40729. if (referrer === "") {
  40730. referrer = "no-referrer";
  40731. } else if (referrer) {
  40732. const parsedReferrer = new URL(referrer);
  40733. referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer;
  40734. } else {
  40735. referrer = void 0;
  40736. }
  40737. this[INTERNALS3] = {
  40738. method,
  40739. redirect: init2.redirect || input.redirect || "follow",
  40740. headers,
  40741. parsedURL,
  40742. signal,
  40743. referrer
  40744. };
  40745. this.follow = init2.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init2.follow;
  40746. this.compress = init2.compress === void 0 ? input.compress === void 0 ? true : input.compress : init2.compress;
  40747. this.counter = init2.counter || input.counter || 0;
  40748. this.agent = init2.agent || input.agent;
  40749. this.highWaterMark = init2.highWaterMark || input.highWaterMark || 16384;
  40750. this.insecureHTTPParser = init2.insecureHTTPParser || input.insecureHTTPParser || false;
  40751. this.referrerPolicy = init2.referrerPolicy || input.referrerPolicy || "";
  40752. }
  40753. /** @returns {string} */
  40754. get method() {
  40755. return this[INTERNALS3].method;
  40756. }
  40757. /** @returns {string} */
  40758. get url() {
  40759. return (0, import_node_url.format)(this[INTERNALS3].parsedURL);
  40760. }
  40761. /** @returns {Headers} */
  40762. get headers() {
  40763. return this[INTERNALS3].headers;
  40764. }
  40765. get redirect() {
  40766. return this[INTERNALS3].redirect;
  40767. }
  40768. /** @returns {AbortSignal} */
  40769. get signal() {
  40770. return this[INTERNALS3].signal;
  40771. }
  40772. // https://fetch.spec.whatwg.org/#dom-request-referrer
  40773. get referrer() {
  40774. if (this[INTERNALS3].referrer === "no-referrer") {
  40775. return "";
  40776. }
  40777. if (this[INTERNALS3].referrer === "client") {
  40778. return "about:client";
  40779. }
  40780. if (this[INTERNALS3].referrer) {
  40781. return this[INTERNALS3].referrer.toString();
  40782. }
  40783. return void 0;
  40784. }
  40785. get referrerPolicy() {
  40786. return this[INTERNALS3].referrerPolicy;
  40787. }
  40788. set referrerPolicy(referrerPolicy) {
  40789. this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy);
  40790. }
  40791. /**
  40792. * Clone this request
  40793. *
  40794. * @return Request
  40795. */
  40796. clone() {
  40797. return new _Request(this);
  40798. }
  40799. get [Symbol.toStringTag]() {
  40800. return "Request";
  40801. }
  40802. };
  40803. Object.defineProperties(Request2.prototype, {
  40804. method: { enumerable: true },
  40805. url: { enumerable: true },
  40806. headers: { enumerable: true },
  40807. redirect: { enumerable: true },
  40808. clone: { enumerable: true },
  40809. signal: { enumerable: true },
  40810. referrer: { enumerable: true },
  40811. referrerPolicy: { enumerable: true }
  40812. });
  40813. getNodeRequestOptions = (request) => {
  40814. const { parsedURL } = request[INTERNALS3];
  40815. const headers = new Headers2(request[INTERNALS3].headers);
  40816. if (!headers.has("Accept")) {
  40817. headers.set("Accept", "*/*");
  40818. }
  40819. let contentLengthValue = null;
  40820. if (request.body === null && /^(post|put)$/i.test(request.method)) {
  40821. contentLengthValue = "0";
  40822. }
  40823. if (request.body !== null) {
  40824. const totalBytes = getTotalBytes(request);
  40825. if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) {
  40826. contentLengthValue = String(totalBytes);
  40827. }
  40828. }
  40829. if (contentLengthValue) {
  40830. headers.set("Content-Length", contentLengthValue);
  40831. }
  40832. if (request.referrerPolicy === "") {
  40833. request.referrerPolicy = DEFAULT_REFERRER_POLICY;
  40834. }
  40835. if (request.referrer && request.referrer !== "no-referrer") {
  40836. request[INTERNALS3].referrer = determineRequestsReferrer(request);
  40837. } else {
  40838. request[INTERNALS3].referrer = "no-referrer";
  40839. }
  40840. if (request[INTERNALS3].referrer instanceof URL) {
  40841. headers.set("Referer", request.referrer);
  40842. }
  40843. if (!headers.has("User-Agent")) {
  40844. headers.set("User-Agent", "node-fetch");
  40845. }
  40846. if (request.compress && !headers.has("Accept-Encoding")) {
  40847. headers.set("Accept-Encoding", "gzip, deflate, br");
  40848. }
  40849. let { agent } = request;
  40850. if (typeof agent === "function") {
  40851. agent = agent(parsedURL);
  40852. }
  40853. const search = getSearch(parsedURL);
  40854. const options = {
  40855. // Overwrite search to retain trailing ? (issue #776)
  40856. path: parsedURL.pathname + search,
  40857. // The following options are not expressed in the URL
  40858. method: request.method,
  40859. headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
  40860. insecureHTTPParser: request.insecureHTTPParser,
  40861. agent
  40862. };
  40863. return {
  40864. /** @type {URL} */
  40865. parsedURL,
  40866. options
  40867. };
  40868. };
  40869. }
  40870. });
  40871. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js
  40872. var AbortError;
  40873. var init_abort_error = __esm({
  40874. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js"() {
  40875. init_base();
  40876. AbortError = class extends FetchBaseError {
  40877. constructor(message, type = "aborted") {
  40878. super(message, type);
  40879. }
  40880. };
  40881. }
  40882. });
  40883. // ../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js
  40884. async function fetch2(url, options_) {
  40885. return new Promise((resolve2, reject) => {
  40886. const request = new Request2(url, options_);
  40887. const { parsedURL, options } = getNodeRequestOptions(request);
  40888. if (!supportedSchemas.has(parsedURL.protocol)) {
  40889. throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`);
  40890. }
  40891. if (parsedURL.protocol === "data:") {
  40892. const data = dist_default(request.url);
  40893. const response2 = new Response2(data, { headers: { "Content-Type": data.typeFull } });
  40894. resolve2(response2);
  40895. return;
  40896. }
  40897. const send = (parsedURL.protocol === "https:" ? import_node_https.default : import_node_http2.default).request;
  40898. const { signal } = request;
  40899. let response = null;
  40900. const abort = () => {
  40901. const error2 = new AbortError("The operation was aborted.");
  40902. reject(error2);
  40903. if (request.body && request.body instanceof import_node_stream2.default.Readable) {
  40904. request.body.destroy(error2);
  40905. }
  40906. if (!response || !response.body) {
  40907. return;
  40908. }
  40909. response.body.emit("error", error2);
  40910. };
  40911. if (signal && signal.aborted) {
  40912. abort();
  40913. return;
  40914. }
  40915. const abortAndFinalize = () => {
  40916. abort();
  40917. finalize();
  40918. };
  40919. const request_ = send(parsedURL.toString(), options);
  40920. if (signal) {
  40921. signal.addEventListener("abort", abortAndFinalize);
  40922. }
  40923. const finalize = () => {
  40924. request_.abort();
  40925. if (signal) {
  40926. signal.removeEventListener("abort", abortAndFinalize);
  40927. }
  40928. };
  40929. request_.on("error", (error2) => {
  40930. reject(new FetchError(`request to ${request.url} failed, reason: ${error2.message}`, "system", error2));
  40931. finalize();
  40932. });
  40933. fixResponseChunkedTransferBadEnding(request_, (error2) => {
  40934. if (response && response.body) {
  40935. response.body.destroy(error2);
  40936. }
  40937. });
  40938. if (process.version < "v14") {
  40939. request_.on("socket", (s4) => {
  40940. let endedWithEventsCount;
  40941. s4.prependListener("end", () => {
  40942. endedWithEventsCount = s4._eventsCount;
  40943. });
  40944. s4.prependListener("close", (hadError) => {
  40945. if (response && endedWithEventsCount < s4._eventsCount && !hadError) {
  40946. const error2 = new Error("Premature close");
  40947. error2.code = "ERR_STREAM_PREMATURE_CLOSE";
  40948. response.body.emit("error", error2);
  40949. }
  40950. });
  40951. });
  40952. }
  40953. request_.on("response", (response_) => {
  40954. request_.setTimeout(0);
  40955. const headers = fromRawHeaders(response_.rawHeaders);
  40956. if (isRedirect(response_.statusCode)) {
  40957. const location = headers.get("Location");
  40958. let locationURL = null;
  40959. try {
  40960. locationURL = location === null ? null : new URL(location, request.url);
  40961. } catch {
  40962. if (request.redirect !== "manual") {
  40963. reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect"));
  40964. finalize();
  40965. return;
  40966. }
  40967. }
  40968. switch (request.redirect) {
  40969. case "error":
  40970. reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, "no-redirect"));
  40971. finalize();
  40972. return;
  40973. case "manual":
  40974. break;
  40975. case "follow": {
  40976. if (locationURL === null) {
  40977. break;
  40978. }
  40979. if (request.counter >= request.follow) {
  40980. reject(new FetchError(`maximum redirect reached at: ${request.url}`, "max-redirect"));
  40981. finalize();
  40982. return;
  40983. }
  40984. const requestOptions = {
  40985. headers: new Headers2(request.headers),
  40986. follow: request.follow,
  40987. counter: request.counter + 1,
  40988. agent: request.agent,
  40989. compress: request.compress,
  40990. method: request.method,
  40991. body: clone(request),
  40992. signal: request.signal,
  40993. size: request.size,
  40994. referrer: request.referrer,
  40995. referrerPolicy: request.referrerPolicy
  40996. };
  40997. if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
  40998. for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
  40999. requestOptions.headers.delete(name);
  41000. }
  41001. }
  41002. if (response_.statusCode !== 303 && request.body && options_.body instanceof import_node_stream2.default.Readable) {
  41003. reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect"));
  41004. finalize();
  41005. return;
  41006. }
  41007. if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request.method === "POST") {
  41008. requestOptions.method = "GET";
  41009. requestOptions.body = void 0;
  41010. requestOptions.headers.delete("content-length");
  41011. }
  41012. const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);
  41013. if (responseReferrerPolicy) {
  41014. requestOptions.referrerPolicy = responseReferrerPolicy;
  41015. }
  41016. resolve2(fetch2(new Request2(locationURL, requestOptions)));
  41017. finalize();
  41018. return;
  41019. }
  41020. default:
  41021. return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`));
  41022. }
  41023. }
  41024. if (signal) {
  41025. response_.once("end", () => {
  41026. signal.removeEventListener("abort", abortAndFinalize);
  41027. });
  41028. }
  41029. let body = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error2) => {
  41030. if (error2) {
  41031. reject(error2);
  41032. }
  41033. });
  41034. if (process.version < "v12.10") {
  41035. response_.on("aborted", abortAndFinalize);
  41036. }
  41037. const responseOptions = {
  41038. url: request.url,
  41039. status: response_.statusCode,
  41040. statusText: response_.statusMessage,
  41041. headers,
  41042. size: request.size,
  41043. counter: request.counter,
  41044. highWaterMark: request.highWaterMark
  41045. };
  41046. const codings = headers.get("Content-Encoding");
  41047. if (!request.compress || request.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
  41048. response = new Response2(body, responseOptions);
  41049. resolve2(response);
  41050. return;
  41051. }
  41052. const zlibOptions = {
  41053. flush: import_node_zlib.default.Z_SYNC_FLUSH,
  41054. finishFlush: import_node_zlib.default.Z_SYNC_FLUSH
  41055. };
  41056. if (codings === "gzip" || codings === "x-gzip") {
  41057. body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createGunzip(zlibOptions), (error2) => {
  41058. if (error2) {
  41059. reject(error2);
  41060. }
  41061. });
  41062. response = new Response2(body, responseOptions);
  41063. resolve2(response);
  41064. return;
  41065. }
  41066. if (codings === "deflate" || codings === "x-deflate") {
  41067. const raw2 = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error2) => {
  41068. if (error2) {
  41069. reject(error2);
  41070. }
  41071. });
  41072. raw2.once("data", (chunk) => {
  41073. if ((chunk[0] & 15) === 8) {
  41074. body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflate(), (error2) => {
  41075. if (error2) {
  41076. reject(error2);
  41077. }
  41078. });
  41079. } else {
  41080. body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflateRaw(), (error2) => {
  41081. if (error2) {
  41082. reject(error2);
  41083. }
  41084. });
  41085. }
  41086. response = new Response2(body, responseOptions);
  41087. resolve2(response);
  41088. });
  41089. raw2.once("end", () => {
  41090. if (!response) {
  41091. response = new Response2(body, responseOptions);
  41092. resolve2(response);
  41093. }
  41094. });
  41095. return;
  41096. }
  41097. if (codings === "br") {
  41098. body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createBrotliDecompress(), (error2) => {
  41099. if (error2) {
  41100. reject(error2);
  41101. }
  41102. });
  41103. response = new Response2(body, responseOptions);
  41104. resolve2(response);
  41105. return;
  41106. }
  41107. response = new Response2(body, responseOptions);
  41108. resolve2(response);
  41109. });
  41110. writeToStream(request_, request).catch(reject);
  41111. });
  41112. }
  41113. function fixResponseChunkedTransferBadEnding(request, errorCallback) {
  41114. const LAST_CHUNK = import_node_buffer2.Buffer.from("0\r\n\r\n");
  41115. let isChunkedTransfer = false;
  41116. let properLastChunkReceived = false;
  41117. let previousChunk;
  41118. request.on("response", (response) => {
  41119. const { headers } = response;
  41120. isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"];
  41121. });
  41122. request.on("socket", (socket) => {
  41123. const onSocketClose = () => {
  41124. if (isChunkedTransfer && !properLastChunkReceived) {
  41125. const error2 = new Error("Premature close");
  41126. error2.code = "ERR_STREAM_PREMATURE_CLOSE";
  41127. errorCallback(error2);
  41128. }
  41129. };
  41130. const onData = (buf) => {
  41131. properLastChunkReceived = import_node_buffer2.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0;
  41132. if (!properLastChunkReceived && previousChunk) {
  41133. properLastChunkReceived = import_node_buffer2.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && import_node_buffer2.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0;
  41134. }
  41135. previousChunk = buf;
  41136. };
  41137. socket.prependListener("close", onSocketClose);
  41138. socket.on("data", onData);
  41139. request.on("close", () => {
  41140. socket.removeListener("close", onSocketClose);
  41141. socket.removeListener("data", onData);
  41142. });
  41143. });
  41144. }
  41145. var import_node_http2, import_node_https, import_node_zlib, import_node_stream2, import_node_buffer2, supportedSchemas;
  41146. var init_src = __esm({
  41147. "../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js"() {
  41148. import_node_http2 = __toESM(require("node:http"), 1);
  41149. import_node_https = __toESM(require("node:https"), 1);
  41150. import_node_zlib = __toESM(require("node:zlib"), 1);
  41151. import_node_stream2 = __toESM(require("node:stream"), 1);
  41152. import_node_buffer2 = require("node:buffer");
  41153. init_dist();
  41154. init_body();
  41155. init_response();
  41156. init_headers();
  41157. init_request();
  41158. init_fetch_error();
  41159. init_abort_error();
  41160. init_is_redirect();
  41161. init_esm_min();
  41162. init_is();
  41163. init_referrer();
  41164. init_from();
  41165. supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]);
  41166. }
  41167. });
  41168. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/constants.js
  41169. var require_constants2 = __commonJS({
  41170. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/constants.js"(exports2, module2) {
  41171. "use strict";
  41172. var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
  41173. var hasBlob = typeof Blob !== "undefined";
  41174. if (hasBlob) BINARY_TYPES.push("blob");
  41175. module2.exports = {
  41176. BINARY_TYPES,
  41177. EMPTY_BUFFER: Buffer.alloc(0),
  41178. GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
  41179. hasBlob,
  41180. kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
  41181. kListener: Symbol("kListener"),
  41182. kStatusCode: Symbol("status-code"),
  41183. kWebSocket: Symbol("websocket"),
  41184. NOOP: () => {
  41185. }
  41186. };
  41187. }
  41188. });
  41189. // ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js
  41190. var require_node_gyp_build = __commonJS({
  41191. "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(exports2, module2) {
  41192. var fs7 = require("fs");
  41193. var path4 = require("path");
  41194. var os3 = require("os");
  41195. var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
  41196. var vars = process.config && process.config.variables || {};
  41197. var prebuildsOnly = !!process.env.PREBUILDS_ONLY;
  41198. var abi = process.versions.modules;
  41199. var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node";
  41200. var arch = process.env.npm_config_arch || os3.arch();
  41201. var platform = process.env.npm_config_platform || os3.platform();
  41202. var libc = process.env.LIBC || (isAlpine(platform) ? "musl" : "glibc");
  41203. var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || "";
  41204. var uv = (process.versions.uv || "").split(".")[0];
  41205. module2.exports = load;
  41206. function load(dir) {
  41207. return runtimeRequire(load.resolve(dir));
  41208. }
  41209. load.resolve = load.path = function(dir) {
  41210. dir = path4.resolve(dir || ".");
  41211. try {
  41212. var name = runtimeRequire(path4.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
  41213. if (process.env[name + "_PREBUILD"]) dir = process.env[name + "_PREBUILD"];
  41214. } catch (err2) {
  41215. }
  41216. if (!prebuildsOnly) {
  41217. var release = getFirst(path4.join(dir, "build/Release"), matchBuild);
  41218. if (release) return release;
  41219. var debug = getFirst(path4.join(dir, "build/Debug"), matchBuild);
  41220. if (debug) return debug;
  41221. }
  41222. var prebuild = resolve2(dir);
  41223. if (prebuild) return prebuild;
  41224. var nearby = resolve2(path4.dirname(process.execPath));
  41225. if (nearby) return nearby;
  41226. var target = [
  41227. "platform=" + platform,
  41228. "arch=" + arch,
  41229. "runtime=" + runtime,
  41230. "abi=" + abi,
  41231. "uv=" + uv,
  41232. armv ? "armv=" + armv : "",
  41233. "libc=" + libc,
  41234. "node=" + process.versions.node,
  41235. process.versions.electron ? "electron=" + process.versions.electron : "",
  41236. typeof __webpack_require__ === "function" ? "webpack=true" : ""
  41237. // eslint-disable-line
  41238. ].filter(Boolean).join(" ");
  41239. throw new Error("No native build was found for " + target + "\n loaded from: " + dir + "\n");
  41240. function resolve2(dir2) {
  41241. var tuples = readdirSync2(path4.join(dir2, "prebuilds")).map(parseTuple);
  41242. var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
  41243. if (!tuple) return;
  41244. var prebuilds = path4.join(dir2, "prebuilds", tuple.name);
  41245. var parsed = readdirSync2(prebuilds).map(parseTags);
  41246. var candidates = parsed.filter(matchTags(runtime, abi));
  41247. var winner = candidates.sort(compareTags(runtime))[0];
  41248. if (winner) return path4.join(prebuilds, winner.file);
  41249. }
  41250. };
  41251. function readdirSync2(dir) {
  41252. try {
  41253. return fs7.readdirSync(dir);
  41254. } catch (err2) {
  41255. return [];
  41256. }
  41257. }
  41258. function getFirst(dir, filter2) {
  41259. var files = readdirSync2(dir).filter(filter2);
  41260. return files[0] && path4.join(dir, files[0]);
  41261. }
  41262. function matchBuild(name) {
  41263. return /\.node$/.test(name);
  41264. }
  41265. function parseTuple(name) {
  41266. var arr = name.split("-");
  41267. if (arr.length !== 2) return;
  41268. var platform2 = arr[0];
  41269. var architectures = arr[1].split("+");
  41270. if (!platform2) return;
  41271. if (!architectures.length) return;
  41272. if (!architectures.every(Boolean)) return;
  41273. return { name, platform: platform2, architectures };
  41274. }
  41275. function matchTuple(platform2, arch2) {
  41276. return function(tuple) {
  41277. if (tuple == null) return false;
  41278. if (tuple.platform !== platform2) return false;
  41279. return tuple.architectures.includes(arch2);
  41280. };
  41281. }
  41282. function compareTuples(a3, b3) {
  41283. return a3.architectures.length - b3.architectures.length;
  41284. }
  41285. function parseTags(file) {
  41286. var arr = file.split(".");
  41287. var extension = arr.pop();
  41288. var tags = { file, specificity: 0 };
  41289. if (extension !== "node") return;
  41290. for (var i4 = 0; i4 < arr.length; i4++) {
  41291. var tag = arr[i4];
  41292. if (tag === "node" || tag === "electron" || tag === "node-webkit") {
  41293. tags.runtime = tag;
  41294. } else if (tag === "napi") {
  41295. tags.napi = true;
  41296. } else if (tag.slice(0, 3) === "abi") {
  41297. tags.abi = tag.slice(3);
  41298. } else if (tag.slice(0, 2) === "uv") {
  41299. tags.uv = tag.slice(2);
  41300. } else if (tag.slice(0, 4) === "armv") {
  41301. tags.armv = tag.slice(4);
  41302. } else if (tag === "glibc" || tag === "musl") {
  41303. tags.libc = tag;
  41304. } else {
  41305. continue;
  41306. }
  41307. tags.specificity++;
  41308. }
  41309. return tags;
  41310. }
  41311. function matchTags(runtime2, abi2) {
  41312. return function(tags) {
  41313. if (tags == null) return false;
  41314. if (tags.runtime && tags.runtime !== runtime2 && !runtimeAgnostic(tags)) return false;
  41315. if (tags.abi && tags.abi !== abi2 && !tags.napi) return false;
  41316. if (tags.uv && tags.uv !== uv) return false;
  41317. if (tags.armv && tags.armv !== armv) return false;
  41318. if (tags.libc && tags.libc !== libc) return false;
  41319. return true;
  41320. };
  41321. }
  41322. function runtimeAgnostic(tags) {
  41323. return tags.runtime === "node" && tags.napi;
  41324. }
  41325. function compareTags(runtime2) {
  41326. return function(a3, b3) {
  41327. if (a3.runtime !== b3.runtime) {
  41328. return a3.runtime === runtime2 ? -1 : 1;
  41329. } else if (a3.abi !== b3.abi) {
  41330. return a3.abi ? -1 : 1;
  41331. } else if (a3.specificity !== b3.specificity) {
  41332. return a3.specificity > b3.specificity ? -1 : 1;
  41333. } else {
  41334. return 0;
  41335. }
  41336. };
  41337. }
  41338. function isNwjs() {
  41339. return !!(process.versions && process.versions.nw);
  41340. }
  41341. function isElectron() {
  41342. if (process.versions && process.versions.electron) return true;
  41343. if (process.env.ELECTRON_RUN_AS_NODE) return true;
  41344. return typeof window !== "undefined" && window.process && window.process.type === "renderer";
  41345. }
  41346. function isAlpine(platform2) {
  41347. return platform2 === "linux" && fs7.existsSync("/etc/alpine-release");
  41348. }
  41349. load.parseTags = parseTags;
  41350. load.matchTags = matchTags;
  41351. load.compareTags = compareTags;
  41352. load.parseTuple = parseTuple;
  41353. load.matchTuple = matchTuple;
  41354. load.compareTuples = compareTuples;
  41355. }
  41356. });
  41357. // ../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js
  41358. var require_node_gyp_build2 = __commonJS({
  41359. "../node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(exports2, module2) {
  41360. var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
  41361. if (typeof runtimeRequire.addon === "function") {
  41362. module2.exports = runtimeRequire.addon.bind(runtimeRequire);
  41363. } else {
  41364. module2.exports = require_node_gyp_build();
  41365. }
  41366. }
  41367. });
  41368. // ../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/fallback.js
  41369. var require_fallback = __commonJS({
  41370. "../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/fallback.js"(exports2, module2) {
  41371. "use strict";
  41372. var mask = (source, mask2, output, offset, length) => {
  41373. for (var i4 = 0; i4 < length; i4++) {
  41374. output[offset + i4] = source[i4] ^ mask2[i4 & 3];
  41375. }
  41376. };
  41377. var unmask = (buffer, mask2) => {
  41378. const length = buffer.length;
  41379. for (var i4 = 0; i4 < length; i4++) {
  41380. buffer[i4] ^= mask2[i4 & 3];
  41381. }
  41382. };
  41383. module2.exports = { mask, unmask };
  41384. }
  41385. });
  41386. // ../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/index.js
  41387. var require_bufferutil = __commonJS({
  41388. "../node_modules/.pnpm/bufferutil@4.0.8/node_modules/bufferutil/index.js"(exports2, module2) {
  41389. "use strict";
  41390. try {
  41391. module2.exports = require_node_gyp_build2()(__dirname);
  41392. } catch (e4) {
  41393. module2.exports = require_fallback();
  41394. }
  41395. }
  41396. });
  41397. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/buffer-util.js
  41398. var require_buffer_util = __commonJS({
  41399. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/buffer-util.js"(exports2, module2) {
  41400. "use strict";
  41401. var { EMPTY_BUFFER } = require_constants2();
  41402. var FastBuffer = Buffer[Symbol.species];
  41403. function concat(list, totalLength) {
  41404. if (list.length === 0) return EMPTY_BUFFER;
  41405. if (list.length === 1) return list[0];
  41406. const target = Buffer.allocUnsafe(totalLength);
  41407. let offset = 0;
  41408. for (let i4 = 0; i4 < list.length; i4++) {
  41409. const buf = list[i4];
  41410. target.set(buf, offset);
  41411. offset += buf.length;
  41412. }
  41413. if (offset < totalLength) {
  41414. return new FastBuffer(target.buffer, target.byteOffset, offset);
  41415. }
  41416. return target;
  41417. }
  41418. function _mask(source, mask, output, offset, length) {
  41419. for (let i4 = 0; i4 < length; i4++) {
  41420. output[offset + i4] = source[i4] ^ mask[i4 & 3];
  41421. }
  41422. }
  41423. function _unmask(buffer, mask) {
  41424. for (let i4 = 0; i4 < buffer.length; i4++) {
  41425. buffer[i4] ^= mask[i4 & 3];
  41426. }
  41427. }
  41428. function toArrayBuffer(buf) {
  41429. if (buf.length === buf.buffer.byteLength) {
  41430. return buf.buffer;
  41431. }
  41432. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
  41433. }
  41434. function toBuffer(data) {
  41435. toBuffer.readOnly = true;
  41436. if (Buffer.isBuffer(data)) return data;
  41437. let buf;
  41438. if (data instanceof ArrayBuffer) {
  41439. buf = new FastBuffer(data);
  41440. } else if (ArrayBuffer.isView(data)) {
  41441. buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
  41442. } else {
  41443. buf = Buffer.from(data);
  41444. toBuffer.readOnly = false;
  41445. }
  41446. return buf;
  41447. }
  41448. module2.exports = {
  41449. concat,
  41450. mask: _mask,
  41451. toArrayBuffer,
  41452. toBuffer,
  41453. unmask: _unmask
  41454. };
  41455. if (!process.env.WS_NO_BUFFER_UTIL) {
  41456. try {
  41457. const bufferUtil = require_bufferutil();
  41458. module2.exports.mask = function(source, mask, output, offset, length) {
  41459. if (length < 48) _mask(source, mask, output, offset, length);
  41460. else bufferUtil.mask(source, mask, output, offset, length);
  41461. };
  41462. module2.exports.unmask = function(buffer, mask) {
  41463. if (buffer.length < 32) _unmask(buffer, mask);
  41464. else bufferUtil.unmask(buffer, mask);
  41465. };
  41466. } catch (e4) {
  41467. }
  41468. }
  41469. }
  41470. });
  41471. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/limiter.js
  41472. var require_limiter = __commonJS({
  41473. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/limiter.js"(exports2, module2) {
  41474. "use strict";
  41475. var kDone = Symbol("kDone");
  41476. var kRun = Symbol("kRun");
  41477. var Limiter = class {
  41478. /**
  41479. * Creates a new `Limiter`.
  41480. *
  41481. * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
  41482. * to run concurrently
  41483. */
  41484. constructor(concurrency) {
  41485. this[kDone] = () => {
  41486. this.pending--;
  41487. this[kRun]();
  41488. };
  41489. this.concurrency = concurrency || Infinity;
  41490. this.jobs = [];
  41491. this.pending = 0;
  41492. }
  41493. /**
  41494. * Adds a job to the queue.
  41495. *
  41496. * @param {Function} job The job to run
  41497. * @public
  41498. */
  41499. add(job) {
  41500. this.jobs.push(job);
  41501. this[kRun]();
  41502. }
  41503. /**
  41504. * Removes a job from the queue and runs it if possible.
  41505. *
  41506. * @private
  41507. */
  41508. [kRun]() {
  41509. if (this.pending === this.concurrency) return;
  41510. if (this.jobs.length) {
  41511. const job = this.jobs.shift();
  41512. this.pending++;
  41513. job(this[kDone]);
  41514. }
  41515. }
  41516. };
  41517. module2.exports = Limiter;
  41518. }
  41519. });
  41520. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/permessage-deflate.js
  41521. var require_permessage_deflate = __commonJS({
  41522. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
  41523. "use strict";
  41524. var zlib2 = require("zlib");
  41525. var bufferUtil = require_buffer_util();
  41526. var Limiter = require_limiter();
  41527. var { kStatusCode } = require_constants2();
  41528. var FastBuffer = Buffer[Symbol.species];
  41529. var TRAILER = Buffer.from([0, 0, 255, 255]);
  41530. var kPerMessageDeflate = Symbol("permessage-deflate");
  41531. var kTotalLength = Symbol("total-length");
  41532. var kCallback = Symbol("callback");
  41533. var kBuffers = Symbol("buffers");
  41534. var kError = Symbol("error");
  41535. var zlibLimiter;
  41536. var PerMessageDeflate = class {
  41537. /**
  41538. * Creates a PerMessageDeflate instance.
  41539. *
  41540. * @param {Object} [options] Configuration options
  41541. * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
  41542. * for, or request, a custom client window size
  41543. * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
  41544. * acknowledge disabling of client context takeover
  41545. * @param {Number} [options.concurrencyLimit=10] The number of concurrent
  41546. * calls to zlib
  41547. * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
  41548. * use of a custom server window size
  41549. * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
  41550. * disabling of server context takeover
  41551. * @param {Number} [options.threshold=1024] Size (in bytes) below which
  41552. * messages should not be compressed if context takeover is disabled
  41553. * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
  41554. * deflate
  41555. * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
  41556. * inflate
  41557. * @param {Boolean} [isServer=false] Create the instance in either server or
  41558. * client mode
  41559. * @param {Number} [maxPayload=0] The maximum allowed message length
  41560. */
  41561. constructor(options, isServer, maxPayload) {
  41562. this._maxPayload = maxPayload | 0;
  41563. this._options = options || {};
  41564. this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
  41565. this._isServer = !!isServer;
  41566. this._deflate = null;
  41567. this._inflate = null;
  41568. this.params = null;
  41569. if (!zlibLimiter) {
  41570. const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
  41571. zlibLimiter = new Limiter(concurrency);
  41572. }
  41573. }
  41574. /**
  41575. * @type {String}
  41576. */
  41577. static get extensionName() {
  41578. return "permessage-deflate";
  41579. }
  41580. /**
  41581. * Create an extension negotiation offer.
  41582. *
  41583. * @return {Object} Extension parameters
  41584. * @public
  41585. */
  41586. offer() {
  41587. const params = {};
  41588. if (this._options.serverNoContextTakeover) {
  41589. params.server_no_context_takeover = true;
  41590. }
  41591. if (this._options.clientNoContextTakeover) {
  41592. params.client_no_context_takeover = true;
  41593. }
  41594. if (this._options.serverMaxWindowBits) {
  41595. params.server_max_window_bits = this._options.serverMaxWindowBits;
  41596. }
  41597. if (this._options.clientMaxWindowBits) {
  41598. params.client_max_window_bits = this._options.clientMaxWindowBits;
  41599. } else if (this._options.clientMaxWindowBits == null) {
  41600. params.client_max_window_bits = true;
  41601. }
  41602. return params;
  41603. }
  41604. /**
  41605. * Accept an extension negotiation offer/response.
  41606. *
  41607. * @param {Array} configurations The extension negotiation offers/reponse
  41608. * @return {Object} Accepted configuration
  41609. * @public
  41610. */
  41611. accept(configurations) {
  41612. configurations = this.normalizeParams(configurations);
  41613. this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
  41614. return this.params;
  41615. }
  41616. /**
  41617. * Releases all resources used by the extension.
  41618. *
  41619. * @public
  41620. */
  41621. cleanup() {
  41622. if (this._inflate) {
  41623. this._inflate.close();
  41624. this._inflate = null;
  41625. }
  41626. if (this._deflate) {
  41627. const callback = this._deflate[kCallback];
  41628. this._deflate.close();
  41629. this._deflate = null;
  41630. if (callback) {
  41631. callback(
  41632. new Error(
  41633. "The deflate stream was closed while data was being processed"
  41634. )
  41635. );
  41636. }
  41637. }
  41638. }
  41639. /**
  41640. * Accept an extension negotiation offer.
  41641. *
  41642. * @param {Array} offers The extension negotiation offers
  41643. * @return {Object} Accepted configuration
  41644. * @private
  41645. */
  41646. acceptAsServer(offers) {
  41647. const opts = this._options;
  41648. const accepted = offers.find((params) => {
  41649. if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
  41650. return false;
  41651. }
  41652. return true;
  41653. });
  41654. if (!accepted) {
  41655. throw new Error("None of the extension offers can be accepted");
  41656. }
  41657. if (opts.serverNoContextTakeover) {
  41658. accepted.server_no_context_takeover = true;
  41659. }
  41660. if (opts.clientNoContextTakeover) {
  41661. accepted.client_no_context_takeover = true;
  41662. }
  41663. if (typeof opts.serverMaxWindowBits === "number") {
  41664. accepted.server_max_window_bits = opts.serverMaxWindowBits;
  41665. }
  41666. if (typeof opts.clientMaxWindowBits === "number") {
  41667. accepted.client_max_window_bits = opts.clientMaxWindowBits;
  41668. } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
  41669. delete accepted.client_max_window_bits;
  41670. }
  41671. return accepted;
  41672. }
  41673. /**
  41674. * Accept the extension negotiation response.
  41675. *
  41676. * @param {Array} response The extension negotiation response
  41677. * @return {Object} Accepted configuration
  41678. * @private
  41679. */
  41680. acceptAsClient(response) {
  41681. const params = response[0];
  41682. if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
  41683. throw new Error('Unexpected parameter "client_no_context_takeover"');
  41684. }
  41685. if (!params.client_max_window_bits) {
  41686. if (typeof this._options.clientMaxWindowBits === "number") {
  41687. params.client_max_window_bits = this._options.clientMaxWindowBits;
  41688. }
  41689. } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
  41690. throw new Error(
  41691. 'Unexpected or invalid parameter "client_max_window_bits"'
  41692. );
  41693. }
  41694. return params;
  41695. }
  41696. /**
  41697. * Normalize parameters.
  41698. *
  41699. * @param {Array} configurations The extension negotiation offers/reponse
  41700. * @return {Array} The offers/response with normalized parameters
  41701. * @private
  41702. */
  41703. normalizeParams(configurations) {
  41704. configurations.forEach((params) => {
  41705. Object.keys(params).forEach((key) => {
  41706. let value = params[key];
  41707. if (value.length > 1) {
  41708. throw new Error(`Parameter "${key}" must have only a single value`);
  41709. }
  41710. value = value[0];
  41711. if (key === "client_max_window_bits") {
  41712. if (value !== true) {
  41713. const num = +value;
  41714. if (!Number.isInteger(num) || num < 8 || num > 15) {
  41715. throw new TypeError(
  41716. `Invalid value for parameter "${key}": ${value}`
  41717. );
  41718. }
  41719. value = num;
  41720. } else if (!this._isServer) {
  41721. throw new TypeError(
  41722. `Invalid value for parameter "${key}": ${value}`
  41723. );
  41724. }
  41725. } else if (key === "server_max_window_bits") {
  41726. const num = +value;
  41727. if (!Number.isInteger(num) || num < 8 || num > 15) {
  41728. throw new TypeError(
  41729. `Invalid value for parameter "${key}": ${value}`
  41730. );
  41731. }
  41732. value = num;
  41733. } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
  41734. if (value !== true) {
  41735. throw new TypeError(
  41736. `Invalid value for parameter "${key}": ${value}`
  41737. );
  41738. }
  41739. } else {
  41740. throw new Error(`Unknown parameter "${key}"`);
  41741. }
  41742. params[key] = value;
  41743. });
  41744. });
  41745. return configurations;
  41746. }
  41747. /**
  41748. * Decompress data. Concurrency limited.
  41749. *
  41750. * @param {Buffer} data Compressed data
  41751. * @param {Boolean} fin Specifies whether or not this is the last fragment
  41752. * @param {Function} callback Callback
  41753. * @public
  41754. */
  41755. decompress(data, fin, callback) {
  41756. zlibLimiter.add((done) => {
  41757. this._decompress(data, fin, (err2, result) => {
  41758. done();
  41759. callback(err2, result);
  41760. });
  41761. });
  41762. }
  41763. /**
  41764. * Compress data. Concurrency limited.
  41765. *
  41766. * @param {(Buffer|String)} data Data to compress
  41767. * @param {Boolean} fin Specifies whether or not this is the last fragment
  41768. * @param {Function} callback Callback
  41769. * @public
  41770. */
  41771. compress(data, fin, callback) {
  41772. zlibLimiter.add((done) => {
  41773. this._compress(data, fin, (err2, result) => {
  41774. done();
  41775. callback(err2, result);
  41776. });
  41777. });
  41778. }
  41779. /**
  41780. * Decompress data.
  41781. *
  41782. * @param {Buffer} data Compressed data
  41783. * @param {Boolean} fin Specifies whether or not this is the last fragment
  41784. * @param {Function} callback Callback
  41785. * @private
  41786. */
  41787. _decompress(data, fin, callback) {
  41788. const endpoint = this._isServer ? "client" : "server";
  41789. if (!this._inflate) {
  41790. const key = `${endpoint}_max_window_bits`;
  41791. const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
  41792. this._inflate = zlib2.createInflateRaw({
  41793. ...this._options.zlibInflateOptions,
  41794. windowBits
  41795. });
  41796. this._inflate[kPerMessageDeflate] = this;
  41797. this._inflate[kTotalLength] = 0;
  41798. this._inflate[kBuffers] = [];
  41799. this._inflate.on("error", inflateOnError);
  41800. this._inflate.on("data", inflateOnData);
  41801. }
  41802. this._inflate[kCallback] = callback;
  41803. this._inflate.write(data);
  41804. if (fin) this._inflate.write(TRAILER);
  41805. this._inflate.flush(() => {
  41806. const err2 = this._inflate[kError];
  41807. if (err2) {
  41808. this._inflate.close();
  41809. this._inflate = null;
  41810. callback(err2);
  41811. return;
  41812. }
  41813. const data2 = bufferUtil.concat(
  41814. this._inflate[kBuffers],
  41815. this._inflate[kTotalLength]
  41816. );
  41817. if (this._inflate._readableState.endEmitted) {
  41818. this._inflate.close();
  41819. this._inflate = null;
  41820. } else {
  41821. this._inflate[kTotalLength] = 0;
  41822. this._inflate[kBuffers] = [];
  41823. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  41824. this._inflate.reset();
  41825. }
  41826. }
  41827. callback(null, data2);
  41828. });
  41829. }
  41830. /**
  41831. * Compress data.
  41832. *
  41833. * @param {(Buffer|String)} data Data to compress
  41834. * @param {Boolean} fin Specifies whether or not this is the last fragment
  41835. * @param {Function} callback Callback
  41836. * @private
  41837. */
  41838. _compress(data, fin, callback) {
  41839. const endpoint = this._isServer ? "server" : "client";
  41840. if (!this._deflate) {
  41841. const key = `${endpoint}_max_window_bits`;
  41842. const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
  41843. this._deflate = zlib2.createDeflateRaw({
  41844. ...this._options.zlibDeflateOptions,
  41845. windowBits
  41846. });
  41847. this._deflate[kTotalLength] = 0;
  41848. this._deflate[kBuffers] = [];
  41849. this._deflate.on("data", deflateOnData);
  41850. }
  41851. this._deflate[kCallback] = callback;
  41852. this._deflate.write(data);
  41853. this._deflate.flush(zlib2.Z_SYNC_FLUSH, () => {
  41854. if (!this._deflate) {
  41855. return;
  41856. }
  41857. let data2 = bufferUtil.concat(
  41858. this._deflate[kBuffers],
  41859. this._deflate[kTotalLength]
  41860. );
  41861. if (fin) {
  41862. data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
  41863. }
  41864. this._deflate[kCallback] = null;
  41865. this._deflate[kTotalLength] = 0;
  41866. this._deflate[kBuffers] = [];
  41867. if (fin && this.params[`${endpoint}_no_context_takeover`]) {
  41868. this._deflate.reset();
  41869. }
  41870. callback(null, data2);
  41871. });
  41872. }
  41873. };
  41874. module2.exports = PerMessageDeflate;
  41875. function deflateOnData(chunk) {
  41876. this[kBuffers].push(chunk);
  41877. this[kTotalLength] += chunk.length;
  41878. }
  41879. function inflateOnData(chunk) {
  41880. this[kTotalLength] += chunk.length;
  41881. if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
  41882. this[kBuffers].push(chunk);
  41883. return;
  41884. }
  41885. this[kError] = new RangeError("Max payload size exceeded");
  41886. this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
  41887. this[kError][kStatusCode] = 1009;
  41888. this.removeListener("data", inflateOnData);
  41889. this.reset();
  41890. }
  41891. function inflateOnError(err2) {
  41892. this[kPerMessageDeflate]._inflate = null;
  41893. if (this[kError]) {
  41894. this[kCallback](this[kError]);
  41895. return;
  41896. }
  41897. err2[kStatusCode] = 1007;
  41898. this[kCallback](err2);
  41899. }
  41900. }
  41901. });
  41902. // ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js
  41903. var require_fallback2 = __commonJS({
  41904. "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/fallback.js"(exports2, module2) {
  41905. "use strict";
  41906. function isValidUTF8(buf) {
  41907. const len = buf.length;
  41908. let i4 = 0;
  41909. while (i4 < len) {
  41910. if ((buf[i4] & 128) === 0) {
  41911. i4++;
  41912. } else if ((buf[i4] & 224) === 192) {
  41913. if (i4 + 1 === len || (buf[i4 + 1] & 192) !== 128 || (buf[i4] & 254) === 192) {
  41914. return false;
  41915. }
  41916. i4 += 2;
  41917. } else if ((buf[i4] & 240) === 224) {
  41918. if (i4 + 2 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || buf[i4] === 224 && (buf[i4 + 1] & 224) === 128 || // overlong
  41919. buf[i4] === 237 && (buf[i4 + 1] & 224) === 160) {
  41920. return false;
  41921. }
  41922. i4 += 3;
  41923. } else if ((buf[i4] & 248) === 240) {
  41924. if (i4 + 3 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || (buf[i4 + 3] & 192) !== 128 || buf[i4] === 240 && (buf[i4 + 1] & 240) === 128 || // overlong
  41925. buf[i4] === 244 && buf[i4 + 1] > 143 || buf[i4] > 244) {
  41926. return false;
  41927. }
  41928. i4 += 4;
  41929. } else {
  41930. return false;
  41931. }
  41932. }
  41933. return true;
  41934. }
  41935. module2.exports = isValidUTF8;
  41936. }
  41937. });
  41938. // ../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/index.js
  41939. var require_utf_8_validate = __commonJS({
  41940. "../node_modules/.pnpm/utf-8-validate@6.0.3/node_modules/utf-8-validate/index.js"(exports2, module2) {
  41941. "use strict";
  41942. try {
  41943. module2.exports = require_node_gyp_build2()(__dirname);
  41944. } catch (e4) {
  41945. module2.exports = require_fallback2();
  41946. }
  41947. }
  41948. });
  41949. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/validation.js
  41950. var require_validation = __commonJS({
  41951. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/validation.js"(exports2, module2) {
  41952. "use strict";
  41953. var { isUtf8 } = require("buffer");
  41954. var { hasBlob } = require_constants2();
  41955. var tokenChars = [
  41956. 0,
  41957. 0,
  41958. 0,
  41959. 0,
  41960. 0,
  41961. 0,
  41962. 0,
  41963. 0,
  41964. 0,
  41965. 0,
  41966. 0,
  41967. 0,
  41968. 0,
  41969. 0,
  41970. 0,
  41971. 0,
  41972. // 0 - 15
  41973. 0,
  41974. 0,
  41975. 0,
  41976. 0,
  41977. 0,
  41978. 0,
  41979. 0,
  41980. 0,
  41981. 0,
  41982. 0,
  41983. 0,
  41984. 0,
  41985. 0,
  41986. 0,
  41987. 0,
  41988. 0,
  41989. // 16 - 31
  41990. 0,
  41991. 1,
  41992. 0,
  41993. 1,
  41994. 1,
  41995. 1,
  41996. 1,
  41997. 1,
  41998. 0,
  41999. 0,
  42000. 1,
  42001. 1,
  42002. 0,
  42003. 1,
  42004. 1,
  42005. 0,
  42006. // 32 - 47
  42007. 1,
  42008. 1,
  42009. 1,
  42010. 1,
  42011. 1,
  42012. 1,
  42013. 1,
  42014. 1,
  42015. 1,
  42016. 1,
  42017. 0,
  42018. 0,
  42019. 0,
  42020. 0,
  42021. 0,
  42022. 0,
  42023. // 48 - 63
  42024. 0,
  42025. 1,
  42026. 1,
  42027. 1,
  42028. 1,
  42029. 1,
  42030. 1,
  42031. 1,
  42032. 1,
  42033. 1,
  42034. 1,
  42035. 1,
  42036. 1,
  42037. 1,
  42038. 1,
  42039. 1,
  42040. // 64 - 79
  42041. 1,
  42042. 1,
  42043. 1,
  42044. 1,
  42045. 1,
  42046. 1,
  42047. 1,
  42048. 1,
  42049. 1,
  42050. 1,
  42051. 1,
  42052. 0,
  42053. 0,
  42054. 0,
  42055. 1,
  42056. 1,
  42057. // 80 - 95
  42058. 1,
  42059. 1,
  42060. 1,
  42061. 1,
  42062. 1,
  42063. 1,
  42064. 1,
  42065. 1,
  42066. 1,
  42067. 1,
  42068. 1,
  42069. 1,
  42070. 1,
  42071. 1,
  42072. 1,
  42073. 1,
  42074. // 96 - 111
  42075. 1,
  42076. 1,
  42077. 1,
  42078. 1,
  42079. 1,
  42080. 1,
  42081. 1,
  42082. 1,
  42083. 1,
  42084. 1,
  42085. 1,
  42086. 0,
  42087. 1,
  42088. 0,
  42089. 1,
  42090. 0
  42091. // 112 - 127
  42092. ];
  42093. function isValidStatusCode(code) {
  42094. return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
  42095. }
  42096. function _isValidUTF8(buf) {
  42097. const len = buf.length;
  42098. let i4 = 0;
  42099. while (i4 < len) {
  42100. if ((buf[i4] & 128) === 0) {
  42101. i4++;
  42102. } else if ((buf[i4] & 224) === 192) {
  42103. if (i4 + 1 === len || (buf[i4 + 1] & 192) !== 128 || (buf[i4] & 254) === 192) {
  42104. return false;
  42105. }
  42106. i4 += 2;
  42107. } else if ((buf[i4] & 240) === 224) {
  42108. if (i4 + 2 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || buf[i4] === 224 && (buf[i4 + 1] & 224) === 128 || // Overlong
  42109. buf[i4] === 237 && (buf[i4 + 1] & 224) === 160) {
  42110. return false;
  42111. }
  42112. i4 += 3;
  42113. } else if ((buf[i4] & 248) === 240) {
  42114. if (i4 + 3 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || (buf[i4 + 3] & 192) !== 128 || buf[i4] === 240 && (buf[i4 + 1] & 240) === 128 || // Overlong
  42115. buf[i4] === 244 && buf[i4 + 1] > 143 || buf[i4] > 244) {
  42116. return false;
  42117. }
  42118. i4 += 4;
  42119. } else {
  42120. return false;
  42121. }
  42122. }
  42123. return true;
  42124. }
  42125. function isBlob3(value) {
  42126. return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
  42127. }
  42128. module2.exports = {
  42129. isBlob: isBlob3,
  42130. isValidStatusCode,
  42131. isValidUTF8: _isValidUTF8,
  42132. tokenChars
  42133. };
  42134. if (isUtf8) {
  42135. module2.exports.isValidUTF8 = function(buf) {
  42136. return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
  42137. };
  42138. } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
  42139. try {
  42140. const isValidUTF8 = require_utf_8_validate();
  42141. module2.exports.isValidUTF8 = function(buf) {
  42142. return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
  42143. };
  42144. } catch (e4) {
  42145. }
  42146. }
  42147. }
  42148. });
  42149. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/receiver.js
  42150. var require_receiver = __commonJS({
  42151. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/receiver.js"(exports2, module2) {
  42152. "use strict";
  42153. var { Writable } = require("stream");
  42154. var PerMessageDeflate = require_permessage_deflate();
  42155. var {
  42156. BINARY_TYPES,
  42157. EMPTY_BUFFER,
  42158. kStatusCode,
  42159. kWebSocket
  42160. } = require_constants2();
  42161. var { concat, toArrayBuffer, unmask } = require_buffer_util();
  42162. var { isValidStatusCode, isValidUTF8 } = require_validation();
  42163. var FastBuffer = Buffer[Symbol.species];
  42164. var GET_INFO = 0;
  42165. var GET_PAYLOAD_LENGTH_16 = 1;
  42166. var GET_PAYLOAD_LENGTH_64 = 2;
  42167. var GET_MASK = 3;
  42168. var GET_DATA = 4;
  42169. var INFLATING = 5;
  42170. var DEFER_EVENT = 6;
  42171. var Receiver2 = class extends Writable {
  42172. /**
  42173. * Creates a Receiver instance.
  42174. *
  42175. * @param {Object} [options] Options object
  42176. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  42177. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  42178. * multiple times in the same tick
  42179. * @param {String} [options.binaryType=nodebuffer] The type for binary data
  42180. * @param {Object} [options.extensions] An object containing the negotiated
  42181. * extensions
  42182. * @param {Boolean} [options.isServer=false] Specifies whether to operate in
  42183. * client or server mode
  42184. * @param {Number} [options.maxPayload=0] The maximum allowed message length
  42185. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  42186. * not to skip UTF-8 validation for text and close messages
  42187. */
  42188. constructor(options = {}) {
  42189. super();
  42190. this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
  42191. this._binaryType = options.binaryType || BINARY_TYPES[0];
  42192. this._extensions = options.extensions || {};
  42193. this._isServer = !!options.isServer;
  42194. this._maxPayload = options.maxPayload | 0;
  42195. this._skipUTF8Validation = !!options.skipUTF8Validation;
  42196. this[kWebSocket] = void 0;
  42197. this._bufferedBytes = 0;
  42198. this._buffers = [];
  42199. this._compressed = false;
  42200. this._payloadLength = 0;
  42201. this._mask = void 0;
  42202. this._fragmented = 0;
  42203. this._masked = false;
  42204. this._fin = false;
  42205. this._opcode = 0;
  42206. this._totalPayloadLength = 0;
  42207. this._messageLength = 0;
  42208. this._fragments = [];
  42209. this._errored = false;
  42210. this._loop = false;
  42211. this._state = GET_INFO;
  42212. }
  42213. /**
  42214. * Implements `Writable.prototype._write()`.
  42215. *
  42216. * @param {Buffer} chunk The chunk of data to write
  42217. * @param {String} encoding The character encoding of `chunk`
  42218. * @param {Function} cb Callback
  42219. * @private
  42220. */
  42221. _write(chunk, encoding, cb) {
  42222. if (this._opcode === 8 && this._state == GET_INFO) return cb();
  42223. this._bufferedBytes += chunk.length;
  42224. this._buffers.push(chunk);
  42225. this.startLoop(cb);
  42226. }
  42227. /**
  42228. * Consumes `n` bytes from the buffered data.
  42229. *
  42230. * @param {Number} n The number of bytes to consume
  42231. * @return {Buffer} The consumed bytes
  42232. * @private
  42233. */
  42234. consume(n3) {
  42235. this._bufferedBytes -= n3;
  42236. if (n3 === this._buffers[0].length) return this._buffers.shift();
  42237. if (n3 < this._buffers[0].length) {
  42238. const buf = this._buffers[0];
  42239. this._buffers[0] = new FastBuffer(
  42240. buf.buffer,
  42241. buf.byteOffset + n3,
  42242. buf.length - n3
  42243. );
  42244. return new FastBuffer(buf.buffer, buf.byteOffset, n3);
  42245. }
  42246. const dst = Buffer.allocUnsafe(n3);
  42247. do {
  42248. const buf = this._buffers[0];
  42249. const offset = dst.length - n3;
  42250. if (n3 >= buf.length) {
  42251. dst.set(this._buffers.shift(), offset);
  42252. } else {
  42253. dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n3), offset);
  42254. this._buffers[0] = new FastBuffer(
  42255. buf.buffer,
  42256. buf.byteOffset + n3,
  42257. buf.length - n3
  42258. );
  42259. }
  42260. n3 -= buf.length;
  42261. } while (n3 > 0);
  42262. return dst;
  42263. }
  42264. /**
  42265. * Starts the parsing loop.
  42266. *
  42267. * @param {Function} cb Callback
  42268. * @private
  42269. */
  42270. startLoop(cb) {
  42271. this._loop = true;
  42272. do {
  42273. switch (this._state) {
  42274. case GET_INFO:
  42275. this.getInfo(cb);
  42276. break;
  42277. case GET_PAYLOAD_LENGTH_16:
  42278. this.getPayloadLength16(cb);
  42279. break;
  42280. case GET_PAYLOAD_LENGTH_64:
  42281. this.getPayloadLength64(cb);
  42282. break;
  42283. case GET_MASK:
  42284. this.getMask();
  42285. break;
  42286. case GET_DATA:
  42287. this.getData(cb);
  42288. break;
  42289. case INFLATING:
  42290. case DEFER_EVENT:
  42291. this._loop = false;
  42292. return;
  42293. }
  42294. } while (this._loop);
  42295. if (!this._errored) cb();
  42296. }
  42297. /**
  42298. * Reads the first two bytes of a frame.
  42299. *
  42300. * @param {Function} cb Callback
  42301. * @private
  42302. */
  42303. getInfo(cb) {
  42304. if (this._bufferedBytes < 2) {
  42305. this._loop = false;
  42306. return;
  42307. }
  42308. const buf = this.consume(2);
  42309. if ((buf[0] & 48) !== 0) {
  42310. const error2 = this.createError(
  42311. RangeError,
  42312. "RSV2 and RSV3 must be clear",
  42313. true,
  42314. 1002,
  42315. "WS_ERR_UNEXPECTED_RSV_2_3"
  42316. );
  42317. cb(error2);
  42318. return;
  42319. }
  42320. const compressed = (buf[0] & 64) === 64;
  42321. if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
  42322. const error2 = this.createError(
  42323. RangeError,
  42324. "RSV1 must be clear",
  42325. true,
  42326. 1002,
  42327. "WS_ERR_UNEXPECTED_RSV_1"
  42328. );
  42329. cb(error2);
  42330. return;
  42331. }
  42332. this._fin = (buf[0] & 128) === 128;
  42333. this._opcode = buf[0] & 15;
  42334. this._payloadLength = buf[1] & 127;
  42335. if (this._opcode === 0) {
  42336. if (compressed) {
  42337. const error2 = this.createError(
  42338. RangeError,
  42339. "RSV1 must be clear",
  42340. true,
  42341. 1002,
  42342. "WS_ERR_UNEXPECTED_RSV_1"
  42343. );
  42344. cb(error2);
  42345. return;
  42346. }
  42347. if (!this._fragmented) {
  42348. const error2 = this.createError(
  42349. RangeError,
  42350. "invalid opcode 0",
  42351. true,
  42352. 1002,
  42353. "WS_ERR_INVALID_OPCODE"
  42354. );
  42355. cb(error2);
  42356. return;
  42357. }
  42358. this._opcode = this._fragmented;
  42359. } else if (this._opcode === 1 || this._opcode === 2) {
  42360. if (this._fragmented) {
  42361. const error2 = this.createError(
  42362. RangeError,
  42363. `invalid opcode ${this._opcode}`,
  42364. true,
  42365. 1002,
  42366. "WS_ERR_INVALID_OPCODE"
  42367. );
  42368. cb(error2);
  42369. return;
  42370. }
  42371. this._compressed = compressed;
  42372. } else if (this._opcode > 7 && this._opcode < 11) {
  42373. if (!this._fin) {
  42374. const error2 = this.createError(
  42375. RangeError,
  42376. "FIN must be set",
  42377. true,
  42378. 1002,
  42379. "WS_ERR_EXPECTED_FIN"
  42380. );
  42381. cb(error2);
  42382. return;
  42383. }
  42384. if (compressed) {
  42385. const error2 = this.createError(
  42386. RangeError,
  42387. "RSV1 must be clear",
  42388. true,
  42389. 1002,
  42390. "WS_ERR_UNEXPECTED_RSV_1"
  42391. );
  42392. cb(error2);
  42393. return;
  42394. }
  42395. if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
  42396. const error2 = this.createError(
  42397. RangeError,
  42398. `invalid payload length ${this._payloadLength}`,
  42399. true,
  42400. 1002,
  42401. "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
  42402. );
  42403. cb(error2);
  42404. return;
  42405. }
  42406. } else {
  42407. const error2 = this.createError(
  42408. RangeError,
  42409. `invalid opcode ${this._opcode}`,
  42410. true,
  42411. 1002,
  42412. "WS_ERR_INVALID_OPCODE"
  42413. );
  42414. cb(error2);
  42415. return;
  42416. }
  42417. if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
  42418. this._masked = (buf[1] & 128) === 128;
  42419. if (this._isServer) {
  42420. if (!this._masked) {
  42421. const error2 = this.createError(
  42422. RangeError,
  42423. "MASK must be set",
  42424. true,
  42425. 1002,
  42426. "WS_ERR_EXPECTED_MASK"
  42427. );
  42428. cb(error2);
  42429. return;
  42430. }
  42431. } else if (this._masked) {
  42432. const error2 = this.createError(
  42433. RangeError,
  42434. "MASK must be clear",
  42435. true,
  42436. 1002,
  42437. "WS_ERR_UNEXPECTED_MASK"
  42438. );
  42439. cb(error2);
  42440. return;
  42441. }
  42442. if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
  42443. else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
  42444. else this.haveLength(cb);
  42445. }
  42446. /**
  42447. * Gets extended payload length (7+16).
  42448. *
  42449. * @param {Function} cb Callback
  42450. * @private
  42451. */
  42452. getPayloadLength16(cb) {
  42453. if (this._bufferedBytes < 2) {
  42454. this._loop = false;
  42455. return;
  42456. }
  42457. this._payloadLength = this.consume(2).readUInt16BE(0);
  42458. this.haveLength(cb);
  42459. }
  42460. /**
  42461. * Gets extended payload length (7+64).
  42462. *
  42463. * @param {Function} cb Callback
  42464. * @private
  42465. */
  42466. getPayloadLength64(cb) {
  42467. if (this._bufferedBytes < 8) {
  42468. this._loop = false;
  42469. return;
  42470. }
  42471. const buf = this.consume(8);
  42472. const num = buf.readUInt32BE(0);
  42473. if (num > Math.pow(2, 53 - 32) - 1) {
  42474. const error2 = this.createError(
  42475. RangeError,
  42476. "Unsupported WebSocket frame: payload length > 2^53 - 1",
  42477. false,
  42478. 1009,
  42479. "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
  42480. );
  42481. cb(error2);
  42482. return;
  42483. }
  42484. this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
  42485. this.haveLength(cb);
  42486. }
  42487. /**
  42488. * Payload length has been read.
  42489. *
  42490. * @param {Function} cb Callback
  42491. * @private
  42492. */
  42493. haveLength(cb) {
  42494. if (this._payloadLength && this._opcode < 8) {
  42495. this._totalPayloadLength += this._payloadLength;
  42496. if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
  42497. const error2 = this.createError(
  42498. RangeError,
  42499. "Max payload size exceeded",
  42500. false,
  42501. 1009,
  42502. "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
  42503. );
  42504. cb(error2);
  42505. return;
  42506. }
  42507. }
  42508. if (this._masked) this._state = GET_MASK;
  42509. else this._state = GET_DATA;
  42510. }
  42511. /**
  42512. * Reads mask bytes.
  42513. *
  42514. * @private
  42515. */
  42516. getMask() {
  42517. if (this._bufferedBytes < 4) {
  42518. this._loop = false;
  42519. return;
  42520. }
  42521. this._mask = this.consume(4);
  42522. this._state = GET_DATA;
  42523. }
  42524. /**
  42525. * Reads data bytes.
  42526. *
  42527. * @param {Function} cb Callback
  42528. * @private
  42529. */
  42530. getData(cb) {
  42531. let data = EMPTY_BUFFER;
  42532. if (this._payloadLength) {
  42533. if (this._bufferedBytes < this._payloadLength) {
  42534. this._loop = false;
  42535. return;
  42536. }
  42537. data = this.consume(this._payloadLength);
  42538. if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
  42539. unmask(data, this._mask);
  42540. }
  42541. }
  42542. if (this._opcode > 7) {
  42543. this.controlMessage(data, cb);
  42544. return;
  42545. }
  42546. if (this._compressed) {
  42547. this._state = INFLATING;
  42548. this.decompress(data, cb);
  42549. return;
  42550. }
  42551. if (data.length) {
  42552. this._messageLength = this._totalPayloadLength;
  42553. this._fragments.push(data);
  42554. }
  42555. this.dataMessage(cb);
  42556. }
  42557. /**
  42558. * Decompresses data.
  42559. *
  42560. * @param {Buffer} data Compressed data
  42561. * @param {Function} cb Callback
  42562. * @private
  42563. */
  42564. decompress(data, cb) {
  42565. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  42566. perMessageDeflate.decompress(data, this._fin, (err2, buf) => {
  42567. if (err2) return cb(err2);
  42568. if (buf.length) {
  42569. this._messageLength += buf.length;
  42570. if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
  42571. const error2 = this.createError(
  42572. RangeError,
  42573. "Max payload size exceeded",
  42574. false,
  42575. 1009,
  42576. "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
  42577. );
  42578. cb(error2);
  42579. return;
  42580. }
  42581. this._fragments.push(buf);
  42582. }
  42583. this.dataMessage(cb);
  42584. if (this._state === GET_INFO) this.startLoop(cb);
  42585. });
  42586. }
  42587. /**
  42588. * Handles a data message.
  42589. *
  42590. * @param {Function} cb Callback
  42591. * @private
  42592. */
  42593. dataMessage(cb) {
  42594. if (!this._fin) {
  42595. this._state = GET_INFO;
  42596. return;
  42597. }
  42598. const messageLength = this._messageLength;
  42599. const fragments = this._fragments;
  42600. this._totalPayloadLength = 0;
  42601. this._messageLength = 0;
  42602. this._fragmented = 0;
  42603. this._fragments = [];
  42604. if (this._opcode === 2) {
  42605. let data;
  42606. if (this._binaryType === "nodebuffer") {
  42607. data = concat(fragments, messageLength);
  42608. } else if (this._binaryType === "arraybuffer") {
  42609. data = toArrayBuffer(concat(fragments, messageLength));
  42610. } else if (this._binaryType === "blob") {
  42611. data = new Blob(fragments);
  42612. } else {
  42613. data = fragments;
  42614. }
  42615. if (this._allowSynchronousEvents) {
  42616. this.emit("message", data, true);
  42617. this._state = GET_INFO;
  42618. } else {
  42619. this._state = DEFER_EVENT;
  42620. setImmediate(() => {
  42621. this.emit("message", data, true);
  42622. this._state = GET_INFO;
  42623. this.startLoop(cb);
  42624. });
  42625. }
  42626. } else {
  42627. const buf = concat(fragments, messageLength);
  42628. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  42629. const error2 = this.createError(
  42630. Error,
  42631. "invalid UTF-8 sequence",
  42632. true,
  42633. 1007,
  42634. "WS_ERR_INVALID_UTF8"
  42635. );
  42636. cb(error2);
  42637. return;
  42638. }
  42639. if (this._state === INFLATING || this._allowSynchronousEvents) {
  42640. this.emit("message", buf, false);
  42641. this._state = GET_INFO;
  42642. } else {
  42643. this._state = DEFER_EVENT;
  42644. setImmediate(() => {
  42645. this.emit("message", buf, false);
  42646. this._state = GET_INFO;
  42647. this.startLoop(cb);
  42648. });
  42649. }
  42650. }
  42651. }
  42652. /**
  42653. * Handles a control message.
  42654. *
  42655. * @param {Buffer} data Data to handle
  42656. * @return {(Error|RangeError|undefined)} A possible error
  42657. * @private
  42658. */
  42659. controlMessage(data, cb) {
  42660. if (this._opcode === 8) {
  42661. if (data.length === 0) {
  42662. this._loop = false;
  42663. this.emit("conclude", 1005, EMPTY_BUFFER);
  42664. this.end();
  42665. } else {
  42666. const code = data.readUInt16BE(0);
  42667. if (!isValidStatusCode(code)) {
  42668. const error2 = this.createError(
  42669. RangeError,
  42670. `invalid status code ${code}`,
  42671. true,
  42672. 1002,
  42673. "WS_ERR_INVALID_CLOSE_CODE"
  42674. );
  42675. cb(error2);
  42676. return;
  42677. }
  42678. const buf = new FastBuffer(
  42679. data.buffer,
  42680. data.byteOffset + 2,
  42681. data.length - 2
  42682. );
  42683. if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
  42684. const error2 = this.createError(
  42685. Error,
  42686. "invalid UTF-8 sequence",
  42687. true,
  42688. 1007,
  42689. "WS_ERR_INVALID_UTF8"
  42690. );
  42691. cb(error2);
  42692. return;
  42693. }
  42694. this._loop = false;
  42695. this.emit("conclude", code, buf);
  42696. this.end();
  42697. }
  42698. this._state = GET_INFO;
  42699. return;
  42700. }
  42701. if (this._allowSynchronousEvents) {
  42702. this.emit(this._opcode === 9 ? "ping" : "pong", data);
  42703. this._state = GET_INFO;
  42704. } else {
  42705. this._state = DEFER_EVENT;
  42706. setImmediate(() => {
  42707. this.emit(this._opcode === 9 ? "ping" : "pong", data);
  42708. this._state = GET_INFO;
  42709. this.startLoop(cb);
  42710. });
  42711. }
  42712. }
  42713. /**
  42714. * Builds an error object.
  42715. *
  42716. * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
  42717. * @param {String} message The error message
  42718. * @param {Boolean} prefix Specifies whether or not to add a default prefix to
  42719. * `message`
  42720. * @param {Number} statusCode The status code
  42721. * @param {String} errorCode The exposed error code
  42722. * @return {(Error|RangeError)} The error
  42723. * @private
  42724. */
  42725. createError(ErrorCtor, message, prefix2, statusCode, errorCode) {
  42726. this._loop = false;
  42727. this._errored = true;
  42728. const err2 = new ErrorCtor(
  42729. prefix2 ? `Invalid WebSocket frame: ${message}` : message
  42730. );
  42731. Error.captureStackTrace(err2, this.createError);
  42732. err2.code = errorCode;
  42733. err2[kStatusCode] = statusCode;
  42734. return err2;
  42735. }
  42736. };
  42737. module2.exports = Receiver2;
  42738. }
  42739. });
  42740. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/sender.js
  42741. var require_sender = __commonJS({
  42742. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/sender.js"(exports2, module2) {
  42743. "use strict";
  42744. var { Duplex } = require("stream");
  42745. var { randomFillSync } = require("crypto");
  42746. var PerMessageDeflate = require_permessage_deflate();
  42747. var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants2();
  42748. var { isBlob: isBlob3, isValidStatusCode } = require_validation();
  42749. var { mask: applyMask, toBuffer } = require_buffer_util();
  42750. var kByteLength = Symbol("kByteLength");
  42751. var maskBuffer = Buffer.alloc(4);
  42752. var RANDOM_POOL_SIZE = 8 * 1024;
  42753. var randomPool;
  42754. var randomPoolPointer = RANDOM_POOL_SIZE;
  42755. var DEFAULT = 0;
  42756. var DEFLATING = 1;
  42757. var GET_BLOB_DATA = 2;
  42758. var Sender2 = class _Sender {
  42759. /**
  42760. * Creates a Sender instance.
  42761. *
  42762. * @param {Duplex} socket The connection socket
  42763. * @param {Object} [extensions] An object containing the negotiated extensions
  42764. * @param {Function} [generateMask] The function used to generate the masking
  42765. * key
  42766. */
  42767. constructor(socket, extensions, generateMask) {
  42768. this._extensions = extensions || {};
  42769. if (generateMask) {
  42770. this._generateMask = generateMask;
  42771. this._maskBuffer = Buffer.alloc(4);
  42772. }
  42773. this._socket = socket;
  42774. this._firstFragment = true;
  42775. this._compress = false;
  42776. this._bufferedBytes = 0;
  42777. this._queue = [];
  42778. this._state = DEFAULT;
  42779. this.onerror = NOOP;
  42780. this[kWebSocket] = void 0;
  42781. }
  42782. /**
  42783. * Frames a piece of data according to the HyBi WebSocket protocol.
  42784. *
  42785. * @param {(Buffer|String)} data The data to frame
  42786. * @param {Object} options Options object
  42787. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  42788. * FIN bit
  42789. * @param {Function} [options.generateMask] The function used to generate the
  42790. * masking key
  42791. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  42792. * `data`
  42793. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  42794. * key
  42795. * @param {Number} options.opcode The opcode
  42796. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  42797. * modified
  42798. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  42799. * RSV1 bit
  42800. * @return {(Buffer|String)[]} The framed data
  42801. * @public
  42802. */
  42803. static frame(data, options) {
  42804. let mask;
  42805. let merge = false;
  42806. let offset = 2;
  42807. let skipMasking = false;
  42808. if (options.mask) {
  42809. mask = options.maskBuffer || maskBuffer;
  42810. if (options.generateMask) {
  42811. options.generateMask(mask);
  42812. } else {
  42813. if (randomPoolPointer === RANDOM_POOL_SIZE) {
  42814. if (randomPool === void 0) {
  42815. randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
  42816. }
  42817. randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
  42818. randomPoolPointer = 0;
  42819. }
  42820. mask[0] = randomPool[randomPoolPointer++];
  42821. mask[1] = randomPool[randomPoolPointer++];
  42822. mask[2] = randomPool[randomPoolPointer++];
  42823. mask[3] = randomPool[randomPoolPointer++];
  42824. }
  42825. skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
  42826. offset = 6;
  42827. }
  42828. let dataLength;
  42829. if (typeof data === "string") {
  42830. if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
  42831. dataLength = options[kByteLength];
  42832. } else {
  42833. data = Buffer.from(data);
  42834. dataLength = data.length;
  42835. }
  42836. } else {
  42837. dataLength = data.length;
  42838. merge = options.mask && options.readOnly && !skipMasking;
  42839. }
  42840. let payloadLength = dataLength;
  42841. if (dataLength >= 65536) {
  42842. offset += 8;
  42843. payloadLength = 127;
  42844. } else if (dataLength > 125) {
  42845. offset += 2;
  42846. payloadLength = 126;
  42847. }
  42848. const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
  42849. target[0] = options.fin ? options.opcode | 128 : options.opcode;
  42850. if (options.rsv1) target[0] |= 64;
  42851. target[1] = payloadLength;
  42852. if (payloadLength === 126) {
  42853. target.writeUInt16BE(dataLength, 2);
  42854. } else if (payloadLength === 127) {
  42855. target[2] = target[3] = 0;
  42856. target.writeUIntBE(dataLength, 4, 6);
  42857. }
  42858. if (!options.mask) return [target, data];
  42859. target[1] |= 128;
  42860. target[offset - 4] = mask[0];
  42861. target[offset - 3] = mask[1];
  42862. target[offset - 2] = mask[2];
  42863. target[offset - 1] = mask[3];
  42864. if (skipMasking) return [target, data];
  42865. if (merge) {
  42866. applyMask(data, mask, target, offset, dataLength);
  42867. return [target];
  42868. }
  42869. applyMask(data, mask, data, 0, dataLength);
  42870. return [target, data];
  42871. }
  42872. /**
  42873. * Sends a close message to the other peer.
  42874. *
  42875. * @param {Number} [code] The status code component of the body
  42876. * @param {(String|Buffer)} [data] The message component of the body
  42877. * @param {Boolean} [mask=false] Specifies whether or not to mask the message
  42878. * @param {Function} [cb] Callback
  42879. * @public
  42880. */
  42881. close(code, data, mask, cb) {
  42882. let buf;
  42883. if (code === void 0) {
  42884. buf = EMPTY_BUFFER;
  42885. } else if (typeof code !== "number" || !isValidStatusCode(code)) {
  42886. throw new TypeError("First argument must be a valid error code number");
  42887. } else if (data === void 0 || !data.length) {
  42888. buf = Buffer.allocUnsafe(2);
  42889. buf.writeUInt16BE(code, 0);
  42890. } else {
  42891. const length = Buffer.byteLength(data);
  42892. if (length > 123) {
  42893. throw new RangeError("The message must not be greater than 123 bytes");
  42894. }
  42895. buf = Buffer.allocUnsafe(2 + length);
  42896. buf.writeUInt16BE(code, 0);
  42897. if (typeof data === "string") {
  42898. buf.write(data, 2);
  42899. } else {
  42900. buf.set(data, 2);
  42901. }
  42902. }
  42903. const options = {
  42904. [kByteLength]: buf.length,
  42905. fin: true,
  42906. generateMask: this._generateMask,
  42907. mask,
  42908. maskBuffer: this._maskBuffer,
  42909. opcode: 8,
  42910. readOnly: false,
  42911. rsv1: false
  42912. };
  42913. if (this._state !== DEFAULT) {
  42914. this.enqueue([this.dispatch, buf, false, options, cb]);
  42915. } else {
  42916. this.sendFrame(_Sender.frame(buf, options), cb);
  42917. }
  42918. }
  42919. /**
  42920. * Sends a ping message to the other peer.
  42921. *
  42922. * @param {*} data The message to send
  42923. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  42924. * @param {Function} [cb] Callback
  42925. * @public
  42926. */
  42927. ping(data, mask, cb) {
  42928. let byteLength;
  42929. let readOnly;
  42930. if (typeof data === "string") {
  42931. byteLength = Buffer.byteLength(data);
  42932. readOnly = false;
  42933. } else if (isBlob3(data)) {
  42934. byteLength = data.size;
  42935. readOnly = false;
  42936. } else {
  42937. data = toBuffer(data);
  42938. byteLength = data.length;
  42939. readOnly = toBuffer.readOnly;
  42940. }
  42941. if (byteLength > 125) {
  42942. throw new RangeError("The data size must not be greater than 125 bytes");
  42943. }
  42944. const options = {
  42945. [kByteLength]: byteLength,
  42946. fin: true,
  42947. generateMask: this._generateMask,
  42948. mask,
  42949. maskBuffer: this._maskBuffer,
  42950. opcode: 9,
  42951. readOnly,
  42952. rsv1: false
  42953. };
  42954. if (isBlob3(data)) {
  42955. if (this._state !== DEFAULT) {
  42956. this.enqueue([this.getBlobData, data, false, options, cb]);
  42957. } else {
  42958. this.getBlobData(data, false, options, cb);
  42959. }
  42960. } else if (this._state !== DEFAULT) {
  42961. this.enqueue([this.dispatch, data, false, options, cb]);
  42962. } else {
  42963. this.sendFrame(_Sender.frame(data, options), cb);
  42964. }
  42965. }
  42966. /**
  42967. * Sends a pong message to the other peer.
  42968. *
  42969. * @param {*} data The message to send
  42970. * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
  42971. * @param {Function} [cb] Callback
  42972. * @public
  42973. */
  42974. pong(data, mask, cb) {
  42975. let byteLength;
  42976. let readOnly;
  42977. if (typeof data === "string") {
  42978. byteLength = Buffer.byteLength(data);
  42979. readOnly = false;
  42980. } else if (isBlob3(data)) {
  42981. byteLength = data.size;
  42982. readOnly = false;
  42983. } else {
  42984. data = toBuffer(data);
  42985. byteLength = data.length;
  42986. readOnly = toBuffer.readOnly;
  42987. }
  42988. if (byteLength > 125) {
  42989. throw new RangeError("The data size must not be greater than 125 bytes");
  42990. }
  42991. const options = {
  42992. [kByteLength]: byteLength,
  42993. fin: true,
  42994. generateMask: this._generateMask,
  42995. mask,
  42996. maskBuffer: this._maskBuffer,
  42997. opcode: 10,
  42998. readOnly,
  42999. rsv1: false
  43000. };
  43001. if (isBlob3(data)) {
  43002. if (this._state !== DEFAULT) {
  43003. this.enqueue([this.getBlobData, data, false, options, cb]);
  43004. } else {
  43005. this.getBlobData(data, false, options, cb);
  43006. }
  43007. } else if (this._state !== DEFAULT) {
  43008. this.enqueue([this.dispatch, data, false, options, cb]);
  43009. } else {
  43010. this.sendFrame(_Sender.frame(data, options), cb);
  43011. }
  43012. }
  43013. /**
  43014. * Sends a data message to the other peer.
  43015. *
  43016. * @param {*} data The message to send
  43017. * @param {Object} options Options object
  43018. * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
  43019. * or text
  43020. * @param {Boolean} [options.compress=false] Specifies whether or not to
  43021. * compress `data`
  43022. * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
  43023. * last one
  43024. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  43025. * `data`
  43026. * @param {Function} [cb] Callback
  43027. * @public
  43028. */
  43029. send(data, options, cb) {
  43030. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  43031. let opcode = options.binary ? 2 : 1;
  43032. let rsv1 = options.compress;
  43033. let byteLength;
  43034. let readOnly;
  43035. if (typeof data === "string") {
  43036. byteLength = Buffer.byteLength(data);
  43037. readOnly = false;
  43038. } else if (isBlob3(data)) {
  43039. byteLength = data.size;
  43040. readOnly = false;
  43041. } else {
  43042. data = toBuffer(data);
  43043. byteLength = data.length;
  43044. readOnly = toBuffer.readOnly;
  43045. }
  43046. if (this._firstFragment) {
  43047. this._firstFragment = false;
  43048. if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
  43049. rsv1 = byteLength >= perMessageDeflate._threshold;
  43050. }
  43051. this._compress = rsv1;
  43052. } else {
  43053. rsv1 = false;
  43054. opcode = 0;
  43055. }
  43056. if (options.fin) this._firstFragment = true;
  43057. const opts = {
  43058. [kByteLength]: byteLength,
  43059. fin: options.fin,
  43060. generateMask: this._generateMask,
  43061. mask: options.mask,
  43062. maskBuffer: this._maskBuffer,
  43063. opcode,
  43064. readOnly,
  43065. rsv1
  43066. };
  43067. if (isBlob3(data)) {
  43068. if (this._state !== DEFAULT) {
  43069. this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
  43070. } else {
  43071. this.getBlobData(data, this._compress, opts, cb);
  43072. }
  43073. } else if (this._state !== DEFAULT) {
  43074. this.enqueue([this.dispatch, data, this._compress, opts, cb]);
  43075. } else {
  43076. this.dispatch(data, this._compress, opts, cb);
  43077. }
  43078. }
  43079. /**
  43080. * Gets the contents of a blob as binary data.
  43081. *
  43082. * @param {Blob} blob The blob
  43083. * @param {Boolean} [compress=false] Specifies whether or not to compress
  43084. * the data
  43085. * @param {Object} options Options object
  43086. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  43087. * FIN bit
  43088. * @param {Function} [options.generateMask] The function used to generate the
  43089. * masking key
  43090. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  43091. * `data`
  43092. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  43093. * key
  43094. * @param {Number} options.opcode The opcode
  43095. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  43096. * modified
  43097. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  43098. * RSV1 bit
  43099. * @param {Function} [cb] Callback
  43100. * @private
  43101. */
  43102. getBlobData(blob, compress2, options, cb) {
  43103. this._bufferedBytes += options[kByteLength];
  43104. this._state = GET_BLOB_DATA;
  43105. blob.arrayBuffer().then((arrayBuffer) => {
  43106. if (this._socket.destroyed) {
  43107. const err2 = new Error(
  43108. "The socket was closed while the blob was being read"
  43109. );
  43110. process.nextTick(callCallbacks, this, err2, cb);
  43111. return;
  43112. }
  43113. this._bufferedBytes -= options[kByteLength];
  43114. const data = toBuffer(arrayBuffer);
  43115. if (!compress2) {
  43116. this._state = DEFAULT;
  43117. this.sendFrame(_Sender.frame(data, options), cb);
  43118. this.dequeue();
  43119. } else {
  43120. this.dispatch(data, compress2, options, cb);
  43121. }
  43122. }).catch((err2) => {
  43123. process.nextTick(onError, this, err2, cb);
  43124. });
  43125. }
  43126. /**
  43127. * Dispatches a message.
  43128. *
  43129. * @param {(Buffer|String)} data The message to send
  43130. * @param {Boolean} [compress=false] Specifies whether or not to compress
  43131. * `data`
  43132. * @param {Object} options Options object
  43133. * @param {Boolean} [options.fin=false] Specifies whether or not to set the
  43134. * FIN bit
  43135. * @param {Function} [options.generateMask] The function used to generate the
  43136. * masking key
  43137. * @param {Boolean} [options.mask=false] Specifies whether or not to mask
  43138. * `data`
  43139. * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
  43140. * key
  43141. * @param {Number} options.opcode The opcode
  43142. * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
  43143. * modified
  43144. * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
  43145. * RSV1 bit
  43146. * @param {Function} [cb] Callback
  43147. * @private
  43148. */
  43149. dispatch(data, compress2, options, cb) {
  43150. if (!compress2) {
  43151. this.sendFrame(_Sender.frame(data, options), cb);
  43152. return;
  43153. }
  43154. const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
  43155. this._bufferedBytes += options[kByteLength];
  43156. this._state = DEFLATING;
  43157. perMessageDeflate.compress(data, options.fin, (_3, buf) => {
  43158. if (this._socket.destroyed) {
  43159. const err2 = new Error(
  43160. "The socket was closed while data was being compressed"
  43161. );
  43162. callCallbacks(this, err2, cb);
  43163. return;
  43164. }
  43165. this._bufferedBytes -= options[kByteLength];
  43166. this._state = DEFAULT;
  43167. options.readOnly = false;
  43168. this.sendFrame(_Sender.frame(buf, options), cb);
  43169. this.dequeue();
  43170. });
  43171. }
  43172. /**
  43173. * Executes queued send operations.
  43174. *
  43175. * @private
  43176. */
  43177. dequeue() {
  43178. while (this._state === DEFAULT && this._queue.length) {
  43179. const params = this._queue.shift();
  43180. this._bufferedBytes -= params[3][kByteLength];
  43181. Reflect.apply(params[0], this, params.slice(1));
  43182. }
  43183. }
  43184. /**
  43185. * Enqueues a send operation.
  43186. *
  43187. * @param {Array} params Send operation parameters.
  43188. * @private
  43189. */
  43190. enqueue(params) {
  43191. this._bufferedBytes += params[3][kByteLength];
  43192. this._queue.push(params);
  43193. }
  43194. /**
  43195. * Sends a frame.
  43196. *
  43197. * @param {(Buffer | String)[]} list The frame to send
  43198. * @param {Function} [cb] Callback
  43199. * @private
  43200. */
  43201. sendFrame(list, cb) {
  43202. if (list.length === 2) {
  43203. this._socket.cork();
  43204. this._socket.write(list[0]);
  43205. this._socket.write(list[1], cb);
  43206. this._socket.uncork();
  43207. } else {
  43208. this._socket.write(list[0], cb);
  43209. }
  43210. }
  43211. };
  43212. module2.exports = Sender2;
  43213. function callCallbacks(sender, err2, cb) {
  43214. if (typeof cb === "function") cb(err2);
  43215. for (let i4 = 0; i4 < sender._queue.length; i4++) {
  43216. const params = sender._queue[i4];
  43217. const callback = params[params.length - 1];
  43218. if (typeof callback === "function") callback(err2);
  43219. }
  43220. }
  43221. function onError(sender, err2, cb) {
  43222. callCallbacks(sender, err2, cb);
  43223. sender.onerror(err2);
  43224. }
  43225. }
  43226. });
  43227. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/event-target.js
  43228. var require_event_target = __commonJS({
  43229. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/event-target.js"(exports2, module2) {
  43230. "use strict";
  43231. var { kForOnEventAttribute, kListener } = require_constants2();
  43232. var kCode = Symbol("kCode");
  43233. var kData = Symbol("kData");
  43234. var kError = Symbol("kError");
  43235. var kMessage = Symbol("kMessage");
  43236. var kReason = Symbol("kReason");
  43237. var kTarget = Symbol("kTarget");
  43238. var kType = Symbol("kType");
  43239. var kWasClean = Symbol("kWasClean");
  43240. var Event = class {
  43241. /**
  43242. * Create a new `Event`.
  43243. *
  43244. * @param {String} type The name of the event
  43245. * @throws {TypeError} If the `type` argument is not specified
  43246. */
  43247. constructor(type) {
  43248. this[kTarget] = null;
  43249. this[kType] = type;
  43250. }
  43251. /**
  43252. * @type {*}
  43253. */
  43254. get target() {
  43255. return this[kTarget];
  43256. }
  43257. /**
  43258. * @type {String}
  43259. */
  43260. get type() {
  43261. return this[kType];
  43262. }
  43263. };
  43264. Object.defineProperty(Event.prototype, "target", { enumerable: true });
  43265. Object.defineProperty(Event.prototype, "type", { enumerable: true });
  43266. var CloseEvent = class extends Event {
  43267. /**
  43268. * Create a new `CloseEvent`.
  43269. *
  43270. * @param {String} type The name of the event
  43271. * @param {Object} [options] A dictionary object that allows for setting
  43272. * attributes via object members of the same name
  43273. * @param {Number} [options.code=0] The status code explaining why the
  43274. * connection was closed
  43275. * @param {String} [options.reason=''] A human-readable string explaining why
  43276. * the connection was closed
  43277. * @param {Boolean} [options.wasClean=false] Indicates whether or not the
  43278. * connection was cleanly closed
  43279. */
  43280. constructor(type, options = {}) {
  43281. super(type);
  43282. this[kCode] = options.code === void 0 ? 0 : options.code;
  43283. this[kReason] = options.reason === void 0 ? "" : options.reason;
  43284. this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
  43285. }
  43286. /**
  43287. * @type {Number}
  43288. */
  43289. get code() {
  43290. return this[kCode];
  43291. }
  43292. /**
  43293. * @type {String}
  43294. */
  43295. get reason() {
  43296. return this[kReason];
  43297. }
  43298. /**
  43299. * @type {Boolean}
  43300. */
  43301. get wasClean() {
  43302. return this[kWasClean];
  43303. }
  43304. };
  43305. Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
  43306. Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
  43307. Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
  43308. var ErrorEvent = class extends Event {
  43309. /**
  43310. * Create a new `ErrorEvent`.
  43311. *
  43312. * @param {String} type The name of the event
  43313. * @param {Object} [options] A dictionary object that allows for setting
  43314. * attributes via object members of the same name
  43315. * @param {*} [options.error=null] The error that generated this event
  43316. * @param {String} [options.message=''] The error message
  43317. */
  43318. constructor(type, options = {}) {
  43319. super(type);
  43320. this[kError] = options.error === void 0 ? null : options.error;
  43321. this[kMessage] = options.message === void 0 ? "" : options.message;
  43322. }
  43323. /**
  43324. * @type {*}
  43325. */
  43326. get error() {
  43327. return this[kError];
  43328. }
  43329. /**
  43330. * @type {String}
  43331. */
  43332. get message() {
  43333. return this[kMessage];
  43334. }
  43335. };
  43336. Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
  43337. Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
  43338. var MessageEvent = class extends Event {
  43339. /**
  43340. * Create a new `MessageEvent`.
  43341. *
  43342. * @param {String} type The name of the event
  43343. * @param {Object} [options] A dictionary object that allows for setting
  43344. * attributes via object members of the same name
  43345. * @param {*} [options.data=null] The message content
  43346. */
  43347. constructor(type, options = {}) {
  43348. super(type);
  43349. this[kData] = options.data === void 0 ? null : options.data;
  43350. }
  43351. /**
  43352. * @type {*}
  43353. */
  43354. get data() {
  43355. return this[kData];
  43356. }
  43357. };
  43358. Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
  43359. var EventTarget = {
  43360. /**
  43361. * Register an event listener.
  43362. *
  43363. * @param {String} type A string representing the event type to listen for
  43364. * @param {(Function|Object)} handler The listener to add
  43365. * @param {Object} [options] An options object specifies characteristics about
  43366. * the event listener
  43367. * @param {Boolean} [options.once=false] A `Boolean` indicating that the
  43368. * listener should be invoked at most once after being added. If `true`,
  43369. * the listener would be automatically removed when invoked.
  43370. * @public
  43371. */
  43372. addEventListener(type, handler, options = {}) {
  43373. for (const listener of this.listeners(type)) {
  43374. if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
  43375. return;
  43376. }
  43377. }
  43378. let wrapper;
  43379. if (type === "message") {
  43380. wrapper = function onMessage(data, isBinary) {
  43381. const event = new MessageEvent("message", {
  43382. data: isBinary ? data : data.toString()
  43383. });
  43384. event[kTarget] = this;
  43385. callListener(handler, this, event);
  43386. };
  43387. } else if (type === "close") {
  43388. wrapper = function onClose(code, message) {
  43389. const event = new CloseEvent("close", {
  43390. code,
  43391. reason: message.toString(),
  43392. wasClean: this._closeFrameReceived && this._closeFrameSent
  43393. });
  43394. event[kTarget] = this;
  43395. callListener(handler, this, event);
  43396. };
  43397. } else if (type === "error") {
  43398. wrapper = function onError(error2) {
  43399. const event = new ErrorEvent("error", {
  43400. error: error2,
  43401. message: error2.message
  43402. });
  43403. event[kTarget] = this;
  43404. callListener(handler, this, event);
  43405. };
  43406. } else if (type === "open") {
  43407. wrapper = function onOpen() {
  43408. const event = new Event("open");
  43409. event[kTarget] = this;
  43410. callListener(handler, this, event);
  43411. };
  43412. } else {
  43413. return;
  43414. }
  43415. wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
  43416. wrapper[kListener] = handler;
  43417. if (options.once) {
  43418. this.once(type, wrapper);
  43419. } else {
  43420. this.on(type, wrapper);
  43421. }
  43422. },
  43423. /**
  43424. * Remove an event listener.
  43425. *
  43426. * @param {String} type A string representing the event type to remove
  43427. * @param {(Function|Object)} handler The listener to remove
  43428. * @public
  43429. */
  43430. removeEventListener(type, handler) {
  43431. for (const listener of this.listeners(type)) {
  43432. if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
  43433. this.removeListener(type, listener);
  43434. break;
  43435. }
  43436. }
  43437. }
  43438. };
  43439. module2.exports = {
  43440. CloseEvent,
  43441. ErrorEvent,
  43442. Event,
  43443. EventTarget,
  43444. MessageEvent
  43445. };
  43446. function callListener(listener, thisArg, event) {
  43447. if (typeof listener === "object" && listener.handleEvent) {
  43448. listener.handleEvent.call(listener, event);
  43449. } else {
  43450. listener.call(thisArg, event);
  43451. }
  43452. }
  43453. }
  43454. });
  43455. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/extension.js
  43456. var require_extension = __commonJS({
  43457. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/extension.js"(exports2, module2) {
  43458. "use strict";
  43459. var { tokenChars } = require_validation();
  43460. function push2(dest, name, elem) {
  43461. if (dest[name] === void 0) dest[name] = [elem];
  43462. else dest[name].push(elem);
  43463. }
  43464. function parse4(header) {
  43465. const offers = /* @__PURE__ */ Object.create(null);
  43466. let params = /* @__PURE__ */ Object.create(null);
  43467. let mustUnescape = false;
  43468. let isEscaping = false;
  43469. let inQuotes = false;
  43470. let extensionName;
  43471. let paramName;
  43472. let start = -1;
  43473. let code = -1;
  43474. let end = -1;
  43475. let i4 = 0;
  43476. for (; i4 < header.length; i4++) {
  43477. code = header.charCodeAt(i4);
  43478. if (extensionName === void 0) {
  43479. if (end === -1 && tokenChars[code] === 1) {
  43480. if (start === -1) start = i4;
  43481. } else if (i4 !== 0 && (code === 32 || code === 9)) {
  43482. if (end === -1 && start !== -1) end = i4;
  43483. } else if (code === 59 || code === 44) {
  43484. if (start === -1) {
  43485. throw new SyntaxError(`Unexpected character at index ${i4}`);
  43486. }
  43487. if (end === -1) end = i4;
  43488. const name = header.slice(start, end);
  43489. if (code === 44) {
  43490. push2(offers, name, params);
  43491. params = /* @__PURE__ */ Object.create(null);
  43492. } else {
  43493. extensionName = name;
  43494. }
  43495. start = end = -1;
  43496. } else {
  43497. throw new SyntaxError(`Unexpected character at index ${i4}`);
  43498. }
  43499. } else if (paramName === void 0) {
  43500. if (end === -1 && tokenChars[code] === 1) {
  43501. if (start === -1) start = i4;
  43502. } else if (code === 32 || code === 9) {
  43503. if (end === -1 && start !== -1) end = i4;
  43504. } else if (code === 59 || code === 44) {
  43505. if (start === -1) {
  43506. throw new SyntaxError(`Unexpected character at index ${i4}`);
  43507. }
  43508. if (end === -1) end = i4;
  43509. push2(params, header.slice(start, end), true);
  43510. if (code === 44) {
  43511. push2(offers, extensionName, params);
  43512. params = /* @__PURE__ */ Object.create(null);
  43513. extensionName = void 0;
  43514. }
  43515. start = end = -1;
  43516. } else if (code === 61 && start !== -1 && end === -1) {
  43517. paramName = header.slice(start, i4);
  43518. start = end = -1;
  43519. } else {
  43520. throw new SyntaxError(`Unexpected character at index ${i4}`);
  43521. }
  43522. } else {
  43523. if (isEscaping) {
  43524. if (tokenChars[code] !== 1) {
  43525. throw new SyntaxError(`Unexpected character at index ${i4}`);
  43526. }
  43527. if (start === -1) start = i4;
  43528. else if (!mustUnescape) mustUnescape = true;
  43529. isEscaping = false;
  43530. } else if (inQuotes) {
  43531. if (tokenChars[code] === 1) {
  43532. if (start === -1) start = i4;
  43533. } else if (code === 34 && start !== -1) {
  43534. inQuotes = false;
  43535. end = i4;
  43536. } else if (code === 92) {
  43537. isEscaping = true;
  43538. } else {
  43539. throw new SyntaxError(`Unexpected character at index ${i4}`);
  43540. }
  43541. } else if (code === 34 && header.charCodeAt(i4 - 1) === 61) {
  43542. inQuotes = true;
  43543. } else if (end === -1 && tokenChars[code] === 1) {
  43544. if (start === -1) start = i4;
  43545. } else if (start !== -1 && (code === 32 || code === 9)) {
  43546. if (end === -1) end = i4;
  43547. } else if (code === 59 || code === 44) {
  43548. if (start === -1) {
  43549. throw new SyntaxError(`Unexpected character at index ${i4}`);
  43550. }
  43551. if (end === -1) end = i4;
  43552. let value = header.slice(start, end);
  43553. if (mustUnescape) {
  43554. value = value.replace(/\\/g, "");
  43555. mustUnescape = false;
  43556. }
  43557. push2(params, paramName, value);
  43558. if (code === 44) {
  43559. push2(offers, extensionName, params);
  43560. params = /* @__PURE__ */ Object.create(null);
  43561. extensionName = void 0;
  43562. }
  43563. paramName = void 0;
  43564. start = end = -1;
  43565. } else {
  43566. throw new SyntaxError(`Unexpected character at index ${i4}`);
  43567. }
  43568. }
  43569. }
  43570. if (start === -1 || inQuotes || code === 32 || code === 9) {
  43571. throw new SyntaxError("Unexpected end of input");
  43572. }
  43573. if (end === -1) end = i4;
  43574. const token = header.slice(start, end);
  43575. if (extensionName === void 0) {
  43576. push2(offers, token, params);
  43577. } else {
  43578. if (paramName === void 0) {
  43579. push2(params, token, true);
  43580. } else if (mustUnescape) {
  43581. push2(params, paramName, token.replace(/\\/g, ""));
  43582. } else {
  43583. push2(params, paramName, token);
  43584. }
  43585. push2(offers, extensionName, params);
  43586. }
  43587. return offers;
  43588. }
  43589. function format(extensions) {
  43590. return Object.keys(extensions).map((extension) => {
  43591. let configurations = extensions[extension];
  43592. if (!Array.isArray(configurations)) configurations = [configurations];
  43593. return configurations.map((params) => {
  43594. return [extension].concat(
  43595. Object.keys(params).map((k3) => {
  43596. let values = params[k3];
  43597. if (!Array.isArray(values)) values = [values];
  43598. return values.map((v6) => v6 === true ? k3 : `${k3}=${v6}`).join("; ");
  43599. })
  43600. ).join("; ");
  43601. }).join(", ");
  43602. }).join(", ");
  43603. }
  43604. module2.exports = { format, parse: parse4 };
  43605. }
  43606. });
  43607. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/websocket.js
  43608. var require_websocket = __commonJS({
  43609. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/websocket.js"(exports2, module2) {
  43610. "use strict";
  43611. var EventEmitter = require("events");
  43612. var https2 = require("https");
  43613. var http3 = require("http");
  43614. var net = require("net");
  43615. var tls = require("tls");
  43616. var { randomBytes, createHash: createHash2 } = require("crypto");
  43617. var { Duplex, Readable: Readable2 } = require("stream");
  43618. var { URL: URL3 } = require("url");
  43619. var PerMessageDeflate = require_permessage_deflate();
  43620. var Receiver2 = require_receiver();
  43621. var Sender2 = require_sender();
  43622. var { isBlob: isBlob3 } = require_validation();
  43623. var {
  43624. BINARY_TYPES,
  43625. EMPTY_BUFFER,
  43626. GUID,
  43627. kForOnEventAttribute,
  43628. kListener,
  43629. kStatusCode,
  43630. kWebSocket,
  43631. NOOP
  43632. } = require_constants2();
  43633. var {
  43634. EventTarget: { addEventListener: addEventListener2, removeEventListener }
  43635. } = require_event_target();
  43636. var { format, parse: parse4 } = require_extension();
  43637. var { toBuffer } = require_buffer_util();
  43638. var closeTimeout = 30 * 1e3;
  43639. var kAborted = Symbol("kAborted");
  43640. var protocolVersions = [8, 13];
  43641. var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
  43642. var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
  43643. var WebSocket2 = class _WebSocket extends EventEmitter {
  43644. /**
  43645. * Create a new `WebSocket`.
  43646. *
  43647. * @param {(String|URL)} address The URL to which to connect
  43648. * @param {(String|String[])} [protocols] The subprotocols
  43649. * @param {Object} [options] Connection options
  43650. */
  43651. constructor(address, protocols, options) {
  43652. super();
  43653. this._binaryType = BINARY_TYPES[0];
  43654. this._closeCode = 1006;
  43655. this._closeFrameReceived = false;
  43656. this._closeFrameSent = false;
  43657. this._closeMessage = EMPTY_BUFFER;
  43658. this._closeTimer = null;
  43659. this._errorEmitted = false;
  43660. this._extensions = {};
  43661. this._paused = false;
  43662. this._protocol = "";
  43663. this._readyState = _WebSocket.CONNECTING;
  43664. this._receiver = null;
  43665. this._sender = null;
  43666. this._socket = null;
  43667. if (address !== null) {
  43668. this._bufferedAmount = 0;
  43669. this._isServer = false;
  43670. this._redirects = 0;
  43671. if (protocols === void 0) {
  43672. protocols = [];
  43673. } else if (!Array.isArray(protocols)) {
  43674. if (typeof protocols === "object" && protocols !== null) {
  43675. options = protocols;
  43676. protocols = [];
  43677. } else {
  43678. protocols = [protocols];
  43679. }
  43680. }
  43681. initAsClient(this, address, protocols, options);
  43682. } else {
  43683. this._autoPong = options.autoPong;
  43684. this._isServer = true;
  43685. }
  43686. }
  43687. /**
  43688. * For historical reasons, the custom "nodebuffer" type is used by the default
  43689. * instead of "blob".
  43690. *
  43691. * @type {String}
  43692. */
  43693. get binaryType() {
  43694. return this._binaryType;
  43695. }
  43696. set binaryType(type) {
  43697. if (!BINARY_TYPES.includes(type)) return;
  43698. this._binaryType = type;
  43699. if (this._receiver) this._receiver._binaryType = type;
  43700. }
  43701. /**
  43702. * @type {Number}
  43703. */
  43704. get bufferedAmount() {
  43705. if (!this._socket) return this._bufferedAmount;
  43706. return this._socket._writableState.length + this._sender._bufferedBytes;
  43707. }
  43708. /**
  43709. * @type {String}
  43710. */
  43711. get extensions() {
  43712. return Object.keys(this._extensions).join();
  43713. }
  43714. /**
  43715. * @type {Boolean}
  43716. */
  43717. get isPaused() {
  43718. return this._paused;
  43719. }
  43720. /**
  43721. * @type {Function}
  43722. */
  43723. /* istanbul ignore next */
  43724. get onclose() {
  43725. return null;
  43726. }
  43727. /**
  43728. * @type {Function}
  43729. */
  43730. /* istanbul ignore next */
  43731. get onerror() {
  43732. return null;
  43733. }
  43734. /**
  43735. * @type {Function}
  43736. */
  43737. /* istanbul ignore next */
  43738. get onopen() {
  43739. return null;
  43740. }
  43741. /**
  43742. * @type {Function}
  43743. */
  43744. /* istanbul ignore next */
  43745. get onmessage() {
  43746. return null;
  43747. }
  43748. /**
  43749. * @type {String}
  43750. */
  43751. get protocol() {
  43752. return this._protocol;
  43753. }
  43754. /**
  43755. * @type {Number}
  43756. */
  43757. get readyState() {
  43758. return this._readyState;
  43759. }
  43760. /**
  43761. * @type {String}
  43762. */
  43763. get url() {
  43764. return this._url;
  43765. }
  43766. /**
  43767. * Set up the socket and the internal resources.
  43768. *
  43769. * @param {Duplex} socket The network socket between the server and client
  43770. * @param {Buffer} head The first packet of the upgraded stream
  43771. * @param {Object} options Options object
  43772. * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
  43773. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  43774. * multiple times in the same tick
  43775. * @param {Function} [options.generateMask] The function used to generate the
  43776. * masking key
  43777. * @param {Number} [options.maxPayload=0] The maximum allowed message size
  43778. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  43779. * not to skip UTF-8 validation for text and close messages
  43780. * @private
  43781. */
  43782. setSocket(socket, head, options) {
  43783. const receiver = new Receiver2({
  43784. allowSynchronousEvents: options.allowSynchronousEvents,
  43785. binaryType: this.binaryType,
  43786. extensions: this._extensions,
  43787. isServer: this._isServer,
  43788. maxPayload: options.maxPayload,
  43789. skipUTF8Validation: options.skipUTF8Validation
  43790. });
  43791. const sender = new Sender2(socket, this._extensions, options.generateMask);
  43792. this._receiver = receiver;
  43793. this._sender = sender;
  43794. this._socket = socket;
  43795. receiver[kWebSocket] = this;
  43796. sender[kWebSocket] = this;
  43797. socket[kWebSocket] = this;
  43798. receiver.on("conclude", receiverOnConclude);
  43799. receiver.on("drain", receiverOnDrain);
  43800. receiver.on("error", receiverOnError);
  43801. receiver.on("message", receiverOnMessage);
  43802. receiver.on("ping", receiverOnPing);
  43803. receiver.on("pong", receiverOnPong);
  43804. sender.onerror = senderOnError;
  43805. if (socket.setTimeout) socket.setTimeout(0);
  43806. if (socket.setNoDelay) socket.setNoDelay();
  43807. if (head.length > 0) socket.unshift(head);
  43808. socket.on("close", socketOnClose);
  43809. socket.on("data", socketOnData);
  43810. socket.on("end", socketOnEnd);
  43811. socket.on("error", socketOnError);
  43812. this._readyState = _WebSocket.OPEN;
  43813. this.emit("open");
  43814. }
  43815. /**
  43816. * Emit the `'close'` event.
  43817. *
  43818. * @private
  43819. */
  43820. emitClose() {
  43821. if (!this._socket) {
  43822. this._readyState = _WebSocket.CLOSED;
  43823. this.emit("close", this._closeCode, this._closeMessage);
  43824. return;
  43825. }
  43826. if (this._extensions[PerMessageDeflate.extensionName]) {
  43827. this._extensions[PerMessageDeflate.extensionName].cleanup();
  43828. }
  43829. this._receiver.removeAllListeners();
  43830. this._readyState = _WebSocket.CLOSED;
  43831. this.emit("close", this._closeCode, this._closeMessage);
  43832. }
  43833. /**
  43834. * Start a closing handshake.
  43835. *
  43836. * +----------+ +-----------+ +----------+
  43837. * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
  43838. * | +----------+ +-----------+ +----------+ |
  43839. * +----------+ +-----------+ |
  43840. * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
  43841. * +----------+ +-----------+ |
  43842. * | | | +---+ |
  43843. * +------------------------+-->|fin| - - - -
  43844. * | +---+ | +---+
  43845. * - - - - -|fin|<---------------------+
  43846. * +---+
  43847. *
  43848. * @param {Number} [code] Status code explaining why the connection is closing
  43849. * @param {(String|Buffer)} [data] The reason why the connection is
  43850. * closing
  43851. * @public
  43852. */
  43853. close(code, data) {
  43854. if (this.readyState === _WebSocket.CLOSED) return;
  43855. if (this.readyState === _WebSocket.CONNECTING) {
  43856. const msg = "WebSocket was closed before the connection was established";
  43857. abortHandshake(this, this._req, msg);
  43858. return;
  43859. }
  43860. if (this.readyState === _WebSocket.CLOSING) {
  43861. if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
  43862. this._socket.end();
  43863. }
  43864. return;
  43865. }
  43866. this._readyState = _WebSocket.CLOSING;
  43867. this._sender.close(code, data, !this._isServer, (err2) => {
  43868. if (err2) return;
  43869. this._closeFrameSent = true;
  43870. if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
  43871. this._socket.end();
  43872. }
  43873. });
  43874. setCloseTimer(this);
  43875. }
  43876. /**
  43877. * Pause the socket.
  43878. *
  43879. * @public
  43880. */
  43881. pause() {
  43882. if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
  43883. return;
  43884. }
  43885. this._paused = true;
  43886. this._socket.pause();
  43887. }
  43888. /**
  43889. * Send a ping.
  43890. *
  43891. * @param {*} [data] The data to send
  43892. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  43893. * @param {Function} [cb] Callback which is executed when the ping is sent
  43894. * @public
  43895. */
  43896. ping(data, mask, cb) {
  43897. if (this.readyState === _WebSocket.CONNECTING) {
  43898. throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  43899. }
  43900. if (typeof data === "function") {
  43901. cb = data;
  43902. data = mask = void 0;
  43903. } else if (typeof mask === "function") {
  43904. cb = mask;
  43905. mask = void 0;
  43906. }
  43907. if (typeof data === "number") data = data.toString();
  43908. if (this.readyState !== _WebSocket.OPEN) {
  43909. sendAfterClose(this, data, cb);
  43910. return;
  43911. }
  43912. if (mask === void 0) mask = !this._isServer;
  43913. this._sender.ping(data || EMPTY_BUFFER, mask, cb);
  43914. }
  43915. /**
  43916. * Send a pong.
  43917. *
  43918. * @param {*} [data] The data to send
  43919. * @param {Boolean} [mask] Indicates whether or not to mask `data`
  43920. * @param {Function} [cb] Callback which is executed when the pong is sent
  43921. * @public
  43922. */
  43923. pong(data, mask, cb) {
  43924. if (this.readyState === _WebSocket.CONNECTING) {
  43925. throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  43926. }
  43927. if (typeof data === "function") {
  43928. cb = data;
  43929. data = mask = void 0;
  43930. } else if (typeof mask === "function") {
  43931. cb = mask;
  43932. mask = void 0;
  43933. }
  43934. if (typeof data === "number") data = data.toString();
  43935. if (this.readyState !== _WebSocket.OPEN) {
  43936. sendAfterClose(this, data, cb);
  43937. return;
  43938. }
  43939. if (mask === void 0) mask = !this._isServer;
  43940. this._sender.pong(data || EMPTY_BUFFER, mask, cb);
  43941. }
  43942. /**
  43943. * Resume the socket.
  43944. *
  43945. * @public
  43946. */
  43947. resume() {
  43948. if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
  43949. return;
  43950. }
  43951. this._paused = false;
  43952. if (!this._receiver._writableState.needDrain) this._socket.resume();
  43953. }
  43954. /**
  43955. * Send a data message.
  43956. *
  43957. * @param {*} data The message to send
  43958. * @param {Object} [options] Options object
  43959. * @param {Boolean} [options.binary] Specifies whether `data` is binary or
  43960. * text
  43961. * @param {Boolean} [options.compress] Specifies whether or not to compress
  43962. * `data`
  43963. * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
  43964. * last one
  43965. * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
  43966. * @param {Function} [cb] Callback which is executed when data is written out
  43967. * @public
  43968. */
  43969. send(data, options, cb) {
  43970. if (this.readyState === _WebSocket.CONNECTING) {
  43971. throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
  43972. }
  43973. if (typeof options === "function") {
  43974. cb = options;
  43975. options = {};
  43976. }
  43977. if (typeof data === "number") data = data.toString();
  43978. if (this.readyState !== _WebSocket.OPEN) {
  43979. sendAfterClose(this, data, cb);
  43980. return;
  43981. }
  43982. const opts = {
  43983. binary: typeof data !== "string",
  43984. mask: !this._isServer,
  43985. compress: true,
  43986. fin: true,
  43987. ...options
  43988. };
  43989. if (!this._extensions[PerMessageDeflate.extensionName]) {
  43990. opts.compress = false;
  43991. }
  43992. this._sender.send(data || EMPTY_BUFFER, opts, cb);
  43993. }
  43994. /**
  43995. * Forcibly close the connection.
  43996. *
  43997. * @public
  43998. */
  43999. terminate() {
  44000. if (this.readyState === _WebSocket.CLOSED) return;
  44001. if (this.readyState === _WebSocket.CONNECTING) {
  44002. const msg = "WebSocket was closed before the connection was established";
  44003. abortHandshake(this, this._req, msg);
  44004. return;
  44005. }
  44006. if (this._socket) {
  44007. this._readyState = _WebSocket.CLOSING;
  44008. this._socket.destroy();
  44009. }
  44010. }
  44011. };
  44012. Object.defineProperty(WebSocket2, "CONNECTING", {
  44013. enumerable: true,
  44014. value: readyStates.indexOf("CONNECTING")
  44015. });
  44016. Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
  44017. enumerable: true,
  44018. value: readyStates.indexOf("CONNECTING")
  44019. });
  44020. Object.defineProperty(WebSocket2, "OPEN", {
  44021. enumerable: true,
  44022. value: readyStates.indexOf("OPEN")
  44023. });
  44024. Object.defineProperty(WebSocket2.prototype, "OPEN", {
  44025. enumerable: true,
  44026. value: readyStates.indexOf("OPEN")
  44027. });
  44028. Object.defineProperty(WebSocket2, "CLOSING", {
  44029. enumerable: true,
  44030. value: readyStates.indexOf("CLOSING")
  44031. });
  44032. Object.defineProperty(WebSocket2.prototype, "CLOSING", {
  44033. enumerable: true,
  44034. value: readyStates.indexOf("CLOSING")
  44035. });
  44036. Object.defineProperty(WebSocket2, "CLOSED", {
  44037. enumerable: true,
  44038. value: readyStates.indexOf("CLOSED")
  44039. });
  44040. Object.defineProperty(WebSocket2.prototype, "CLOSED", {
  44041. enumerable: true,
  44042. value: readyStates.indexOf("CLOSED")
  44043. });
  44044. [
  44045. "binaryType",
  44046. "bufferedAmount",
  44047. "extensions",
  44048. "isPaused",
  44049. "protocol",
  44050. "readyState",
  44051. "url"
  44052. ].forEach((property) => {
  44053. Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
  44054. });
  44055. ["open", "error", "close", "message"].forEach((method) => {
  44056. Object.defineProperty(WebSocket2.prototype, `on${method}`, {
  44057. enumerable: true,
  44058. get() {
  44059. for (const listener of this.listeners(method)) {
  44060. if (listener[kForOnEventAttribute]) return listener[kListener];
  44061. }
  44062. return null;
  44063. },
  44064. set(handler) {
  44065. for (const listener of this.listeners(method)) {
  44066. if (listener[kForOnEventAttribute]) {
  44067. this.removeListener(method, listener);
  44068. break;
  44069. }
  44070. }
  44071. if (typeof handler !== "function") return;
  44072. this.addEventListener(method, handler, {
  44073. [kForOnEventAttribute]: true
  44074. });
  44075. }
  44076. });
  44077. });
  44078. WebSocket2.prototype.addEventListener = addEventListener2;
  44079. WebSocket2.prototype.removeEventListener = removeEventListener;
  44080. module2.exports = WebSocket2;
  44081. function initAsClient(websocket, address, protocols, options) {
  44082. const opts = {
  44083. allowSynchronousEvents: true,
  44084. autoPong: true,
  44085. protocolVersion: protocolVersions[1],
  44086. maxPayload: 100 * 1024 * 1024,
  44087. skipUTF8Validation: false,
  44088. perMessageDeflate: true,
  44089. followRedirects: false,
  44090. maxRedirects: 10,
  44091. ...options,
  44092. socketPath: void 0,
  44093. hostname: void 0,
  44094. protocol: void 0,
  44095. timeout: void 0,
  44096. method: "GET",
  44097. host: void 0,
  44098. path: void 0,
  44099. port: void 0
  44100. };
  44101. websocket._autoPong = opts.autoPong;
  44102. if (!protocolVersions.includes(opts.protocolVersion)) {
  44103. throw new RangeError(
  44104. `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
  44105. );
  44106. }
  44107. let parsedUrl;
  44108. if (address instanceof URL3) {
  44109. parsedUrl = address;
  44110. } else {
  44111. try {
  44112. parsedUrl = new URL3(address);
  44113. } catch (e4) {
  44114. throw new SyntaxError(`Invalid URL: ${address}`);
  44115. }
  44116. }
  44117. if (parsedUrl.protocol === "http:") {
  44118. parsedUrl.protocol = "ws:";
  44119. } else if (parsedUrl.protocol === "https:") {
  44120. parsedUrl.protocol = "wss:";
  44121. }
  44122. websocket._url = parsedUrl.href;
  44123. const isSecure = parsedUrl.protocol === "wss:";
  44124. const isIpcUrl = parsedUrl.protocol === "ws+unix:";
  44125. let invalidUrlMessage;
  44126. if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
  44127. invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
  44128. } else if (isIpcUrl && !parsedUrl.pathname) {
  44129. invalidUrlMessage = "The URL's pathname is empty";
  44130. } else if (parsedUrl.hash) {
  44131. invalidUrlMessage = "The URL contains a fragment identifier";
  44132. }
  44133. if (invalidUrlMessage) {
  44134. const err2 = new SyntaxError(invalidUrlMessage);
  44135. if (websocket._redirects === 0) {
  44136. throw err2;
  44137. } else {
  44138. emitErrorAndClose(websocket, err2);
  44139. return;
  44140. }
  44141. }
  44142. const defaultPort = isSecure ? 443 : 80;
  44143. const key = randomBytes(16).toString("base64");
  44144. const request = isSecure ? https2.request : http3.request;
  44145. const protocolSet = /* @__PURE__ */ new Set();
  44146. let perMessageDeflate;
  44147. opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
  44148. opts.defaultPort = opts.defaultPort || defaultPort;
  44149. opts.port = parsedUrl.port || defaultPort;
  44150. opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
  44151. opts.headers = {
  44152. ...opts.headers,
  44153. "Sec-WebSocket-Version": opts.protocolVersion,
  44154. "Sec-WebSocket-Key": key,
  44155. Connection: "Upgrade",
  44156. Upgrade: "websocket"
  44157. };
  44158. opts.path = parsedUrl.pathname + parsedUrl.search;
  44159. opts.timeout = opts.handshakeTimeout;
  44160. if (opts.perMessageDeflate) {
  44161. perMessageDeflate = new PerMessageDeflate(
  44162. opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
  44163. false,
  44164. opts.maxPayload
  44165. );
  44166. opts.headers["Sec-WebSocket-Extensions"] = format({
  44167. [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
  44168. });
  44169. }
  44170. if (protocols.length) {
  44171. for (const protocol of protocols) {
  44172. if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
  44173. throw new SyntaxError(
  44174. "An invalid or duplicated subprotocol was specified"
  44175. );
  44176. }
  44177. protocolSet.add(protocol);
  44178. }
  44179. opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
  44180. }
  44181. if (opts.origin) {
  44182. if (opts.protocolVersion < 13) {
  44183. opts.headers["Sec-WebSocket-Origin"] = opts.origin;
  44184. } else {
  44185. opts.headers.Origin = opts.origin;
  44186. }
  44187. }
  44188. if (parsedUrl.username || parsedUrl.password) {
  44189. opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
  44190. }
  44191. if (isIpcUrl) {
  44192. const parts = opts.path.split(":");
  44193. opts.socketPath = parts[0];
  44194. opts.path = parts[1];
  44195. }
  44196. let req;
  44197. if (opts.followRedirects) {
  44198. if (websocket._redirects === 0) {
  44199. websocket._originalIpc = isIpcUrl;
  44200. websocket._originalSecure = isSecure;
  44201. websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
  44202. const headers = options && options.headers;
  44203. options = { ...options, headers: {} };
  44204. if (headers) {
  44205. for (const [key2, value] of Object.entries(headers)) {
  44206. options.headers[key2.toLowerCase()] = value;
  44207. }
  44208. }
  44209. } else if (websocket.listenerCount("redirect") === 0) {
  44210. const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
  44211. if (!isSameHost || websocket._originalSecure && !isSecure) {
  44212. delete opts.headers.authorization;
  44213. delete opts.headers.cookie;
  44214. if (!isSameHost) delete opts.headers.host;
  44215. opts.auth = void 0;
  44216. }
  44217. }
  44218. if (opts.auth && !options.headers.authorization) {
  44219. options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
  44220. }
  44221. req = websocket._req = request(opts);
  44222. if (websocket._redirects) {
  44223. websocket.emit("redirect", websocket.url, req);
  44224. }
  44225. } else {
  44226. req = websocket._req = request(opts);
  44227. }
  44228. if (opts.timeout) {
  44229. req.on("timeout", () => {
  44230. abortHandshake(websocket, req, "Opening handshake has timed out");
  44231. });
  44232. }
  44233. req.on("error", (err2) => {
  44234. if (req === null || req[kAborted]) return;
  44235. req = websocket._req = null;
  44236. emitErrorAndClose(websocket, err2);
  44237. });
  44238. req.on("response", (res) => {
  44239. const location = res.headers.location;
  44240. const statusCode = res.statusCode;
  44241. if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
  44242. if (++websocket._redirects > opts.maxRedirects) {
  44243. abortHandshake(websocket, req, "Maximum redirects exceeded");
  44244. return;
  44245. }
  44246. req.abort();
  44247. let addr;
  44248. try {
  44249. addr = new URL3(location, address);
  44250. } catch (e4) {
  44251. const err2 = new SyntaxError(`Invalid URL: ${location}`);
  44252. emitErrorAndClose(websocket, err2);
  44253. return;
  44254. }
  44255. initAsClient(websocket, addr, protocols, options);
  44256. } else if (!websocket.emit("unexpected-response", req, res)) {
  44257. abortHandshake(
  44258. websocket,
  44259. req,
  44260. `Unexpected server response: ${res.statusCode}`
  44261. );
  44262. }
  44263. });
  44264. req.on("upgrade", (res, socket, head) => {
  44265. websocket.emit("upgrade", res);
  44266. if (websocket.readyState !== WebSocket2.CONNECTING) return;
  44267. req = websocket._req = null;
  44268. const upgrade = res.headers.upgrade;
  44269. if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
  44270. abortHandshake(websocket, socket, "Invalid Upgrade header");
  44271. return;
  44272. }
  44273. const digest = createHash2("sha1").update(key + GUID).digest("base64");
  44274. if (res.headers["sec-websocket-accept"] !== digest) {
  44275. abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
  44276. return;
  44277. }
  44278. const serverProt = res.headers["sec-websocket-protocol"];
  44279. let protError;
  44280. if (serverProt !== void 0) {
  44281. if (!protocolSet.size) {
  44282. protError = "Server sent a subprotocol but none was requested";
  44283. } else if (!protocolSet.has(serverProt)) {
  44284. protError = "Server sent an invalid subprotocol";
  44285. }
  44286. } else if (protocolSet.size) {
  44287. protError = "Server sent no subprotocol";
  44288. }
  44289. if (protError) {
  44290. abortHandshake(websocket, socket, protError);
  44291. return;
  44292. }
  44293. if (serverProt) websocket._protocol = serverProt;
  44294. const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
  44295. if (secWebSocketExtensions !== void 0) {
  44296. if (!perMessageDeflate) {
  44297. const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
  44298. abortHandshake(websocket, socket, message);
  44299. return;
  44300. }
  44301. let extensions;
  44302. try {
  44303. extensions = parse4(secWebSocketExtensions);
  44304. } catch (err2) {
  44305. const message = "Invalid Sec-WebSocket-Extensions header";
  44306. abortHandshake(websocket, socket, message);
  44307. return;
  44308. }
  44309. const extensionNames = Object.keys(extensions);
  44310. if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
  44311. const message = "Server indicated an extension that was not requested";
  44312. abortHandshake(websocket, socket, message);
  44313. return;
  44314. }
  44315. try {
  44316. perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
  44317. } catch (err2) {
  44318. const message = "Invalid Sec-WebSocket-Extensions header";
  44319. abortHandshake(websocket, socket, message);
  44320. return;
  44321. }
  44322. websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  44323. }
  44324. websocket.setSocket(socket, head, {
  44325. allowSynchronousEvents: opts.allowSynchronousEvents,
  44326. generateMask: opts.generateMask,
  44327. maxPayload: opts.maxPayload,
  44328. skipUTF8Validation: opts.skipUTF8Validation
  44329. });
  44330. });
  44331. if (opts.finishRequest) {
  44332. opts.finishRequest(req, websocket);
  44333. } else {
  44334. req.end();
  44335. }
  44336. }
  44337. function emitErrorAndClose(websocket, err2) {
  44338. websocket._readyState = WebSocket2.CLOSING;
  44339. websocket._errorEmitted = true;
  44340. websocket.emit("error", err2);
  44341. websocket.emitClose();
  44342. }
  44343. function netConnect(options) {
  44344. options.path = options.socketPath;
  44345. return net.connect(options);
  44346. }
  44347. function tlsConnect(options) {
  44348. options.path = void 0;
  44349. if (!options.servername && options.servername !== "") {
  44350. options.servername = net.isIP(options.host) ? "" : options.host;
  44351. }
  44352. return tls.connect(options);
  44353. }
  44354. function abortHandshake(websocket, stream, message) {
  44355. websocket._readyState = WebSocket2.CLOSING;
  44356. const err2 = new Error(message);
  44357. Error.captureStackTrace(err2, abortHandshake);
  44358. if (stream.setHeader) {
  44359. stream[kAborted] = true;
  44360. stream.abort();
  44361. if (stream.socket && !stream.socket.destroyed) {
  44362. stream.socket.destroy();
  44363. }
  44364. process.nextTick(emitErrorAndClose, websocket, err2);
  44365. } else {
  44366. stream.destroy(err2);
  44367. stream.once("error", websocket.emit.bind(websocket, "error"));
  44368. stream.once("close", websocket.emitClose.bind(websocket));
  44369. }
  44370. }
  44371. function sendAfterClose(websocket, data, cb) {
  44372. if (data) {
  44373. const length = isBlob3(data) ? data.size : toBuffer(data).length;
  44374. if (websocket._socket) websocket._sender._bufferedBytes += length;
  44375. else websocket._bufferedAmount += length;
  44376. }
  44377. if (cb) {
  44378. const err2 = new Error(
  44379. `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
  44380. );
  44381. process.nextTick(cb, err2);
  44382. }
  44383. }
  44384. function receiverOnConclude(code, reason) {
  44385. const websocket = this[kWebSocket];
  44386. websocket._closeFrameReceived = true;
  44387. websocket._closeMessage = reason;
  44388. websocket._closeCode = code;
  44389. if (websocket._socket[kWebSocket] === void 0) return;
  44390. websocket._socket.removeListener("data", socketOnData);
  44391. process.nextTick(resume, websocket._socket);
  44392. if (code === 1005) websocket.close();
  44393. else websocket.close(code, reason);
  44394. }
  44395. function receiverOnDrain() {
  44396. const websocket = this[kWebSocket];
  44397. if (!websocket.isPaused) websocket._socket.resume();
  44398. }
  44399. function receiverOnError(err2) {
  44400. const websocket = this[kWebSocket];
  44401. if (websocket._socket[kWebSocket] !== void 0) {
  44402. websocket._socket.removeListener("data", socketOnData);
  44403. process.nextTick(resume, websocket._socket);
  44404. websocket.close(err2[kStatusCode]);
  44405. }
  44406. if (!websocket._errorEmitted) {
  44407. websocket._errorEmitted = true;
  44408. websocket.emit("error", err2);
  44409. }
  44410. }
  44411. function receiverOnFinish() {
  44412. this[kWebSocket].emitClose();
  44413. }
  44414. function receiverOnMessage(data, isBinary) {
  44415. this[kWebSocket].emit("message", data, isBinary);
  44416. }
  44417. function receiverOnPing(data) {
  44418. const websocket = this[kWebSocket];
  44419. if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
  44420. websocket.emit("ping", data);
  44421. }
  44422. function receiverOnPong(data) {
  44423. this[kWebSocket].emit("pong", data);
  44424. }
  44425. function resume(stream) {
  44426. stream.resume();
  44427. }
  44428. function senderOnError(err2) {
  44429. const websocket = this[kWebSocket];
  44430. if (websocket.readyState === WebSocket2.CLOSED) return;
  44431. if (websocket.readyState === WebSocket2.OPEN) {
  44432. websocket._readyState = WebSocket2.CLOSING;
  44433. setCloseTimer(websocket);
  44434. }
  44435. this._socket.end();
  44436. if (!websocket._errorEmitted) {
  44437. websocket._errorEmitted = true;
  44438. websocket.emit("error", err2);
  44439. }
  44440. }
  44441. function setCloseTimer(websocket) {
  44442. websocket._closeTimer = setTimeout(
  44443. websocket._socket.destroy.bind(websocket._socket),
  44444. closeTimeout
  44445. );
  44446. }
  44447. function socketOnClose() {
  44448. const websocket = this[kWebSocket];
  44449. this.removeListener("close", socketOnClose);
  44450. this.removeListener("data", socketOnData);
  44451. this.removeListener("end", socketOnEnd);
  44452. websocket._readyState = WebSocket2.CLOSING;
  44453. let chunk;
  44454. if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
  44455. websocket._receiver.write(chunk);
  44456. }
  44457. websocket._receiver.end();
  44458. this[kWebSocket] = void 0;
  44459. clearTimeout(websocket._closeTimer);
  44460. if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
  44461. websocket.emitClose();
  44462. } else {
  44463. websocket._receiver.on("error", receiverOnFinish);
  44464. websocket._receiver.on("finish", receiverOnFinish);
  44465. }
  44466. }
  44467. function socketOnData(chunk) {
  44468. if (!this[kWebSocket]._receiver.write(chunk)) {
  44469. this.pause();
  44470. }
  44471. }
  44472. function socketOnEnd() {
  44473. const websocket = this[kWebSocket];
  44474. websocket._readyState = WebSocket2.CLOSING;
  44475. websocket._receiver.end();
  44476. this.end();
  44477. }
  44478. function socketOnError() {
  44479. const websocket = this[kWebSocket];
  44480. this.removeListener("error", socketOnError);
  44481. this.on("error", NOOP);
  44482. if (websocket) {
  44483. websocket._readyState = WebSocket2.CLOSING;
  44484. this.destroy();
  44485. }
  44486. }
  44487. }
  44488. });
  44489. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/stream.js
  44490. var require_stream = __commonJS({
  44491. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/stream.js"(exports2, module2) {
  44492. "use strict";
  44493. var WebSocket2 = require_websocket();
  44494. var { Duplex } = require("stream");
  44495. function emitClose(stream) {
  44496. stream.emit("close");
  44497. }
  44498. function duplexOnEnd() {
  44499. if (!this.destroyed && this._writableState.finished) {
  44500. this.destroy();
  44501. }
  44502. }
  44503. function duplexOnError(err2) {
  44504. this.removeListener("error", duplexOnError);
  44505. this.destroy();
  44506. if (this.listenerCount("error") === 0) {
  44507. this.emit("error", err2);
  44508. }
  44509. }
  44510. function createWebSocketStream2(ws, options) {
  44511. let terminateOnDestroy = true;
  44512. const duplex = new Duplex({
  44513. ...options,
  44514. autoDestroy: false,
  44515. emitClose: false,
  44516. objectMode: false,
  44517. writableObjectMode: false
  44518. });
  44519. ws.on("message", function message(msg, isBinary) {
  44520. const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
  44521. if (!duplex.push(data)) ws.pause();
  44522. });
  44523. ws.once("error", function error2(err2) {
  44524. if (duplex.destroyed) return;
  44525. terminateOnDestroy = false;
  44526. duplex.destroy(err2);
  44527. });
  44528. ws.once("close", function close() {
  44529. if (duplex.destroyed) return;
  44530. duplex.push(null);
  44531. });
  44532. duplex._destroy = function(err2, callback) {
  44533. if (ws.readyState === ws.CLOSED) {
  44534. callback(err2);
  44535. process.nextTick(emitClose, duplex);
  44536. return;
  44537. }
  44538. let called = false;
  44539. ws.once("error", function error2(err3) {
  44540. called = true;
  44541. callback(err3);
  44542. });
  44543. ws.once("close", function close() {
  44544. if (!called) callback(err2);
  44545. process.nextTick(emitClose, duplex);
  44546. });
  44547. if (terminateOnDestroy) ws.terminate();
  44548. };
  44549. duplex._final = function(callback) {
  44550. if (ws.readyState === ws.CONNECTING) {
  44551. ws.once("open", function open() {
  44552. duplex._final(callback);
  44553. });
  44554. return;
  44555. }
  44556. if (ws._socket === null) return;
  44557. if (ws._socket._writableState.finished) {
  44558. callback();
  44559. if (duplex._readableState.endEmitted) duplex.destroy();
  44560. } else {
  44561. ws._socket.once("finish", function finish() {
  44562. callback();
  44563. });
  44564. ws.close();
  44565. }
  44566. };
  44567. duplex._read = function() {
  44568. if (ws.isPaused) ws.resume();
  44569. };
  44570. duplex._write = function(chunk, encoding, callback) {
  44571. if (ws.readyState === ws.CONNECTING) {
  44572. ws.once("open", function open() {
  44573. duplex._write(chunk, encoding, callback);
  44574. });
  44575. return;
  44576. }
  44577. ws.send(chunk, callback);
  44578. };
  44579. duplex.on("end", duplexOnEnd);
  44580. duplex.on("error", duplexOnError);
  44581. return duplex;
  44582. }
  44583. module2.exports = createWebSocketStream2;
  44584. }
  44585. });
  44586. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/subprotocol.js
  44587. var require_subprotocol = __commonJS({
  44588. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/subprotocol.js"(exports2, module2) {
  44589. "use strict";
  44590. var { tokenChars } = require_validation();
  44591. function parse4(header) {
  44592. const protocols = /* @__PURE__ */ new Set();
  44593. let start = -1;
  44594. let end = -1;
  44595. let i4 = 0;
  44596. for (i4; i4 < header.length; i4++) {
  44597. const code = header.charCodeAt(i4);
  44598. if (end === -1 && tokenChars[code] === 1) {
  44599. if (start === -1) start = i4;
  44600. } else if (i4 !== 0 && (code === 32 || code === 9)) {
  44601. if (end === -1 && start !== -1) end = i4;
  44602. } else if (code === 44) {
  44603. if (start === -1) {
  44604. throw new SyntaxError(`Unexpected character at index ${i4}`);
  44605. }
  44606. if (end === -1) end = i4;
  44607. const protocol2 = header.slice(start, end);
  44608. if (protocols.has(protocol2)) {
  44609. throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
  44610. }
  44611. protocols.add(protocol2);
  44612. start = end = -1;
  44613. } else {
  44614. throw new SyntaxError(`Unexpected character at index ${i4}`);
  44615. }
  44616. }
  44617. if (start === -1 || end !== -1) {
  44618. throw new SyntaxError("Unexpected end of input");
  44619. }
  44620. const protocol = header.slice(start, i4);
  44621. if (protocols.has(protocol)) {
  44622. throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
  44623. }
  44624. protocols.add(protocol);
  44625. return protocols;
  44626. }
  44627. module2.exports = { parse: parse4 };
  44628. }
  44629. });
  44630. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/websocket-server.js
  44631. var require_websocket_server = __commonJS({
  44632. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/lib/websocket-server.js"(exports2, module2) {
  44633. "use strict";
  44634. var EventEmitter = require("events");
  44635. var http3 = require("http");
  44636. var { Duplex } = require("stream");
  44637. var { createHash: createHash2 } = require("crypto");
  44638. var extension = require_extension();
  44639. var PerMessageDeflate = require_permessage_deflate();
  44640. var subprotocol = require_subprotocol();
  44641. var WebSocket2 = require_websocket();
  44642. var { GUID, kWebSocket } = require_constants2();
  44643. var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
  44644. var RUNNING = 0;
  44645. var CLOSING = 1;
  44646. var CLOSED = 2;
  44647. var WebSocketServer2 = class extends EventEmitter {
  44648. /**
  44649. * Create a `WebSocketServer` instance.
  44650. *
  44651. * @param {Object} options Configuration options
  44652. * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
  44653. * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
  44654. * multiple times in the same tick
  44655. * @param {Boolean} [options.autoPong=true] Specifies whether or not to
  44656. * automatically send a pong in response to a ping
  44657. * @param {Number} [options.backlog=511] The maximum length of the queue of
  44658. * pending connections
  44659. * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
  44660. * track clients
  44661. * @param {Function} [options.handleProtocols] A hook to handle protocols
  44662. * @param {String} [options.host] The hostname where to bind the server
  44663. * @param {Number} [options.maxPayload=104857600] The maximum allowed message
  44664. * size
  44665. * @param {Boolean} [options.noServer=false] Enable no server mode
  44666. * @param {String} [options.path] Accept only connections matching this path
  44667. * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
  44668. * permessage-deflate
  44669. * @param {Number} [options.port] The port where to bind the server
  44670. * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
  44671. * server to use
  44672. * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
  44673. * not to skip UTF-8 validation for text and close messages
  44674. * @param {Function} [options.verifyClient] A hook to reject connections
  44675. * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
  44676. * class to use. It must be the `WebSocket` class or class that extends it
  44677. * @param {Function} [callback] A listener for the `listening` event
  44678. */
  44679. constructor(options, callback) {
  44680. super();
  44681. options = {
  44682. allowSynchronousEvents: true,
  44683. autoPong: true,
  44684. maxPayload: 100 * 1024 * 1024,
  44685. skipUTF8Validation: false,
  44686. perMessageDeflate: false,
  44687. handleProtocols: null,
  44688. clientTracking: true,
  44689. verifyClient: null,
  44690. noServer: false,
  44691. backlog: null,
  44692. // use default (511 as implemented in net.js)
  44693. server: null,
  44694. host: null,
  44695. path: null,
  44696. port: null,
  44697. WebSocket: WebSocket2,
  44698. ...options
  44699. };
  44700. if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
  44701. throw new TypeError(
  44702. 'One and only one of the "port", "server", or "noServer" options must be specified'
  44703. );
  44704. }
  44705. if (options.port != null) {
  44706. this._server = http3.createServer((req, res) => {
  44707. const body = http3.STATUS_CODES[426];
  44708. res.writeHead(426, {
  44709. "Content-Length": body.length,
  44710. "Content-Type": "text/plain"
  44711. });
  44712. res.end(body);
  44713. });
  44714. this._server.listen(
  44715. options.port,
  44716. options.host,
  44717. options.backlog,
  44718. callback
  44719. );
  44720. } else if (options.server) {
  44721. this._server = options.server;
  44722. }
  44723. if (this._server) {
  44724. const emitConnection = this.emit.bind(this, "connection");
  44725. this._removeListeners = addListeners(this._server, {
  44726. listening: this.emit.bind(this, "listening"),
  44727. error: this.emit.bind(this, "error"),
  44728. upgrade: (req, socket, head) => {
  44729. this.handleUpgrade(req, socket, head, emitConnection);
  44730. }
  44731. });
  44732. }
  44733. if (options.perMessageDeflate === true) options.perMessageDeflate = {};
  44734. if (options.clientTracking) {
  44735. this.clients = /* @__PURE__ */ new Set();
  44736. this._shouldEmitClose = false;
  44737. }
  44738. this.options = options;
  44739. this._state = RUNNING;
  44740. }
  44741. /**
  44742. * Returns the bound address, the address family name, and port of the server
  44743. * as reported by the operating system if listening on an IP socket.
  44744. * If the server is listening on a pipe or UNIX domain socket, the name is
  44745. * returned as a string.
  44746. *
  44747. * @return {(Object|String|null)} The address of the server
  44748. * @public
  44749. */
  44750. address() {
  44751. if (this.options.noServer) {
  44752. throw new Error('The server is operating in "noServer" mode');
  44753. }
  44754. if (!this._server) return null;
  44755. return this._server.address();
  44756. }
  44757. /**
  44758. * Stop the server from accepting new connections and emit the `'close'` event
  44759. * when all existing connections are closed.
  44760. *
  44761. * @param {Function} [cb] A one-time listener for the `'close'` event
  44762. * @public
  44763. */
  44764. close(cb) {
  44765. if (this._state === CLOSED) {
  44766. if (cb) {
  44767. this.once("close", () => {
  44768. cb(new Error("The server is not running"));
  44769. });
  44770. }
  44771. process.nextTick(emitClose, this);
  44772. return;
  44773. }
  44774. if (cb) this.once("close", cb);
  44775. if (this._state === CLOSING) return;
  44776. this._state = CLOSING;
  44777. if (this.options.noServer || this.options.server) {
  44778. if (this._server) {
  44779. this._removeListeners();
  44780. this._removeListeners = this._server = null;
  44781. }
  44782. if (this.clients) {
  44783. if (!this.clients.size) {
  44784. process.nextTick(emitClose, this);
  44785. } else {
  44786. this._shouldEmitClose = true;
  44787. }
  44788. } else {
  44789. process.nextTick(emitClose, this);
  44790. }
  44791. } else {
  44792. const server = this._server;
  44793. this._removeListeners();
  44794. this._removeListeners = this._server = null;
  44795. server.close(() => {
  44796. emitClose(this);
  44797. });
  44798. }
  44799. }
  44800. /**
  44801. * See if a given request should be handled by this server instance.
  44802. *
  44803. * @param {http.IncomingMessage} req Request object to inspect
  44804. * @return {Boolean} `true` if the request is valid, else `false`
  44805. * @public
  44806. */
  44807. shouldHandle(req) {
  44808. if (this.options.path) {
  44809. const index6 = req.url.indexOf("?");
  44810. const pathname = index6 !== -1 ? req.url.slice(0, index6) : req.url;
  44811. if (pathname !== this.options.path) return false;
  44812. }
  44813. return true;
  44814. }
  44815. /**
  44816. * Handle a HTTP Upgrade request.
  44817. *
  44818. * @param {http.IncomingMessage} req The request object
  44819. * @param {Duplex} socket The network socket between the server and client
  44820. * @param {Buffer} head The first packet of the upgraded stream
  44821. * @param {Function} cb Callback
  44822. * @public
  44823. */
  44824. handleUpgrade(req, socket, head, cb) {
  44825. socket.on("error", socketOnError);
  44826. const key = req.headers["sec-websocket-key"];
  44827. const upgrade = req.headers.upgrade;
  44828. const version3 = +req.headers["sec-websocket-version"];
  44829. if (req.method !== "GET") {
  44830. const message = "Invalid HTTP method";
  44831. abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
  44832. return;
  44833. }
  44834. if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
  44835. const message = "Invalid Upgrade header";
  44836. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  44837. return;
  44838. }
  44839. if (key === void 0 || !keyRegex.test(key)) {
  44840. const message = "Missing or invalid Sec-WebSocket-Key header";
  44841. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  44842. return;
  44843. }
  44844. if (version3 !== 8 && version3 !== 13) {
  44845. const message = "Missing or invalid Sec-WebSocket-Version header";
  44846. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  44847. return;
  44848. }
  44849. if (!this.shouldHandle(req)) {
  44850. abortHandshake(socket, 400);
  44851. return;
  44852. }
  44853. const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
  44854. let protocols = /* @__PURE__ */ new Set();
  44855. if (secWebSocketProtocol !== void 0) {
  44856. try {
  44857. protocols = subprotocol.parse(secWebSocketProtocol);
  44858. } catch (err2) {
  44859. const message = "Invalid Sec-WebSocket-Protocol header";
  44860. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  44861. return;
  44862. }
  44863. }
  44864. const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
  44865. const extensions = {};
  44866. if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
  44867. const perMessageDeflate = new PerMessageDeflate(
  44868. this.options.perMessageDeflate,
  44869. true,
  44870. this.options.maxPayload
  44871. );
  44872. try {
  44873. const offers = extension.parse(secWebSocketExtensions);
  44874. if (offers[PerMessageDeflate.extensionName]) {
  44875. perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
  44876. extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  44877. }
  44878. } catch (err2) {
  44879. const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
  44880. abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
  44881. return;
  44882. }
  44883. }
  44884. if (this.options.verifyClient) {
  44885. const info2 = {
  44886. origin: req.headers[`${version3 === 8 ? "sec-websocket-origin" : "origin"}`],
  44887. secure: !!(req.socket.authorized || req.socket.encrypted),
  44888. req
  44889. };
  44890. if (this.options.verifyClient.length === 2) {
  44891. this.options.verifyClient(info2, (verified, code, message, headers) => {
  44892. if (!verified) {
  44893. return abortHandshake(socket, code || 401, message, headers);
  44894. }
  44895. this.completeUpgrade(
  44896. extensions,
  44897. key,
  44898. protocols,
  44899. req,
  44900. socket,
  44901. head,
  44902. cb
  44903. );
  44904. });
  44905. return;
  44906. }
  44907. if (!this.options.verifyClient(info2)) return abortHandshake(socket, 401);
  44908. }
  44909. this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
  44910. }
  44911. /**
  44912. * Upgrade the connection to WebSocket.
  44913. *
  44914. * @param {Object} extensions The accepted extensions
  44915. * @param {String} key The value of the `Sec-WebSocket-Key` header
  44916. * @param {Set} protocols The subprotocols
  44917. * @param {http.IncomingMessage} req The request object
  44918. * @param {Duplex} socket The network socket between the server and client
  44919. * @param {Buffer} head The first packet of the upgraded stream
  44920. * @param {Function} cb Callback
  44921. * @throws {Error} If called more than once with the same socket
  44922. * @private
  44923. */
  44924. completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
  44925. if (!socket.readable || !socket.writable) return socket.destroy();
  44926. if (socket[kWebSocket]) {
  44927. throw new Error(
  44928. "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
  44929. );
  44930. }
  44931. if (this._state > RUNNING) return abortHandshake(socket, 503);
  44932. const digest = createHash2("sha1").update(key + GUID).digest("base64");
  44933. const headers = [
  44934. "HTTP/1.1 101 Switching Protocols",
  44935. "Upgrade: websocket",
  44936. "Connection: Upgrade",
  44937. `Sec-WebSocket-Accept: ${digest}`
  44938. ];
  44939. const ws = new this.options.WebSocket(null, void 0, this.options);
  44940. if (protocols.size) {
  44941. const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
  44942. if (protocol) {
  44943. headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
  44944. ws._protocol = protocol;
  44945. }
  44946. }
  44947. if (extensions[PerMessageDeflate.extensionName]) {
  44948. const params = extensions[PerMessageDeflate.extensionName].params;
  44949. const value = extension.format({
  44950. [PerMessageDeflate.extensionName]: [params]
  44951. });
  44952. headers.push(`Sec-WebSocket-Extensions: ${value}`);
  44953. ws._extensions = extensions;
  44954. }
  44955. this.emit("headers", headers, req);
  44956. socket.write(headers.concat("\r\n").join("\r\n"));
  44957. socket.removeListener("error", socketOnError);
  44958. ws.setSocket(socket, head, {
  44959. allowSynchronousEvents: this.options.allowSynchronousEvents,
  44960. maxPayload: this.options.maxPayload,
  44961. skipUTF8Validation: this.options.skipUTF8Validation
  44962. });
  44963. if (this.clients) {
  44964. this.clients.add(ws);
  44965. ws.on("close", () => {
  44966. this.clients.delete(ws);
  44967. if (this._shouldEmitClose && !this.clients.size) {
  44968. process.nextTick(emitClose, this);
  44969. }
  44970. });
  44971. }
  44972. cb(ws, req);
  44973. }
  44974. };
  44975. module2.exports = WebSocketServer2;
  44976. function addListeners(server, map2) {
  44977. for (const event of Object.keys(map2)) server.on(event, map2[event]);
  44978. return function removeListeners() {
  44979. for (const event of Object.keys(map2)) {
  44980. server.removeListener(event, map2[event]);
  44981. }
  44982. };
  44983. }
  44984. function emitClose(server) {
  44985. server._state = CLOSED;
  44986. server.emit("close");
  44987. }
  44988. function socketOnError() {
  44989. this.destroy();
  44990. }
  44991. function abortHandshake(socket, code, message, headers) {
  44992. message = message || http3.STATUS_CODES[code];
  44993. headers = {
  44994. Connection: "close",
  44995. "Content-Type": "text/html",
  44996. "Content-Length": Buffer.byteLength(message),
  44997. ...headers
  44998. };
  44999. socket.once("finish", socket.destroy);
  45000. socket.end(
  45001. `HTTP/1.1 ${code} ${http3.STATUS_CODES[code]}\r
  45002. ` + Object.keys(headers).map((h4) => `${h4}: ${headers[h4]}`).join("\r\n") + "\r\n\r\n" + message
  45003. );
  45004. }
  45005. function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
  45006. if (server.listenerCount("wsClientError")) {
  45007. const err2 = new Error(message);
  45008. Error.captureStackTrace(err2, abortHandshakeOrEmitwsClientError);
  45009. server.emit("wsClientError", err2, socket, req);
  45010. } else {
  45011. abortHandshake(socket, code, message);
  45012. }
  45013. }
  45014. }
  45015. });
  45016. // ../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/wrapper.mjs
  45017. var import_stream, import_receiver, import_sender, import_websocket, import_websocket_server, wrapper_default;
  45018. var init_wrapper = __esm({
  45019. "../node_modules/.pnpm/ws@8.18.2_bufferutil@4.0.8_utf-8-validate@6.0.3/node_modules/ws/wrapper.mjs"() {
  45020. import_stream = __toESM(require_stream(), 1);
  45021. import_receiver = __toESM(require_receiver(), 1);
  45022. import_sender = __toESM(require_sender(), 1);
  45023. import_websocket = __toESM(require_websocket(), 1);
  45024. import_websocket_server = __toESM(require_websocket_server(), 1);
  45025. wrapper_default = import_websocket.default;
  45026. }
  45027. });
  45028. // ../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-cjs/index.js
  45029. var require_dist_cjs = __commonJS({
  45030. "../node_modules/.pnpm/@smithy+types@4.3.1/node_modules/@smithy/types/dist-cjs/index.js"(exports2, module2) {
  45031. var __defProp3 = Object.defineProperty;
  45032. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  45033. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  45034. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  45035. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  45036. var __export2 = (target, all) => {
  45037. for (var name in all)
  45038. __defProp3(target, name, { get: all[name], enumerable: true });
  45039. };
  45040. var __copyProps3 = (to, from, except, desc) => {
  45041. if (from && typeof from === "object" || typeof from === "function") {
  45042. for (let key of __getOwnPropNames3(from))
  45043. if (!__hasOwnProp3.call(to, key) && key !== except)
  45044. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  45045. }
  45046. return to;
  45047. };
  45048. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  45049. var src_exports = {};
  45050. __export2(src_exports, {
  45051. AlgorithmId: () => AlgorithmId,
  45052. EndpointURLScheme: () => EndpointURLScheme,
  45053. FieldPosition: () => FieldPosition,
  45054. HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation2,
  45055. HttpAuthLocation: () => HttpAuthLocation,
  45056. IniSectionType: () => IniSectionType,
  45057. RequestHandlerProtocol: () => RequestHandlerProtocol,
  45058. SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY4,
  45059. getDefaultClientConfiguration: () => getDefaultClientConfiguration,
  45060. resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig3
  45061. });
  45062. module2.exports = __toCommonJS2(src_exports);
  45063. var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => {
  45064. HttpAuthLocation2["HEADER"] = "header";
  45065. HttpAuthLocation2["QUERY"] = "query";
  45066. return HttpAuthLocation2;
  45067. })(HttpAuthLocation || {});
  45068. var HttpApiKeyAuthLocation2 = /* @__PURE__ */ ((HttpApiKeyAuthLocation22) => {
  45069. HttpApiKeyAuthLocation22["HEADER"] = "header";
  45070. HttpApiKeyAuthLocation22["QUERY"] = "query";
  45071. return HttpApiKeyAuthLocation22;
  45072. })(HttpApiKeyAuthLocation2 || {});
  45073. var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => {
  45074. EndpointURLScheme2["HTTP"] = "http";
  45075. EndpointURLScheme2["HTTPS"] = "https";
  45076. return EndpointURLScheme2;
  45077. })(EndpointURLScheme || {});
  45078. var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => {
  45079. AlgorithmId2["MD5"] = "md5";
  45080. AlgorithmId2["CRC32"] = "crc32";
  45081. AlgorithmId2["CRC32C"] = "crc32c";
  45082. AlgorithmId2["SHA1"] = "sha1";
  45083. AlgorithmId2["SHA256"] = "sha256";
  45084. return AlgorithmId2;
  45085. })(AlgorithmId || {});
  45086. var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
  45087. const checksumAlgorithms = [];
  45088. if (runtimeConfig.sha256 !== void 0) {
  45089. checksumAlgorithms.push({
  45090. algorithmId: () => "sha256",
  45091. checksumConstructor: () => runtimeConfig.sha256
  45092. });
  45093. }
  45094. if (runtimeConfig.md5 != void 0) {
  45095. checksumAlgorithms.push({
  45096. algorithmId: () => "md5",
  45097. checksumConstructor: () => runtimeConfig.md5
  45098. });
  45099. }
  45100. return {
  45101. addChecksumAlgorithm(algo) {
  45102. checksumAlgorithms.push(algo);
  45103. },
  45104. checksumAlgorithms() {
  45105. return checksumAlgorithms;
  45106. }
  45107. };
  45108. }, "getChecksumConfiguration");
  45109. var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => {
  45110. const runtimeConfig = {};
  45111. clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
  45112. runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
  45113. });
  45114. return runtimeConfig;
  45115. }, "resolveChecksumRuntimeConfig");
  45116. var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
  45117. return getChecksumConfiguration(runtimeConfig);
  45118. }, "getDefaultClientConfiguration");
  45119. var resolveDefaultRuntimeConfig3 = /* @__PURE__ */ __name((config) => {
  45120. return resolveChecksumRuntimeConfig(config);
  45121. }, "resolveDefaultRuntimeConfig");
  45122. var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => {
  45123. FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
  45124. FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
  45125. return FieldPosition2;
  45126. })(FieldPosition || {});
  45127. var SMITHY_CONTEXT_KEY4 = "__smithy_context";
  45128. var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => {
  45129. IniSectionType2["PROFILE"] = "profile";
  45130. IniSectionType2["SSO_SESSION"] = "sso-session";
  45131. IniSectionType2["SERVICES"] = "services";
  45132. return IniSectionType2;
  45133. })(IniSectionType || {});
  45134. var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => {
  45135. RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
  45136. RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
  45137. RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
  45138. return RequestHandlerProtocol2;
  45139. })(RequestHandlerProtocol || {});
  45140. }
  45141. });
  45142. // ../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-cjs/index.js
  45143. var require_dist_cjs2 = __commonJS({
  45144. "../node_modules/.pnpm/@smithy+protocol-http@5.1.2/node_modules/@smithy/protocol-http/dist-cjs/index.js"(exports2, module2) {
  45145. var __defProp3 = Object.defineProperty;
  45146. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  45147. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  45148. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  45149. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  45150. var __export2 = (target, all) => {
  45151. for (var name in all)
  45152. __defProp3(target, name, { get: all[name], enumerable: true });
  45153. };
  45154. var __copyProps3 = (to, from, except, desc) => {
  45155. if (from && typeof from === "object" || typeof from === "function") {
  45156. for (let key of __getOwnPropNames3(from))
  45157. if (!__hasOwnProp3.call(to, key) && key !== except)
  45158. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  45159. }
  45160. return to;
  45161. };
  45162. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  45163. var src_exports = {};
  45164. __export2(src_exports, {
  45165. Field: () => Field,
  45166. Fields: () => Fields,
  45167. HttpRequest: () => HttpRequest10,
  45168. HttpResponse: () => HttpResponse4,
  45169. IHttpRequest: () => import_types5.HttpRequest,
  45170. getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration3,
  45171. isValidHostname: () => isValidHostname,
  45172. resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig3
  45173. });
  45174. module2.exports = __toCommonJS2(src_exports);
  45175. var getHttpHandlerExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
  45176. return {
  45177. setHttpHandler(handler) {
  45178. runtimeConfig.httpHandler = handler;
  45179. },
  45180. httpHandler() {
  45181. return runtimeConfig.httpHandler;
  45182. },
  45183. updateHttpClientConfig(key, value) {
  45184. var _a6;
  45185. (_a6 = runtimeConfig.httpHandler) == null ? void 0 : _a6.updateHttpClientConfig(key, value);
  45186. },
  45187. httpHandlerConfigs() {
  45188. return runtimeConfig.httpHandler.httpHandlerConfigs();
  45189. }
  45190. };
  45191. }, "getHttpHandlerExtensionConfiguration");
  45192. var resolveHttpHandlerRuntimeConfig3 = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => {
  45193. return {
  45194. httpHandler: httpHandlerExtensionConfiguration.httpHandler()
  45195. };
  45196. }, "resolveHttpHandlerRuntimeConfig");
  45197. var import_types5 = require_dist_cjs();
  45198. var _a2;
  45199. var Field = (_a2 = class {
  45200. constructor({ name, kind = import_types5.FieldPosition.HEADER, values = [] }) {
  45201. this.name = name;
  45202. this.kind = kind;
  45203. this.values = values;
  45204. }
  45205. /**
  45206. * Appends a value to the field.
  45207. *
  45208. * @param value The value to append.
  45209. */
  45210. add(value) {
  45211. this.values.push(value);
  45212. }
  45213. /**
  45214. * Overwrite existing field values.
  45215. *
  45216. * @param values The new field values.
  45217. */
  45218. set(values) {
  45219. this.values = values;
  45220. }
  45221. /**
  45222. * Remove all matching entries from list.
  45223. *
  45224. * @param value Value to remove.
  45225. */
  45226. remove(value) {
  45227. this.values = this.values.filter((v6) => v6 !== value);
  45228. }
  45229. /**
  45230. * Get comma-delimited string.
  45231. *
  45232. * @returns String representation of {@link Field}.
  45233. */
  45234. toString() {
  45235. return this.values.map((v6) => v6.includes(",") || v6.includes(" ") ? `"${v6}"` : v6).join(", ");
  45236. }
  45237. /**
  45238. * Get string values as a list
  45239. *
  45240. * @returns Values in {@link Field} as a list.
  45241. */
  45242. get() {
  45243. return this.values;
  45244. }
  45245. }, __name(_a2, "Field"), _a2);
  45246. var _a3;
  45247. var Fields = (_a3 = class {
  45248. constructor({ fields = [], encoding = "utf-8" }) {
  45249. this.entries = {};
  45250. fields.forEach(this.setField.bind(this));
  45251. this.encoding = encoding;
  45252. }
  45253. /**
  45254. * Set entry for a {@link Field} name. The `name`
  45255. * attribute will be used to key the collection.
  45256. *
  45257. * @param field The {@link Field} to set.
  45258. */
  45259. setField(field) {
  45260. this.entries[field.name.toLowerCase()] = field;
  45261. }
  45262. /**
  45263. * Retrieve {@link Field} entry by name.
  45264. *
  45265. * @param name The name of the {@link Field} entry
  45266. * to retrieve
  45267. * @returns The {@link Field} if it exists.
  45268. */
  45269. getField(name) {
  45270. return this.entries[name.toLowerCase()];
  45271. }
  45272. /**
  45273. * Delete entry from collection.
  45274. *
  45275. * @param name Name of the entry to delete.
  45276. */
  45277. removeField(name) {
  45278. delete this.entries[name.toLowerCase()];
  45279. }
  45280. /**
  45281. * Helper function for retrieving specific types of fields.
  45282. * Used to grab all headers or all trailers.
  45283. *
  45284. * @param kind {@link FieldPosition} of entries to retrieve.
  45285. * @returns The {@link Field} entries with the specified
  45286. * {@link FieldPosition}.
  45287. */
  45288. getByType(kind) {
  45289. return Object.values(this.entries).filter((field) => field.kind === kind);
  45290. }
  45291. }, __name(_a3, "Fields"), _a3);
  45292. var _a4;
  45293. var HttpRequest10 = (_a4 = class {
  45294. constructor(options) {
  45295. this.method = options.method || "GET";
  45296. this.hostname = options.hostname || "localhost";
  45297. this.port = options.port;
  45298. this.query = options.query || {};
  45299. this.headers = options.headers || {};
  45300. this.body = options.body;
  45301. this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
  45302. this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
  45303. this.username = options.username;
  45304. this.password = options.password;
  45305. this.fragment = options.fragment;
  45306. }
  45307. /**
  45308. * Note: this does not deep-clone the body.
  45309. */
  45310. static clone(request) {
  45311. const cloned = new _a4({
  45312. ...request,
  45313. headers: { ...request.headers }
  45314. });
  45315. if (cloned.query) {
  45316. cloned.query = cloneQuery(cloned.query);
  45317. }
  45318. return cloned;
  45319. }
  45320. /**
  45321. * This method only actually asserts that request is the interface {@link IHttpRequest},
  45322. * and not necessarily this concrete class. Left in place for API stability.
  45323. *
  45324. * Do not call instance methods on the input of this function, and
  45325. * do not assume it has the HttpRequest prototype.
  45326. */
  45327. static isInstance(request) {
  45328. if (!request) {
  45329. return false;
  45330. }
  45331. const req = request;
  45332. return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
  45333. }
  45334. /**
  45335. * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call
  45336. * this method because {@link HttpRequest.isInstance} incorrectly
  45337. * asserts that IHttpRequest (interface) objects are of type HttpRequest (class).
  45338. */
  45339. clone() {
  45340. return _a4.clone(this);
  45341. }
  45342. }, __name(_a4, "HttpRequest"), _a4);
  45343. function cloneQuery(query) {
  45344. return Object.keys(query).reduce((carry, paramName) => {
  45345. const param = query[paramName];
  45346. return {
  45347. ...carry,
  45348. [paramName]: Array.isArray(param) ? [...param] : param
  45349. };
  45350. }, {});
  45351. }
  45352. __name(cloneQuery, "cloneQuery");
  45353. var _a5;
  45354. var HttpResponse4 = (_a5 = class {
  45355. constructor(options) {
  45356. this.statusCode = options.statusCode;
  45357. this.reason = options.reason;
  45358. this.headers = options.headers || {};
  45359. this.body = options.body;
  45360. }
  45361. static isInstance(response) {
  45362. if (!response)
  45363. return false;
  45364. const resp = response;
  45365. return typeof resp.statusCode === "number" && typeof resp.headers === "object";
  45366. }
  45367. }, __name(_a5, "HttpResponse"), _a5);
  45368. function isValidHostname(hostname) {
  45369. const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
  45370. return hostPattern.test(hostname);
  45371. }
  45372. __name(isValidHostname, "isValidHostname");
  45373. }
  45374. });
  45375. // ../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.804.0/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js
  45376. var require_dist_cjs3 = __commonJS({
  45377. "../node_modules/.pnpm/@aws-sdk+middleware-host-header@3.804.0/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js"(exports2, module2) {
  45378. "use strict";
  45379. var __defProp3 = Object.defineProperty;
  45380. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  45381. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  45382. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  45383. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  45384. var __export2 = (target, all) => {
  45385. for (var name in all)
  45386. __defProp3(target, name, { get: all[name], enumerable: true });
  45387. };
  45388. var __copyProps3 = (to, from, except, desc) => {
  45389. if (from && typeof from === "object" || typeof from === "function") {
  45390. for (let key of __getOwnPropNames3(from))
  45391. if (!__hasOwnProp3.call(to, key) && key !== except)
  45392. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  45393. }
  45394. return to;
  45395. };
  45396. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  45397. var index_exports = {};
  45398. __export2(index_exports, {
  45399. getHostHeaderPlugin: () => getHostHeaderPlugin3,
  45400. hostHeaderMiddleware: () => hostHeaderMiddleware,
  45401. hostHeaderMiddlewareOptions: () => hostHeaderMiddlewareOptions,
  45402. resolveHostHeaderConfig: () => resolveHostHeaderConfig3
  45403. });
  45404. module2.exports = __toCommonJS2(index_exports);
  45405. var import_protocol_http15 = require_dist_cjs2();
  45406. function resolveHostHeaderConfig3(input) {
  45407. return input;
  45408. }
  45409. __name(resolveHostHeaderConfig3, "resolveHostHeaderConfig");
  45410. var hostHeaderMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => {
  45411. if (!import_protocol_http15.HttpRequest.isInstance(args.request)) return next(args);
  45412. const { request } = args;
  45413. const { handlerProtocol = "" } = options.requestHandler.metadata || {};
  45414. if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) {
  45415. delete request.headers["host"];
  45416. request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : "");
  45417. } else if (!request.headers["host"]) {
  45418. let host = request.hostname;
  45419. if (request.port != null) host += `:${request.port}`;
  45420. request.headers["host"] = host;
  45421. }
  45422. return next(args);
  45423. }, "hostHeaderMiddleware");
  45424. var hostHeaderMiddlewareOptions = {
  45425. name: "hostHeaderMiddleware",
  45426. step: "build",
  45427. priority: "low",
  45428. tags: ["HOST"],
  45429. override: true
  45430. };
  45431. var getHostHeaderPlugin3 = /* @__PURE__ */ __name((options) => ({
  45432. applyToStack: /* @__PURE__ */ __name((clientStack) => {
  45433. clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions);
  45434. }, "applyToStack")
  45435. }), "getHostHeaderPlugin");
  45436. }
  45437. });
  45438. // ../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js
  45439. var require_dist_cjs4 = __commonJS({
  45440. "../node_modules/.pnpm/@aws-sdk+middleware-logger@3.804.0/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js"(exports2, module2) {
  45441. "use strict";
  45442. var __defProp3 = Object.defineProperty;
  45443. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  45444. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  45445. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  45446. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  45447. var __export2 = (target, all) => {
  45448. for (var name in all)
  45449. __defProp3(target, name, { get: all[name], enumerable: true });
  45450. };
  45451. var __copyProps3 = (to, from, except, desc) => {
  45452. if (from && typeof from === "object" || typeof from === "function") {
  45453. for (let key of __getOwnPropNames3(from))
  45454. if (!__hasOwnProp3.call(to, key) && key !== except)
  45455. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  45456. }
  45457. return to;
  45458. };
  45459. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  45460. var index_exports = {};
  45461. __export2(index_exports, {
  45462. getLoggerPlugin: () => getLoggerPlugin3,
  45463. loggerMiddleware: () => loggerMiddleware,
  45464. loggerMiddlewareOptions: () => loggerMiddlewareOptions
  45465. });
  45466. module2.exports = __toCommonJS2(index_exports);
  45467. var loggerMiddleware = /* @__PURE__ */ __name(() => (next, context) => async (args) => {
  45468. var _a2, _b;
  45469. try {
  45470. const response = await next(args);
  45471. const { clientName, commandName, logger: logger3, dynamoDbDocumentClientOptions = {} } = context;
  45472. const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
  45473. const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
  45474. const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog;
  45475. const { $metadata, ...outputWithoutMetadata } = response.output;
  45476. (_a2 = logger3 == null ? void 0 : logger3.info) == null ? void 0 : _a2.call(logger3, {
  45477. clientName,
  45478. commandName,
  45479. input: inputFilterSensitiveLog(args.input),
  45480. output: outputFilterSensitiveLog(outputWithoutMetadata),
  45481. metadata: $metadata
  45482. });
  45483. return response;
  45484. } catch (error2) {
  45485. const { clientName, commandName, logger: logger3, dynamoDbDocumentClientOptions = {} } = context;
  45486. const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
  45487. const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog;
  45488. (_b = logger3 == null ? void 0 : logger3.error) == null ? void 0 : _b.call(logger3, {
  45489. clientName,
  45490. commandName,
  45491. input: inputFilterSensitiveLog(args.input),
  45492. error: error2,
  45493. metadata: error2.$metadata
  45494. });
  45495. throw error2;
  45496. }
  45497. }, "loggerMiddleware");
  45498. var loggerMiddlewareOptions = {
  45499. name: "loggerMiddleware",
  45500. tags: ["LOGGER"],
  45501. step: "initialize",
  45502. override: true
  45503. };
  45504. var getLoggerPlugin3 = /* @__PURE__ */ __name((options) => ({
  45505. applyToStack: /* @__PURE__ */ __name((clientStack) => {
  45506. clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);
  45507. }, "applyToStack")
  45508. }), "getLoggerPlugin");
  45509. }
  45510. });
  45511. // ../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js
  45512. var require_dist_cjs5 = __commonJS({
  45513. "../node_modules/.pnpm/@aws-sdk+middleware-recursion-detection@3.804.0/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js"(exports2, module2) {
  45514. "use strict";
  45515. var __defProp3 = Object.defineProperty;
  45516. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  45517. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  45518. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  45519. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  45520. var __export2 = (target, all) => {
  45521. for (var name in all)
  45522. __defProp3(target, name, { get: all[name], enumerable: true });
  45523. };
  45524. var __copyProps3 = (to, from, except, desc) => {
  45525. if (from && typeof from === "object" || typeof from === "function") {
  45526. for (let key of __getOwnPropNames3(from))
  45527. if (!__hasOwnProp3.call(to, key) && key !== except)
  45528. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  45529. }
  45530. return to;
  45531. };
  45532. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  45533. var index_exports = {};
  45534. __export2(index_exports, {
  45535. addRecursionDetectionMiddlewareOptions: () => addRecursionDetectionMiddlewareOptions,
  45536. getRecursionDetectionPlugin: () => getRecursionDetectionPlugin3,
  45537. recursionDetectionMiddleware: () => recursionDetectionMiddleware
  45538. });
  45539. module2.exports = __toCommonJS2(index_exports);
  45540. var import_protocol_http15 = require_dist_cjs2();
  45541. var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
  45542. var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
  45543. var ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
  45544. var recursionDetectionMiddleware = /* @__PURE__ */ __name((options) => (next) => async (args) => {
  45545. const { request } = args;
  45546. if (!import_protocol_http15.HttpRequest.isInstance(request) || options.runtime !== "node") {
  45547. return next(args);
  45548. }
  45549. const traceIdHeader = Object.keys(request.headers ?? {}).find((h4) => h4.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME;
  45550. if (request.headers.hasOwnProperty(traceIdHeader)) {
  45551. return next(args);
  45552. }
  45553. const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];
  45554. const traceId = process.env[ENV_TRACE_ID];
  45555. const nonEmptyString = /* @__PURE__ */ __name((str) => typeof str === "string" && str.length > 0, "nonEmptyString");
  45556. if (nonEmptyString(functionName) && nonEmptyString(traceId)) {
  45557. request.headers[TRACE_ID_HEADER_NAME] = traceId;
  45558. }
  45559. return next({
  45560. ...args,
  45561. request
  45562. });
  45563. }, "recursionDetectionMiddleware");
  45564. var addRecursionDetectionMiddlewareOptions = {
  45565. step: "build",
  45566. tags: ["RECURSION_DETECTION"],
  45567. name: "recursionDetectionMiddleware",
  45568. override: true,
  45569. priority: "low"
  45570. };
  45571. var getRecursionDetectionPlugin3 = /* @__PURE__ */ __name((options) => ({
  45572. applyToStack: /* @__PURE__ */ __name((clientStack) => {
  45573. clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions);
  45574. }, "applyToStack")
  45575. }), "getRecursionDetectionPlugin");
  45576. }
  45577. });
  45578. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js
  45579. var import_types, getSmithyContext;
  45580. var init_getSmithyContext = __esm({
  45581. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/getSmithyContext.js"() {
  45582. import_types = __toESM(require_dist_cjs());
  45583. getSmithyContext = (context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {});
  45584. }
  45585. });
  45586. // ../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-cjs/index.js
  45587. var require_dist_cjs6 = __commonJS({
  45588. "../node_modules/.pnpm/@smithy+util-middleware@4.0.4/node_modules/@smithy/util-middleware/dist-cjs/index.js"(exports2, module2) {
  45589. var __defProp3 = Object.defineProperty;
  45590. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  45591. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  45592. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  45593. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  45594. var __export2 = (target, all) => {
  45595. for (var name in all)
  45596. __defProp3(target, name, { get: all[name], enumerable: true });
  45597. };
  45598. var __copyProps3 = (to, from, except, desc) => {
  45599. if (from && typeof from === "object" || typeof from === "function") {
  45600. for (let key of __getOwnPropNames3(from))
  45601. if (!__hasOwnProp3.call(to, key) && key !== except)
  45602. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  45603. }
  45604. return to;
  45605. };
  45606. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  45607. var src_exports = {};
  45608. __export2(src_exports, {
  45609. getSmithyContext: () => getSmithyContext8,
  45610. normalizeProvider: () => normalizeProvider4
  45611. });
  45612. module2.exports = __toCommonJS2(src_exports);
  45613. var import_types5 = require_dist_cjs();
  45614. var getSmithyContext8 = /* @__PURE__ */ __name((context) => context[import_types5.SMITHY_CONTEXT_KEY] || (context[import_types5.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext");
  45615. var normalizeProvider4 = /* @__PURE__ */ __name((input) => {
  45616. if (typeof input === "function")
  45617. return input;
  45618. const promisified = Promise.resolve(input);
  45619. return () => promisified;
  45620. }, "normalizeProvider");
  45621. }
  45622. });
  45623. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js
  45624. var resolveAuthOptions;
  45625. var init_resolveAuthOptions = __esm({
  45626. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js"() {
  45627. resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => {
  45628. if (!authSchemePreference || authSchemePreference.length === 0) {
  45629. return candidateAuthOptions;
  45630. }
  45631. const preferredAuthOptions = [];
  45632. for (const preferredSchemeName of authSchemePreference) {
  45633. for (const candidateAuthOption of candidateAuthOptions) {
  45634. const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1];
  45635. if (candidateAuthSchemeName === preferredSchemeName) {
  45636. preferredAuthOptions.push(candidateAuthOption);
  45637. }
  45638. }
  45639. }
  45640. for (const candidateAuthOption of candidateAuthOptions) {
  45641. if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) {
  45642. preferredAuthOptions.push(candidateAuthOption);
  45643. }
  45644. }
  45645. return preferredAuthOptions;
  45646. };
  45647. }
  45648. });
  45649. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js
  45650. function convertHttpAuthSchemesToMap(httpAuthSchemes) {
  45651. const map2 = /* @__PURE__ */ new Map();
  45652. for (const scheme of httpAuthSchemes) {
  45653. map2.set(scheme.schemeId, scheme);
  45654. }
  45655. return map2;
  45656. }
  45657. var import_types2, import_util_middleware, httpAuthSchemeMiddleware;
  45658. var init_httpAuthSchemeMiddleware = __esm({
  45659. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() {
  45660. import_types2 = __toESM(require_dist_cjs());
  45661. import_util_middleware = __toESM(require_dist_cjs6());
  45662. init_resolveAuthOptions();
  45663. httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => {
  45664. var _a2;
  45665. const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input));
  45666. const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : [];
  45667. const resolvedOptions = resolveAuthOptions(options, authSchemePreference);
  45668. const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes);
  45669. const smithyContext = (0, import_util_middleware.getSmithyContext)(context);
  45670. const failureReasons = [];
  45671. for (const option of resolvedOptions) {
  45672. const scheme = authSchemes.get(option.schemeId);
  45673. if (!scheme) {
  45674. failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);
  45675. continue;
  45676. }
  45677. const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));
  45678. if (!identityProvider) {
  45679. failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);
  45680. continue;
  45681. }
  45682. const { identityProperties = {}, signingProperties = {} } = ((_a2 = option.propertiesExtractor) == null ? void 0 : _a2.call(option, config, context)) || {};
  45683. option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties);
  45684. option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties);
  45685. smithyContext.selectedHttpAuthScheme = {
  45686. httpAuthOption: option,
  45687. identity: await identityProvider(option.identityProperties),
  45688. signer: scheme.signer
  45689. };
  45690. break;
  45691. }
  45692. if (!smithyContext.selectedHttpAuthScheme) {
  45693. throw new Error(failureReasons.join("\n"));
  45694. }
  45695. return next(args);
  45696. };
  45697. }
  45698. });
  45699. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js
  45700. var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin;
  45701. var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({
  45702. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() {
  45703. init_httpAuthSchemeMiddleware();
  45704. httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
  45705. step: "serialize",
  45706. tags: ["HTTP_AUTH_SCHEME"],
  45707. name: "httpAuthSchemeMiddleware",
  45708. override: true,
  45709. relation: "before",
  45710. toMiddleware: "endpointV2Middleware"
  45711. };
  45712. getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
  45713. applyToStack: (clientStack) => {
  45714. clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
  45715. httpAuthSchemeParametersProvider,
  45716. identityProviderConfigProvider
  45717. }), httpAuthSchemeEndpointRuleSetMiddlewareOptions);
  45718. }
  45719. });
  45720. }
  45721. });
  45722. // ../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-cjs/index.js
  45723. var require_dist_cjs7 = __commonJS({
  45724. "../node_modules/.pnpm/@smithy+middleware-serde@4.0.8/node_modules/@smithy/middleware-serde/dist-cjs/index.js"(exports2, module2) {
  45725. var __defProp3 = Object.defineProperty;
  45726. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  45727. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  45728. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  45729. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  45730. var __export2 = (target, all) => {
  45731. for (var name in all)
  45732. __defProp3(target, name, { get: all[name], enumerable: true });
  45733. };
  45734. var __copyProps3 = (to, from, except, desc) => {
  45735. if (from && typeof from === "object" || typeof from === "function") {
  45736. for (let key of __getOwnPropNames3(from))
  45737. if (!__hasOwnProp3.call(to, key) && key !== except)
  45738. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  45739. }
  45740. return to;
  45741. };
  45742. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  45743. var src_exports = {};
  45744. __export2(src_exports, {
  45745. deserializerMiddleware: () => deserializerMiddleware,
  45746. deserializerMiddlewareOption: () => deserializerMiddlewareOption,
  45747. getSerdePlugin: () => getSerdePlugin4,
  45748. serializerMiddleware: () => serializerMiddleware,
  45749. serializerMiddlewareOption: () => serializerMiddlewareOption2
  45750. });
  45751. module2.exports = __toCommonJS2(src_exports);
  45752. var import_protocol_http15 = require_dist_cjs2();
  45753. var deserializerMiddleware = /* @__PURE__ */ __name((options, deserializer) => (next, context) => async (args) => {
  45754. var _a2, _b, _c, _d;
  45755. const { response } = await next(args);
  45756. try {
  45757. const parsed = await deserializer(response, options);
  45758. return {
  45759. response,
  45760. output: parsed
  45761. };
  45762. } catch (error2) {
  45763. Object.defineProperty(error2, "$response", {
  45764. value: response
  45765. });
  45766. if (!("$metadata" in error2)) {
  45767. const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
  45768. try {
  45769. error2.message += "\n " + hint;
  45770. } catch (e4) {
  45771. if (!context.logger || ((_b = (_a2 = context.logger) == null ? void 0 : _a2.constructor) == null ? void 0 : _b.name) === "NoOpLogger") {
  45772. console.warn(hint);
  45773. } else {
  45774. (_d = (_c = context.logger) == null ? void 0 : _c.warn) == null ? void 0 : _d.call(_c, hint);
  45775. }
  45776. }
  45777. if (typeof error2.$responseBodyText !== "undefined") {
  45778. if (error2.$response) {
  45779. error2.$response.body = error2.$responseBodyText;
  45780. }
  45781. }
  45782. try {
  45783. if (import_protocol_http15.HttpResponse.isInstance(response)) {
  45784. const { headers = {} } = response;
  45785. const headerEntries = Object.entries(headers);
  45786. error2.$metadata = {
  45787. httpStatusCode: response.statusCode,
  45788. requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
  45789. extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
  45790. cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
  45791. };
  45792. }
  45793. } catch (e4) {
  45794. }
  45795. }
  45796. throw error2;
  45797. }
  45798. }, "deserializerMiddleware");
  45799. var findHeader = /* @__PURE__ */ __name((pattern, headers) => {
  45800. return (headers.find(([k3]) => {
  45801. return k3.match(pattern);
  45802. }) || [void 0, void 0])[1];
  45803. }, "findHeader");
  45804. var serializerMiddleware = /* @__PURE__ */ __name((options, serializer) => (next, context) => async (args) => {
  45805. var _a2;
  45806. const endpointConfig = options;
  45807. const endpoint = ((_a2 = context.endpointV2) == null ? void 0 : _a2.url) && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint;
  45808. if (!endpoint) {
  45809. throw new Error("No valid endpoint provider available.");
  45810. }
  45811. const request = await serializer(args.input, { ...options, endpoint });
  45812. return next({
  45813. ...args,
  45814. request
  45815. });
  45816. }, "serializerMiddleware");
  45817. var deserializerMiddlewareOption = {
  45818. name: "deserializerMiddleware",
  45819. step: "deserialize",
  45820. tags: ["DESERIALIZER"],
  45821. override: true
  45822. };
  45823. var serializerMiddlewareOption2 = {
  45824. name: "serializerMiddleware",
  45825. step: "serialize",
  45826. tags: ["SERIALIZER"],
  45827. override: true
  45828. };
  45829. function getSerdePlugin4(config, serializer, deserializer) {
  45830. return {
  45831. applyToStack: (commandStack) => {
  45832. commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption);
  45833. commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption2);
  45834. }
  45835. };
  45836. }
  45837. __name(getSerdePlugin4, "getSerdePlugin");
  45838. }
  45839. });
  45840. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js
  45841. var import_middleware_serde, httpAuthSchemeMiddlewareOptions, getHttpAuthSchemePlugin;
  45842. var init_getHttpAuthSchemePlugin = __esm({
  45843. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() {
  45844. import_middleware_serde = __toESM(require_dist_cjs7());
  45845. init_httpAuthSchemeMiddleware();
  45846. httpAuthSchemeMiddlewareOptions = {
  45847. step: "serialize",
  45848. tags: ["HTTP_AUTH_SCHEME"],
  45849. name: "httpAuthSchemeMiddleware",
  45850. override: true,
  45851. relation: "before",
  45852. toMiddleware: import_middleware_serde.serializerMiddlewareOption.name
  45853. };
  45854. getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
  45855. applyToStack: (clientStack) => {
  45856. clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
  45857. httpAuthSchemeParametersProvider,
  45858. identityProviderConfigProvider
  45859. }), httpAuthSchemeMiddlewareOptions);
  45860. }
  45861. });
  45862. }
  45863. });
  45864. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js
  45865. var init_middleware_http_auth_scheme = __esm({
  45866. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() {
  45867. init_httpAuthSchemeMiddleware();
  45868. init_getHttpAuthSchemeEndpointRuleSetPlugin();
  45869. init_getHttpAuthSchemePlugin();
  45870. }
  45871. });
  45872. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js
  45873. var import_protocol_http, import_types3, import_util_middleware2, defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware;
  45874. var init_httpSigningMiddleware = __esm({
  45875. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() {
  45876. import_protocol_http = __toESM(require_dist_cjs2());
  45877. import_types3 = __toESM(require_dist_cjs());
  45878. import_util_middleware2 = __toESM(require_dist_cjs6());
  45879. defaultErrorHandler = (signingProperties) => (error2) => {
  45880. throw error2;
  45881. };
  45882. defaultSuccessHandler = (httpResponse, signingProperties) => {
  45883. };
  45884. httpSigningMiddleware = (config) => (next, context) => async (args) => {
  45885. if (!import_protocol_http.HttpRequest.isInstance(args.request)) {
  45886. return next(args);
  45887. }
  45888. const smithyContext = (0, import_util_middleware2.getSmithyContext)(context);
  45889. const scheme = smithyContext.selectedHttpAuthScheme;
  45890. if (!scheme) {
  45891. throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
  45892. }
  45893. const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme;
  45894. const output = await next({
  45895. ...args,
  45896. request: await signer.sign(args.request, identity, signingProperties)
  45897. }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));
  45898. (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties);
  45899. return output;
  45900. };
  45901. }
  45902. });
  45903. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js
  45904. var httpSigningMiddlewareOptions, getHttpSigningPlugin;
  45905. var init_getHttpSigningMiddleware = __esm({
  45906. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() {
  45907. init_httpSigningMiddleware();
  45908. httpSigningMiddlewareOptions = {
  45909. step: "finalizeRequest",
  45910. tags: ["HTTP_SIGNING"],
  45911. name: "httpSigningMiddleware",
  45912. aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"],
  45913. override: true,
  45914. relation: "after",
  45915. toMiddleware: "retryMiddleware"
  45916. };
  45917. getHttpSigningPlugin = (config) => ({
  45918. applyToStack: (clientStack) => {
  45919. clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions);
  45920. }
  45921. });
  45922. }
  45923. });
  45924. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js
  45925. var init_middleware_http_signing = __esm({
  45926. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() {
  45927. init_httpSigningMiddleware();
  45928. init_getHttpSigningMiddleware();
  45929. }
  45930. });
  45931. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js
  45932. var normalizeProvider;
  45933. var init_normalizeProvider = __esm({
  45934. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/normalizeProvider.js"() {
  45935. normalizeProvider = (input) => {
  45936. if (typeof input === "function")
  45937. return input;
  45938. const promisified = Promise.resolve(input);
  45939. return () => promisified;
  45940. };
  45941. }
  45942. });
  45943. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js
  45944. function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) {
  45945. return async function* paginateOperation(config, input, ...additionalArguments) {
  45946. const _input = input;
  45947. let token = config.startingToken ?? _input[inputTokenName];
  45948. let hasNext = true;
  45949. let page;
  45950. while (hasNext) {
  45951. _input[inputTokenName] = token;
  45952. if (pageSizeTokenName) {
  45953. _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize;
  45954. }
  45955. if (config.client instanceof ClientCtor) {
  45956. page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments);
  45957. } else {
  45958. throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`);
  45959. }
  45960. yield page;
  45961. const prevToken = token;
  45962. token = get(page, outputTokenName);
  45963. hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken));
  45964. }
  45965. return void 0;
  45966. };
  45967. }
  45968. var makePagedClientRequest, get;
  45969. var init_createPaginator = __esm({
  45970. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() {
  45971. makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_3) => _3, ...args) => {
  45972. let command = new CommandCtor(input);
  45973. command = withCommand(command) ?? command;
  45974. return await client.send(command, ...args);
  45975. };
  45976. get = (fromObject, path4) => {
  45977. let cursor = fromObject;
  45978. const pathComponents = path4.split(".");
  45979. for (const step of pathComponents) {
  45980. if (!cursor || typeof cursor !== "object") {
  45981. return void 0;
  45982. }
  45983. cursor = cursor[step];
  45984. }
  45985. return cursor;
  45986. };
  45987. }
  45988. });
  45989. // ../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
  45990. var require_dist_cjs8 = __commonJS({
  45991. "../node_modules/.pnpm/@smithy+is-array-buffer@4.0.0/node_modules/@smithy/is-array-buffer/dist-cjs/index.js"(exports2, module2) {
  45992. var __defProp3 = Object.defineProperty;
  45993. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  45994. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  45995. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  45996. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  45997. var __export2 = (target, all) => {
  45998. for (var name in all)
  45999. __defProp3(target, name, { get: all[name], enumerable: true });
  46000. };
  46001. var __copyProps3 = (to, from, except, desc) => {
  46002. if (from && typeof from === "object" || typeof from === "function") {
  46003. for (let key of __getOwnPropNames3(from))
  46004. if (!__hasOwnProp3.call(to, key) && key !== except)
  46005. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  46006. }
  46007. return to;
  46008. };
  46009. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  46010. var src_exports = {};
  46011. __export2(src_exports, {
  46012. isArrayBuffer: () => isArrayBuffer
  46013. });
  46014. module2.exports = __toCommonJS2(src_exports);
  46015. var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer");
  46016. }
  46017. });
  46018. // ../node_modules/.pnpm/@smithy+util-buffer-from@4.0.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
  46019. var require_dist_cjs9 = __commonJS({
  46020. "../node_modules/.pnpm/@smithy+util-buffer-from@4.0.0/node_modules/@smithy/util-buffer-from/dist-cjs/index.js"(exports2, module2) {
  46021. var __defProp3 = Object.defineProperty;
  46022. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  46023. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  46024. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  46025. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  46026. var __export2 = (target, all) => {
  46027. for (var name in all)
  46028. __defProp3(target, name, { get: all[name], enumerable: true });
  46029. };
  46030. var __copyProps3 = (to, from, except, desc) => {
  46031. if (from && typeof from === "object" || typeof from === "function") {
  46032. for (let key of __getOwnPropNames3(from))
  46033. if (!__hasOwnProp3.call(to, key) && key !== except)
  46034. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  46035. }
  46036. return to;
  46037. };
  46038. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  46039. var src_exports = {};
  46040. __export2(src_exports, {
  46041. fromArrayBuffer: () => fromArrayBuffer,
  46042. fromString: () => fromString
  46043. });
  46044. module2.exports = __toCommonJS2(src_exports);
  46045. var import_is_array_buffer = require_dist_cjs8();
  46046. var import_buffer2 = require("buffer");
  46047. var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => {
  46048. if (!(0, import_is_array_buffer.isArrayBuffer)(input)) {
  46049. throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
  46050. }
  46051. return import_buffer2.Buffer.from(input, offset, length);
  46052. }, "fromArrayBuffer");
  46053. var fromString = /* @__PURE__ */ __name((input, encoding) => {
  46054. if (typeof input !== "string") {
  46055. throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
  46056. }
  46057. return encoding ? import_buffer2.Buffer.from(input, encoding) : import_buffer2.Buffer.from(input);
  46058. }, "fromString");
  46059. }
  46060. });
  46061. // ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js
  46062. var require_fromBase64 = __commonJS({
  46063. "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js"(exports2) {
  46064. "use strict";
  46065. Object.defineProperty(exports2, "__esModule", { value: true });
  46066. exports2.fromBase64 = void 0;
  46067. var util_buffer_from_1 = require_dist_cjs9();
  46068. var BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
  46069. var fromBase645 = (input) => {
  46070. if (input.length * 3 % 4 !== 0) {
  46071. throw new TypeError(`Incorrect padding on base64 string.`);
  46072. }
  46073. if (!BASE64_REGEX.exec(input)) {
  46074. throw new TypeError(`Invalid base64 string.`);
  46075. }
  46076. const buffer = (0, util_buffer_from_1.fromString)(input, "base64");
  46077. return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  46078. };
  46079. exports2.fromBase64 = fromBase645;
  46080. }
  46081. });
  46082. // ../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-cjs/index.js
  46083. var require_dist_cjs10 = __commonJS({
  46084. "../node_modules/.pnpm/@smithy+util-utf8@4.0.0/node_modules/@smithy/util-utf8/dist-cjs/index.js"(exports2, module2) {
  46085. var __defProp3 = Object.defineProperty;
  46086. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  46087. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  46088. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  46089. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  46090. var __export2 = (target, all) => {
  46091. for (var name in all)
  46092. __defProp3(target, name, { get: all[name], enumerable: true });
  46093. };
  46094. var __copyProps3 = (to, from, except, desc) => {
  46095. if (from && typeof from === "object" || typeof from === "function") {
  46096. for (let key of __getOwnPropNames3(from))
  46097. if (!__hasOwnProp3.call(to, key) && key !== except)
  46098. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  46099. }
  46100. return to;
  46101. };
  46102. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  46103. var src_exports = {};
  46104. __export2(src_exports, {
  46105. fromUtf8: () => fromUtf84,
  46106. toUint8Array: () => toUint8Array,
  46107. toUtf8: () => toUtf85
  46108. });
  46109. module2.exports = __toCommonJS2(src_exports);
  46110. var import_util_buffer_from = require_dist_cjs9();
  46111. var fromUtf84 = /* @__PURE__ */ __name((input) => {
  46112. const buf = (0, import_util_buffer_from.fromString)(input, "utf8");
  46113. return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
  46114. }, "fromUtf8");
  46115. var toUint8Array = /* @__PURE__ */ __name((data) => {
  46116. if (typeof data === "string") {
  46117. return fromUtf84(data);
  46118. }
  46119. if (ArrayBuffer.isView(data)) {
  46120. return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);
  46121. }
  46122. return new Uint8Array(data);
  46123. }, "toUint8Array");
  46124. var toUtf85 = /* @__PURE__ */ __name((input) => {
  46125. if (typeof input === "string") {
  46126. return input;
  46127. }
  46128. if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
  46129. throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
  46130. }
  46131. return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8");
  46132. }, "toUtf8");
  46133. }
  46134. });
  46135. // ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/toBase64.js
  46136. var require_toBase64 = __commonJS({
  46137. "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/toBase64.js"(exports2) {
  46138. "use strict";
  46139. Object.defineProperty(exports2, "__esModule", { value: true });
  46140. exports2.toBase64 = void 0;
  46141. var util_buffer_from_1 = require_dist_cjs9();
  46142. var util_utf8_1 = require_dist_cjs10();
  46143. var toBase645 = (_input) => {
  46144. let input;
  46145. if (typeof _input === "string") {
  46146. input = (0, util_utf8_1.fromUtf8)(_input);
  46147. } else {
  46148. input = _input;
  46149. }
  46150. if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
  46151. throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
  46152. }
  46153. return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64");
  46154. };
  46155. exports2.toBase64 = toBase645;
  46156. }
  46157. });
  46158. // ../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/index.js
  46159. var require_dist_cjs11 = __commonJS({
  46160. "../node_modules/.pnpm/@smithy+util-base64@4.0.0/node_modules/@smithy/util-base64/dist-cjs/index.js"(exports2, module2) {
  46161. var __defProp3 = Object.defineProperty;
  46162. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  46163. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  46164. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  46165. var __copyProps3 = (to, from, except, desc) => {
  46166. if (from && typeof from === "object" || typeof from === "function") {
  46167. for (let key of __getOwnPropNames3(from))
  46168. if (!__hasOwnProp3.call(to, key) && key !== except)
  46169. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  46170. }
  46171. return to;
  46172. };
  46173. var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
  46174. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  46175. var src_exports = {};
  46176. module2.exports = __toCommonJS2(src_exports);
  46177. __reExport(src_exports, require_fromBase64(), module2.exports);
  46178. __reExport(src_exports, require_toBase64(), module2.exports);
  46179. }
  46180. });
  46181. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js
  46182. var require_ChecksumStream = __commonJS({
  46183. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js"(exports2) {
  46184. "use strict";
  46185. Object.defineProperty(exports2, "__esModule", { value: true });
  46186. exports2.ChecksumStream = void 0;
  46187. var util_base64_1 = require_dist_cjs11();
  46188. var stream_1 = require("stream");
  46189. var ChecksumStream2 = class extends stream_1.Duplex {
  46190. constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) {
  46191. var _a2, _b;
  46192. super();
  46193. if (typeof source.pipe === "function") {
  46194. this.source = source;
  46195. } else {
  46196. throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a2 = source === null || source === void 0 ? void 0 : source.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`);
  46197. }
  46198. this.base64Encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64;
  46199. this.expectedChecksum = expectedChecksum;
  46200. this.checksum = checksum;
  46201. this.checksumSourceLocation = checksumSourceLocation;
  46202. this.source.pipe(this);
  46203. }
  46204. _read(size) {
  46205. }
  46206. _write(chunk, encoding, callback) {
  46207. try {
  46208. this.checksum.update(chunk);
  46209. this.push(chunk);
  46210. } catch (e4) {
  46211. return callback(e4);
  46212. }
  46213. return callback();
  46214. }
  46215. async _final(callback) {
  46216. try {
  46217. const digest = await this.checksum.digest();
  46218. const received = this.base64Encoder(digest);
  46219. if (this.expectedChecksum !== received) {
  46220. return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}" in response header "${this.checksumSourceLocation}".`));
  46221. }
  46222. } catch (e4) {
  46223. return callback(e4);
  46224. }
  46225. this.push(null);
  46226. return callback();
  46227. }
  46228. };
  46229. exports2.ChecksumStream = ChecksumStream2;
  46230. }
  46231. });
  46232. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js
  46233. var require_stream_type_check = __commonJS({
  46234. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js"(exports2) {
  46235. "use strict";
  46236. Object.defineProperty(exports2, "__esModule", { value: true });
  46237. exports2.isBlob = exports2.isReadableStream = void 0;
  46238. var isReadableStream2 = (stream) => {
  46239. var _a2;
  46240. return typeof ReadableStream === "function" && (((_a2 = stream === null || stream === void 0 ? void 0 : stream.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) === ReadableStream.name || stream instanceof ReadableStream);
  46241. };
  46242. exports2.isReadableStream = isReadableStream2;
  46243. var isBlob3 = (blob) => {
  46244. var _a2;
  46245. return typeof Blob === "function" && (((_a2 = blob === null || blob === void 0 ? void 0 : blob.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) === Blob.name || blob instanceof Blob);
  46246. };
  46247. exports2.isBlob = isBlob3;
  46248. }
  46249. });
  46250. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js
  46251. var require_ChecksumStream_browser = __commonJS({
  46252. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js"(exports2) {
  46253. "use strict";
  46254. Object.defineProperty(exports2, "__esModule", { value: true });
  46255. exports2.ChecksumStream = void 0;
  46256. var ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function() {
  46257. };
  46258. var ChecksumStream2 = class extends ReadableStreamRef {
  46259. };
  46260. exports2.ChecksumStream = ChecksumStream2;
  46261. }
  46262. });
  46263. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js
  46264. var require_createChecksumStream_browser = __commonJS({
  46265. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js"(exports2) {
  46266. "use strict";
  46267. Object.defineProperty(exports2, "__esModule", { value: true });
  46268. exports2.createChecksumStream = void 0;
  46269. var util_base64_1 = require_dist_cjs11();
  46270. var stream_type_check_1 = require_stream_type_check();
  46271. var ChecksumStream_browser_1 = require_ChecksumStream_browser();
  46272. var createChecksumStream2 = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder }) => {
  46273. var _a2, _b;
  46274. if (!(0, stream_type_check_1.isReadableStream)(source)) {
  46275. throw new Error(`@smithy/util-stream: unsupported source type ${(_b = (_a2 = source === null || source === void 0 ? void 0 : source.constructor) === null || _a2 === void 0 ? void 0 : _a2.name) !== null && _b !== void 0 ? _b : source} in ChecksumStream.`);
  46276. }
  46277. const encoder = base64Encoder !== null && base64Encoder !== void 0 ? base64Encoder : util_base64_1.toBase64;
  46278. if (typeof TransformStream !== "function") {
  46279. throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");
  46280. }
  46281. const transform = new TransformStream({
  46282. start() {
  46283. },
  46284. async transform(chunk, controller) {
  46285. checksum.update(chunk);
  46286. controller.enqueue(chunk);
  46287. },
  46288. async flush(controller) {
  46289. const digest = await checksum.digest();
  46290. const received = encoder(digest);
  46291. if (expectedChecksum !== received) {
  46292. const error2 = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}" in response header "${checksumSourceLocation}".`);
  46293. controller.error(error2);
  46294. } else {
  46295. controller.terminate();
  46296. }
  46297. }
  46298. });
  46299. source.pipeThrough(transform);
  46300. const readable = transform.readable;
  46301. Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype);
  46302. return readable;
  46303. };
  46304. exports2.createChecksumStream = createChecksumStream2;
  46305. }
  46306. });
  46307. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js
  46308. var require_createChecksumStream = __commonJS({
  46309. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js"(exports2) {
  46310. "use strict";
  46311. Object.defineProperty(exports2, "__esModule", { value: true });
  46312. exports2.createChecksumStream = createChecksumStream2;
  46313. var stream_type_check_1 = require_stream_type_check();
  46314. var ChecksumStream_1 = require_ChecksumStream();
  46315. var createChecksumStream_browser_1 = require_createChecksumStream_browser();
  46316. function createChecksumStream2(init2) {
  46317. if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init2.source)) {
  46318. return (0, createChecksumStream_browser_1.createChecksumStream)(init2);
  46319. }
  46320. return new ChecksumStream_1.ChecksumStream(init2);
  46321. }
  46322. }
  46323. });
  46324. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js
  46325. var require_ByteArrayCollector = __commonJS({
  46326. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js"(exports2) {
  46327. "use strict";
  46328. Object.defineProperty(exports2, "__esModule", { value: true });
  46329. exports2.ByteArrayCollector = void 0;
  46330. var ByteArrayCollector = class {
  46331. constructor(allocByteArray) {
  46332. this.allocByteArray = allocByteArray;
  46333. this.byteLength = 0;
  46334. this.byteArrays = [];
  46335. }
  46336. push(byteArray) {
  46337. this.byteArrays.push(byteArray);
  46338. this.byteLength += byteArray.byteLength;
  46339. }
  46340. flush() {
  46341. if (this.byteArrays.length === 1) {
  46342. const bytes = this.byteArrays[0];
  46343. this.reset();
  46344. return bytes;
  46345. }
  46346. const aggregation = this.allocByteArray(this.byteLength);
  46347. let cursor = 0;
  46348. for (let i4 = 0; i4 < this.byteArrays.length; ++i4) {
  46349. const bytes = this.byteArrays[i4];
  46350. aggregation.set(bytes, cursor);
  46351. cursor += bytes.byteLength;
  46352. }
  46353. this.reset();
  46354. return aggregation;
  46355. }
  46356. reset() {
  46357. this.byteArrays = [];
  46358. this.byteLength = 0;
  46359. }
  46360. };
  46361. exports2.ByteArrayCollector = ByteArrayCollector;
  46362. }
  46363. });
  46364. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js
  46365. var require_createBufferedReadableStream = __commonJS({
  46366. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js"(exports2) {
  46367. "use strict";
  46368. Object.defineProperty(exports2, "__esModule", { value: true });
  46369. exports2.createBufferedReadable = void 0;
  46370. exports2.createBufferedReadableStream = createBufferedReadableStream;
  46371. exports2.merge = merge;
  46372. exports2.flush = flush;
  46373. exports2.sizeOf = sizeOf;
  46374. exports2.modeOf = modeOf;
  46375. var ByteArrayCollector_1 = require_ByteArrayCollector();
  46376. function createBufferedReadableStream(upstream, size, logger3) {
  46377. const reader = upstream.getReader();
  46378. let streamBufferingLoggedWarning = false;
  46379. let bytesSeen = 0;
  46380. const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size2) => new Uint8Array(size2))];
  46381. let mode = -1;
  46382. const pull2 = async (controller) => {
  46383. const { value, done } = await reader.read();
  46384. const chunk = value;
  46385. if (done) {
  46386. if (mode !== -1) {
  46387. const remainder = flush(buffers, mode);
  46388. if (sizeOf(remainder) > 0) {
  46389. controller.enqueue(remainder);
  46390. }
  46391. }
  46392. controller.close();
  46393. } else {
  46394. const chunkMode = modeOf(chunk, false);
  46395. if (mode !== chunkMode) {
  46396. if (mode >= 0) {
  46397. controller.enqueue(flush(buffers, mode));
  46398. }
  46399. mode = chunkMode;
  46400. }
  46401. if (mode === -1) {
  46402. controller.enqueue(chunk);
  46403. return;
  46404. }
  46405. const chunkSize = sizeOf(chunk);
  46406. bytesSeen += chunkSize;
  46407. const bufferSize = sizeOf(buffers[mode]);
  46408. if (chunkSize >= size && bufferSize === 0) {
  46409. controller.enqueue(chunk);
  46410. } else {
  46411. const newSize = merge(buffers, mode, chunk);
  46412. if (!streamBufferingLoggedWarning && bytesSeen > size * 2) {
  46413. streamBufferingLoggedWarning = true;
  46414. logger3 === null || logger3 === void 0 ? void 0 : logger3.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);
  46415. }
  46416. if (newSize >= size) {
  46417. controller.enqueue(flush(buffers, mode));
  46418. } else {
  46419. await pull2(controller);
  46420. }
  46421. }
  46422. }
  46423. };
  46424. return new ReadableStream({
  46425. pull: pull2
  46426. });
  46427. }
  46428. exports2.createBufferedReadable = createBufferedReadableStream;
  46429. function merge(buffers, mode, chunk) {
  46430. switch (mode) {
  46431. case 0:
  46432. buffers[0] += chunk;
  46433. return sizeOf(buffers[0]);
  46434. case 1:
  46435. case 2:
  46436. buffers[mode].push(chunk);
  46437. return sizeOf(buffers[mode]);
  46438. }
  46439. }
  46440. function flush(buffers, mode) {
  46441. switch (mode) {
  46442. case 0:
  46443. const s4 = buffers[0];
  46444. buffers[0] = "";
  46445. return s4;
  46446. case 1:
  46447. case 2:
  46448. return buffers[mode].flush();
  46449. }
  46450. throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`);
  46451. }
  46452. function sizeOf(chunk) {
  46453. var _a2, _b;
  46454. return (_b = (_a2 = chunk === null || chunk === void 0 ? void 0 : chunk.byteLength) !== null && _a2 !== void 0 ? _a2 : chunk === null || chunk === void 0 ? void 0 : chunk.length) !== null && _b !== void 0 ? _b : 0;
  46455. }
  46456. function modeOf(chunk, allowBuffer = true) {
  46457. if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) {
  46458. return 2;
  46459. }
  46460. if (chunk instanceof Uint8Array) {
  46461. return 1;
  46462. }
  46463. if (typeof chunk === "string") {
  46464. return 0;
  46465. }
  46466. return -1;
  46467. }
  46468. }
  46469. });
  46470. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js
  46471. var require_createBufferedReadable = __commonJS({
  46472. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js"(exports2) {
  46473. "use strict";
  46474. Object.defineProperty(exports2, "__esModule", { value: true });
  46475. exports2.createBufferedReadable = createBufferedReadable2;
  46476. var node_stream_1 = require("node:stream");
  46477. var ByteArrayCollector_1 = require_ByteArrayCollector();
  46478. var createBufferedReadableStream_1 = require_createBufferedReadableStream();
  46479. var stream_type_check_1 = require_stream_type_check();
  46480. function createBufferedReadable2(upstream, size, logger3) {
  46481. if ((0, stream_type_check_1.isReadableStream)(upstream)) {
  46482. return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger3);
  46483. }
  46484. const downstream = new node_stream_1.Readable({ read() {
  46485. } });
  46486. let streamBufferingLoggedWarning = false;
  46487. let bytesSeen = 0;
  46488. const buffers = [
  46489. "",
  46490. new ByteArrayCollector_1.ByteArrayCollector((size2) => new Uint8Array(size2)),
  46491. new ByteArrayCollector_1.ByteArrayCollector((size2) => Buffer.from(new Uint8Array(size2)))
  46492. ];
  46493. let mode = -1;
  46494. upstream.on("data", (chunk) => {
  46495. const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true);
  46496. if (mode !== chunkMode) {
  46497. if (mode >= 0) {
  46498. downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode));
  46499. }
  46500. mode = chunkMode;
  46501. }
  46502. if (mode === -1) {
  46503. downstream.push(chunk);
  46504. return;
  46505. }
  46506. const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk);
  46507. bytesSeen += chunkSize;
  46508. const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]);
  46509. if (chunkSize >= size && bufferSize === 0) {
  46510. downstream.push(chunk);
  46511. } else {
  46512. const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk);
  46513. if (!streamBufferingLoggedWarning && bytesSeen > size * 2) {
  46514. streamBufferingLoggedWarning = true;
  46515. logger3 === null || logger3 === void 0 ? void 0 : logger3.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`);
  46516. }
  46517. if (newSize >= size) {
  46518. downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode));
  46519. }
  46520. }
  46521. });
  46522. upstream.on("end", () => {
  46523. if (mode !== -1) {
  46524. const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode);
  46525. if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) {
  46526. downstream.push(remainder);
  46527. }
  46528. }
  46529. downstream.push(null);
  46530. });
  46531. return downstream;
  46532. }
  46533. }
  46534. });
  46535. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js
  46536. var require_getAwsChunkedEncodingStream = __commonJS({
  46537. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js"(exports2) {
  46538. "use strict";
  46539. Object.defineProperty(exports2, "__esModule", { value: true });
  46540. exports2.getAwsChunkedEncodingStream = void 0;
  46541. var stream_1 = require("stream");
  46542. var getAwsChunkedEncodingStream2 = (readableStream, options) => {
  46543. const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options;
  46544. const checksumRequired = base64Encoder !== void 0 && checksumAlgorithmFn !== void 0 && checksumLocationName !== void 0 && streamHasher !== void 0;
  46545. const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : void 0;
  46546. const awsChunkedEncodingStream = new stream_1.Readable({ read: () => {
  46547. } });
  46548. readableStream.on("data", (data) => {
  46549. const length = bodyLengthChecker(data) || 0;
  46550. awsChunkedEncodingStream.push(`${length.toString(16)}\r
  46551. `);
  46552. awsChunkedEncodingStream.push(data);
  46553. awsChunkedEncodingStream.push("\r\n");
  46554. });
  46555. readableStream.on("end", async () => {
  46556. awsChunkedEncodingStream.push(`0\r
  46557. `);
  46558. if (checksumRequired) {
  46559. const checksum = base64Encoder(await digest);
  46560. awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r
  46561. `);
  46562. awsChunkedEncodingStream.push(`\r
  46563. `);
  46564. }
  46565. awsChunkedEncodingStream.push(null);
  46566. });
  46567. return awsChunkedEncodingStream;
  46568. };
  46569. exports2.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream2;
  46570. }
  46571. });
  46572. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js
  46573. var require_headStream_browser = __commonJS({
  46574. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js"(exports2) {
  46575. "use strict";
  46576. Object.defineProperty(exports2, "__esModule", { value: true });
  46577. exports2.headStream = headStream2;
  46578. async function headStream2(stream, bytes) {
  46579. var _a2;
  46580. let byteLengthCounter = 0;
  46581. const chunks = [];
  46582. const reader = stream.getReader();
  46583. let isDone = false;
  46584. while (!isDone) {
  46585. const { done, value } = await reader.read();
  46586. if (value) {
  46587. chunks.push(value);
  46588. byteLengthCounter += (_a2 = value === null || value === void 0 ? void 0 : value.byteLength) !== null && _a2 !== void 0 ? _a2 : 0;
  46589. }
  46590. if (byteLengthCounter >= bytes) {
  46591. break;
  46592. }
  46593. isDone = done;
  46594. }
  46595. reader.releaseLock();
  46596. const collected = new Uint8Array(Math.min(bytes, byteLengthCounter));
  46597. let offset = 0;
  46598. for (const chunk of chunks) {
  46599. if (chunk.byteLength > collected.byteLength - offset) {
  46600. collected.set(chunk.subarray(0, collected.byteLength - offset), offset);
  46601. break;
  46602. } else {
  46603. collected.set(chunk, offset);
  46604. }
  46605. offset += chunk.length;
  46606. }
  46607. return collected;
  46608. }
  46609. }
  46610. });
  46611. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.js
  46612. var require_headStream = __commonJS({
  46613. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/headStream.js"(exports2) {
  46614. "use strict";
  46615. Object.defineProperty(exports2, "__esModule", { value: true });
  46616. exports2.headStream = void 0;
  46617. var stream_1 = require("stream");
  46618. var headStream_browser_1 = require_headStream_browser();
  46619. var stream_type_check_1 = require_stream_type_check();
  46620. var headStream2 = (stream, bytes) => {
  46621. if ((0, stream_type_check_1.isReadableStream)(stream)) {
  46622. return (0, headStream_browser_1.headStream)(stream, bytes);
  46623. }
  46624. return new Promise((resolve2, reject) => {
  46625. const collector = new Collector();
  46626. collector.limit = bytes;
  46627. stream.pipe(collector);
  46628. stream.on("error", (err2) => {
  46629. collector.end();
  46630. reject(err2);
  46631. });
  46632. collector.on("error", reject);
  46633. collector.on("finish", function() {
  46634. const bytes2 = new Uint8Array(Buffer.concat(this.buffers));
  46635. resolve2(bytes2);
  46636. });
  46637. });
  46638. };
  46639. exports2.headStream = headStream2;
  46640. var Collector = class extends stream_1.Writable {
  46641. constructor() {
  46642. super(...arguments);
  46643. this.buffers = [];
  46644. this.limit = Infinity;
  46645. this.bytesBuffered = 0;
  46646. }
  46647. _write(chunk, encoding, callback) {
  46648. var _a2;
  46649. this.buffers.push(chunk);
  46650. this.bytesBuffered += (_a2 = chunk.byteLength) !== null && _a2 !== void 0 ? _a2 : 0;
  46651. if (this.bytesBuffered >= this.limit) {
  46652. const excess = this.bytesBuffered - this.limit;
  46653. const tailBuffer = this.buffers[this.buffers.length - 1];
  46654. this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess);
  46655. this.emit("finish");
  46656. }
  46657. callback();
  46658. }
  46659. };
  46660. }
  46661. });
  46662. // ../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-cjs/index.js
  46663. var require_dist_cjs12 = __commonJS({
  46664. "../node_modules/.pnpm/@smithy+util-uri-escape@4.0.0/node_modules/@smithy/util-uri-escape/dist-cjs/index.js"(exports2, module2) {
  46665. var __defProp3 = Object.defineProperty;
  46666. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  46667. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  46668. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  46669. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  46670. var __export2 = (target, all) => {
  46671. for (var name in all)
  46672. __defProp3(target, name, { get: all[name], enumerable: true });
  46673. };
  46674. var __copyProps3 = (to, from, except, desc) => {
  46675. if (from && typeof from === "object" || typeof from === "function") {
  46676. for (let key of __getOwnPropNames3(from))
  46677. if (!__hasOwnProp3.call(to, key) && key !== except)
  46678. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  46679. }
  46680. return to;
  46681. };
  46682. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  46683. var src_exports = {};
  46684. __export2(src_exports, {
  46685. escapeUri: () => escapeUri,
  46686. escapeUriPath: () => escapeUriPath
  46687. });
  46688. module2.exports = __toCommonJS2(src_exports);
  46689. var escapeUri = /* @__PURE__ */ __name((uri) => (
  46690. // AWS percent-encodes some extra non-standard characters in a URI
  46691. encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode)
  46692. ), "escapeUri");
  46693. var hexEncode = /* @__PURE__ */ __name((c3) => `%${c3.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode");
  46694. var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath");
  46695. }
  46696. });
  46697. // ../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-cjs/index.js
  46698. var require_dist_cjs13 = __commonJS({
  46699. "../node_modules/.pnpm/@smithy+querystring-builder@4.0.4/node_modules/@smithy/querystring-builder/dist-cjs/index.js"(exports2, module2) {
  46700. var __defProp3 = Object.defineProperty;
  46701. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  46702. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  46703. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  46704. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  46705. var __export2 = (target, all) => {
  46706. for (var name in all)
  46707. __defProp3(target, name, { get: all[name], enumerable: true });
  46708. };
  46709. var __copyProps3 = (to, from, except, desc) => {
  46710. if (from && typeof from === "object" || typeof from === "function") {
  46711. for (let key of __getOwnPropNames3(from))
  46712. if (!__hasOwnProp3.call(to, key) && key !== except)
  46713. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  46714. }
  46715. return to;
  46716. };
  46717. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  46718. var src_exports = {};
  46719. __export2(src_exports, {
  46720. buildQueryString: () => buildQueryString
  46721. });
  46722. module2.exports = __toCommonJS2(src_exports);
  46723. var import_util_uri_escape = require_dist_cjs12();
  46724. function buildQueryString(query) {
  46725. const parts = [];
  46726. for (let key of Object.keys(query).sort()) {
  46727. const value = query[key];
  46728. key = (0, import_util_uri_escape.escapeUri)(key);
  46729. if (Array.isArray(value)) {
  46730. for (let i4 = 0, iLen = value.length; i4 < iLen; i4++) {
  46731. parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i4])}`);
  46732. }
  46733. } else {
  46734. let qsEntry = key;
  46735. if (value || typeof value === "string") {
  46736. qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`;
  46737. }
  46738. parts.push(qsEntry);
  46739. }
  46740. }
  46741. return parts.join("&");
  46742. }
  46743. __name(buildQueryString, "buildQueryString");
  46744. }
  46745. });
  46746. // ../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-cjs/index.js
  46747. var require_dist_cjs14 = __commonJS({
  46748. "../node_modules/.pnpm/@smithy+node-http-handler@4.0.6/node_modules/@smithy/node-http-handler/dist-cjs/index.js"(exports2, module2) {
  46749. var __create3 = Object.create;
  46750. var __defProp3 = Object.defineProperty;
  46751. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  46752. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  46753. var __getProtoOf3 = Object.getPrototypeOf;
  46754. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  46755. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  46756. var __export2 = (target, all) => {
  46757. for (var name in all)
  46758. __defProp3(target, name, { get: all[name], enumerable: true });
  46759. };
  46760. var __copyProps3 = (to, from, except, desc) => {
  46761. if (from && typeof from === "object" || typeof from === "function") {
  46762. for (let key of __getOwnPropNames3(from))
  46763. if (!__hasOwnProp3.call(to, key) && key !== except)
  46764. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  46765. }
  46766. return to;
  46767. };
  46768. var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
  46769. // If the importer is in node compatibility mode or this is not an ESM
  46770. // file that has been converted to a CommonJS file using a Babel-
  46771. // compatible transform (i.e. "__esModule" has not been set), then set
  46772. // "default" to the CommonJS "module.exports" for node compatibility.
  46773. isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
  46774. mod
  46775. ));
  46776. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  46777. var src_exports = {};
  46778. __export2(src_exports, {
  46779. DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT,
  46780. NodeHttp2Handler: () => NodeHttp2Handler,
  46781. NodeHttpHandler: () => NodeHttpHandler,
  46782. streamCollector: () => streamCollector3
  46783. });
  46784. module2.exports = __toCommonJS2(src_exports);
  46785. var import_protocol_http15 = require_dist_cjs2();
  46786. var import_querystring_builder = require_dist_cjs13();
  46787. var import_http3 = require("http");
  46788. var import_https = require("https");
  46789. var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"];
  46790. var getTransformedHeaders = /* @__PURE__ */ __name((headers) => {
  46791. const transformedHeaders = {};
  46792. for (const name of Object.keys(headers)) {
  46793. const headerValues = headers[name];
  46794. transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues;
  46795. }
  46796. return transformedHeaders;
  46797. }, "getTransformedHeaders");
  46798. var timing = {
  46799. setTimeout: (cb, ms) => setTimeout(cb, ms),
  46800. clearTimeout: (timeoutId) => clearTimeout(timeoutId)
  46801. };
  46802. var DEFER_EVENT_LISTENER_TIME = 1e3;
  46803. var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => {
  46804. if (!timeoutInMs) {
  46805. return -1;
  46806. }
  46807. const registerTimeout = /* @__PURE__ */ __name((offset) => {
  46808. const timeoutId = timing.setTimeout(() => {
  46809. request.destroy();
  46810. reject(
  46811. Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), {
  46812. name: "TimeoutError"
  46813. })
  46814. );
  46815. }, timeoutInMs - offset);
  46816. const doWithSocket = /* @__PURE__ */ __name((socket) => {
  46817. if (socket == null ? void 0 : socket.connecting) {
  46818. socket.on("connect", () => {
  46819. timing.clearTimeout(timeoutId);
  46820. });
  46821. } else {
  46822. timing.clearTimeout(timeoutId);
  46823. }
  46824. }, "doWithSocket");
  46825. if (request.socket) {
  46826. doWithSocket(request.socket);
  46827. } else {
  46828. request.on("socket", doWithSocket);
  46829. }
  46830. }, "registerTimeout");
  46831. if (timeoutInMs < 2e3) {
  46832. registerTimeout(0);
  46833. return 0;
  46834. }
  46835. return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);
  46836. }, "setConnectionTimeout");
  46837. var DEFER_EVENT_LISTENER_TIME2 = 3e3;
  46838. var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME2) => {
  46839. if (keepAlive !== true) {
  46840. return -1;
  46841. }
  46842. const registerListener = /* @__PURE__ */ __name(() => {
  46843. if (request.socket) {
  46844. request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
  46845. } else {
  46846. request.on("socket", (socket) => {
  46847. socket.setKeepAlive(keepAlive, keepAliveMsecs || 0);
  46848. });
  46849. }
  46850. }, "registerListener");
  46851. if (deferTimeMs === 0) {
  46852. registerListener();
  46853. return 0;
  46854. }
  46855. return timing.setTimeout(registerListener, deferTimeMs);
  46856. }, "setSocketKeepAlive");
  46857. var DEFER_EVENT_LISTENER_TIME3 = 3e3;
  46858. var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => {
  46859. const registerTimeout = /* @__PURE__ */ __name((offset) => {
  46860. const timeout = timeoutInMs - offset;
  46861. const onTimeout = /* @__PURE__ */ __name(() => {
  46862. request.destroy();
  46863. reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" }));
  46864. }, "onTimeout");
  46865. if (request.socket) {
  46866. request.socket.setTimeout(timeout, onTimeout);
  46867. request.on("close", () => {
  46868. var _a7;
  46869. return (_a7 = request.socket) == null ? void 0 : _a7.removeListener("timeout", onTimeout);
  46870. });
  46871. } else {
  46872. request.setTimeout(timeout, onTimeout);
  46873. }
  46874. }, "registerTimeout");
  46875. if (0 < timeoutInMs && timeoutInMs < 6e3) {
  46876. registerTimeout(0);
  46877. return 0;
  46878. }
  46879. return timing.setTimeout(
  46880. registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME3),
  46881. DEFER_EVENT_LISTENER_TIME3
  46882. );
  46883. }, "setSocketTimeout");
  46884. var import_stream3 = require("stream");
  46885. var MIN_WAIT_TIME = 6e3;
  46886. async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) {
  46887. const headers = request.headers ?? {};
  46888. const expect = headers["Expect"] || headers["expect"];
  46889. let timeoutId = -1;
  46890. let sendBody = true;
  46891. if (expect === "100-continue") {
  46892. sendBody = await Promise.race([
  46893. new Promise((resolve2) => {
  46894. timeoutId = Number(timing.setTimeout(() => resolve2(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));
  46895. }),
  46896. new Promise((resolve2) => {
  46897. httpRequest.on("continue", () => {
  46898. timing.clearTimeout(timeoutId);
  46899. resolve2(true);
  46900. });
  46901. httpRequest.on("response", () => {
  46902. timing.clearTimeout(timeoutId);
  46903. resolve2(false);
  46904. });
  46905. httpRequest.on("error", () => {
  46906. timing.clearTimeout(timeoutId);
  46907. resolve2(false);
  46908. });
  46909. })
  46910. ]);
  46911. }
  46912. if (sendBody) {
  46913. writeBody(httpRequest, request.body);
  46914. }
  46915. }
  46916. __name(writeRequestBody, "writeRequestBody");
  46917. function writeBody(httpRequest, body) {
  46918. if (body instanceof import_stream3.Readable) {
  46919. body.pipe(httpRequest);
  46920. return;
  46921. }
  46922. if (body) {
  46923. if (Buffer.isBuffer(body) || typeof body === "string") {
  46924. httpRequest.end(body);
  46925. return;
  46926. }
  46927. const uint8 = body;
  46928. if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") {
  46929. httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength));
  46930. return;
  46931. }
  46932. httpRequest.end(Buffer.from(body));
  46933. return;
  46934. }
  46935. httpRequest.end();
  46936. }
  46937. __name(writeBody, "writeBody");
  46938. var DEFAULT_REQUEST_TIMEOUT = 0;
  46939. var _a2;
  46940. var NodeHttpHandler = (_a2 = class {
  46941. constructor(options) {
  46942. this.socketWarningTimestamp = 0;
  46943. this.metadata = { handlerProtocol: "http/1.1" };
  46944. this.configProvider = new Promise((resolve2, reject) => {
  46945. if (typeof options === "function") {
  46946. options().then((_options) => {
  46947. resolve2(this.resolveDefaultConfig(_options));
  46948. }).catch(reject);
  46949. } else {
  46950. resolve2(this.resolveDefaultConfig(options));
  46951. }
  46952. });
  46953. }
  46954. /**
  46955. * @returns the input if it is an HttpHandler of any class,
  46956. * or instantiates a new instance of this handler.
  46957. */
  46958. static create(instanceOrOptions) {
  46959. if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") {
  46960. return instanceOrOptions;
  46961. }
  46962. return new _a2(instanceOrOptions);
  46963. }
  46964. /**
  46965. * @internal
  46966. *
  46967. * @param agent - http(s) agent in use by the NodeHttpHandler instance.
  46968. * @param socketWarningTimestamp - last socket usage check timestamp.
  46969. * @param logger - channel for the warning.
  46970. * @returns timestamp of last emitted warning.
  46971. */
  46972. static checkSocketUsage(agent, socketWarningTimestamp, logger3 = console) {
  46973. var _a7, _b, _c;
  46974. const { sockets, requests, maxSockets } = agent;
  46975. if (typeof maxSockets !== "number" || maxSockets === Infinity) {
  46976. return socketWarningTimestamp;
  46977. }
  46978. const interval = 15e3;
  46979. if (Date.now() - interval < socketWarningTimestamp) {
  46980. return socketWarningTimestamp;
  46981. }
  46982. if (sockets && requests) {
  46983. for (const origin in sockets) {
  46984. const socketsInUse = ((_a7 = sockets[origin]) == null ? void 0 : _a7.length) ?? 0;
  46985. const requestsEnqueued = ((_b = requests[origin]) == null ? void 0 : _b.length) ?? 0;
  46986. if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) {
  46987. (_c = logger3 == null ? void 0 : logger3.warn) == null ? void 0 : _c.call(
  46988. logger3,
  46989. `@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.
  46990. See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
  46991. or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`
  46992. );
  46993. return Date.now();
  46994. }
  46995. }
  46996. }
  46997. return socketWarningTimestamp;
  46998. }
  46999. resolveDefaultConfig(options) {
  47000. const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {};
  47001. const keepAlive = true;
  47002. const maxSockets = 50;
  47003. return {
  47004. connectionTimeout,
  47005. requestTimeout: requestTimeout ?? socketTimeout,
  47006. socketAcquisitionWarningTimeout,
  47007. httpAgent: (() => {
  47008. if (httpAgent instanceof import_http3.Agent || typeof (httpAgent == null ? void 0 : httpAgent.destroy) === "function") {
  47009. return httpAgent;
  47010. }
  47011. return new import_http3.Agent({ keepAlive, maxSockets, ...httpAgent });
  47012. })(),
  47013. httpsAgent: (() => {
  47014. if (httpsAgent instanceof import_https.Agent || typeof (httpsAgent == null ? void 0 : httpsAgent.destroy) === "function") {
  47015. return httpsAgent;
  47016. }
  47017. return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent });
  47018. })(),
  47019. logger: console
  47020. };
  47021. }
  47022. destroy() {
  47023. var _a7, _b, _c, _d;
  47024. (_b = (_a7 = this.config) == null ? void 0 : _a7.httpAgent) == null ? void 0 : _b.destroy();
  47025. (_d = (_c = this.config) == null ? void 0 : _c.httpsAgent) == null ? void 0 : _d.destroy();
  47026. }
  47027. async handle(request, { abortSignal } = {}) {
  47028. if (!this.config) {
  47029. this.config = await this.configProvider;
  47030. }
  47031. return new Promise((_resolve, _reject) => {
  47032. let writeRequestBodyPromise = void 0;
  47033. const timeouts = [];
  47034. const resolve2 = /* @__PURE__ */ __name(async (arg) => {
  47035. await writeRequestBodyPromise;
  47036. timeouts.forEach(timing.clearTimeout);
  47037. _resolve(arg);
  47038. }, "resolve");
  47039. const reject = /* @__PURE__ */ __name(async (arg) => {
  47040. await writeRequestBodyPromise;
  47041. timeouts.forEach(timing.clearTimeout);
  47042. _reject(arg);
  47043. }, "reject");
  47044. if (!this.config) {
  47045. throw new Error("Node HTTP request handler config is not resolved");
  47046. }
  47047. if (abortSignal == null ? void 0 : abortSignal.aborted) {
  47048. const abortError = new Error("Request aborted");
  47049. abortError.name = "AbortError";
  47050. reject(abortError);
  47051. return;
  47052. }
  47053. const isSSL = request.protocol === "https:";
  47054. const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent;
  47055. timeouts.push(
  47056. timing.setTimeout(
  47057. () => {
  47058. this.socketWarningTimestamp = _a2.checkSocketUsage(
  47059. agent,
  47060. this.socketWarningTimestamp,
  47061. this.config.logger
  47062. );
  47063. },
  47064. this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3)
  47065. )
  47066. );
  47067. const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {});
  47068. let auth = void 0;
  47069. if (request.username != null || request.password != null) {
  47070. const username = request.username ?? "";
  47071. const password = request.password ?? "";
  47072. auth = `${username}:${password}`;
  47073. }
  47074. let path4 = request.path;
  47075. if (queryString) {
  47076. path4 += `?${queryString}`;
  47077. }
  47078. if (request.fragment) {
  47079. path4 += `#${request.fragment}`;
  47080. }
  47081. let hostname = request.hostname ?? "";
  47082. if (hostname[0] === "[" && hostname.endsWith("]")) {
  47083. hostname = request.hostname.slice(1, -1);
  47084. } else {
  47085. hostname = request.hostname;
  47086. }
  47087. const nodeHttpsOptions = {
  47088. headers: request.headers,
  47089. host: hostname,
  47090. method: request.method,
  47091. path: path4,
  47092. port: request.port,
  47093. agent,
  47094. auth
  47095. };
  47096. const requestFunc = isSSL ? import_https.request : import_http3.request;
  47097. const req = requestFunc(nodeHttpsOptions, (res) => {
  47098. const httpResponse = new import_protocol_http15.HttpResponse({
  47099. statusCode: res.statusCode || -1,
  47100. reason: res.statusMessage,
  47101. headers: getTransformedHeaders(res.headers),
  47102. body: res
  47103. });
  47104. resolve2({ response: httpResponse });
  47105. });
  47106. req.on("error", (err2) => {
  47107. if (NODEJS_TIMEOUT_ERROR_CODES.includes(err2.code)) {
  47108. reject(Object.assign(err2, { name: "TimeoutError" }));
  47109. } else {
  47110. reject(err2);
  47111. }
  47112. });
  47113. if (abortSignal) {
  47114. const onAbort = /* @__PURE__ */ __name(() => {
  47115. req.destroy();
  47116. const abortError = new Error("Request aborted");
  47117. abortError.name = "AbortError";
  47118. reject(abortError);
  47119. }, "onAbort");
  47120. if (typeof abortSignal.addEventListener === "function") {
  47121. const signal = abortSignal;
  47122. signal.addEventListener("abort", onAbort, { once: true });
  47123. req.once("close", () => signal.removeEventListener("abort", onAbort));
  47124. } else {
  47125. abortSignal.onabort = onAbort;
  47126. }
  47127. }
  47128. timeouts.push(setConnectionTimeout(req, reject, this.config.connectionTimeout));
  47129. timeouts.push(setSocketTimeout(req, reject, this.config.requestTimeout));
  47130. const httpAgent = nodeHttpsOptions.agent;
  47131. if (typeof httpAgent === "object" && "keepAlive" in httpAgent) {
  47132. timeouts.push(
  47133. setSocketKeepAlive(req, {
  47134. // @ts-expect-error keepAlive is not public on httpAgent.
  47135. keepAlive: httpAgent.keepAlive,
  47136. // @ts-expect-error keepAliveMsecs is not public on httpAgent.
  47137. keepAliveMsecs: httpAgent.keepAliveMsecs
  47138. })
  47139. );
  47140. }
  47141. writeRequestBodyPromise = writeRequestBody(req, request, this.config.requestTimeout).catch((e4) => {
  47142. timeouts.forEach(timing.clearTimeout);
  47143. return _reject(e4);
  47144. });
  47145. });
  47146. }
  47147. updateHttpClientConfig(key, value) {
  47148. this.config = void 0;
  47149. this.configProvider = this.configProvider.then((config) => {
  47150. return {
  47151. ...config,
  47152. [key]: value
  47153. };
  47154. });
  47155. }
  47156. httpHandlerConfigs() {
  47157. return this.config ?? {};
  47158. }
  47159. }, __name(_a2, "NodeHttpHandler"), _a2);
  47160. var import_http22 = require("http2");
  47161. var import_http23 = __toESM3(require("http2"));
  47162. var _a3;
  47163. var NodeHttp2ConnectionPool = (_a3 = class {
  47164. constructor(sessions) {
  47165. this.sessions = [];
  47166. this.sessions = sessions ?? [];
  47167. }
  47168. poll() {
  47169. if (this.sessions.length > 0) {
  47170. return this.sessions.shift();
  47171. }
  47172. }
  47173. offerLast(session) {
  47174. this.sessions.push(session);
  47175. }
  47176. contains(session) {
  47177. return this.sessions.includes(session);
  47178. }
  47179. remove(session) {
  47180. this.sessions = this.sessions.filter((s4) => s4 !== session);
  47181. }
  47182. [Symbol.iterator]() {
  47183. return this.sessions[Symbol.iterator]();
  47184. }
  47185. destroy(connection) {
  47186. for (const session of this.sessions) {
  47187. if (session === connection) {
  47188. if (!session.destroyed) {
  47189. session.destroy();
  47190. }
  47191. }
  47192. }
  47193. }
  47194. }, __name(_a3, "NodeHttp2ConnectionPool"), _a3);
  47195. var _a4;
  47196. var NodeHttp2ConnectionManager = (_a4 = class {
  47197. constructor(config) {
  47198. this.sessionCache = /* @__PURE__ */ new Map();
  47199. this.config = config;
  47200. if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) {
  47201. throw new RangeError("maxConcurrency must be greater than zero.");
  47202. }
  47203. }
  47204. lease(requestContext, connectionConfiguration) {
  47205. const url = this.getUrlString(requestContext);
  47206. const existingPool = this.sessionCache.get(url);
  47207. if (existingPool) {
  47208. const existingSession = existingPool.poll();
  47209. if (existingSession && !this.config.disableConcurrency) {
  47210. return existingSession;
  47211. }
  47212. }
  47213. const session = import_http23.default.connect(url);
  47214. if (this.config.maxConcurrency) {
  47215. session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err2) => {
  47216. if (err2) {
  47217. throw new Error(
  47218. "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString()
  47219. );
  47220. }
  47221. });
  47222. }
  47223. session.unref();
  47224. const destroySessionCb = /* @__PURE__ */ __name(() => {
  47225. session.destroy();
  47226. this.deleteSession(url, session);
  47227. }, "destroySessionCb");
  47228. session.on("goaway", destroySessionCb);
  47229. session.on("error", destroySessionCb);
  47230. session.on("frameError", destroySessionCb);
  47231. session.on("close", () => this.deleteSession(url, session));
  47232. if (connectionConfiguration.requestTimeout) {
  47233. session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb);
  47234. }
  47235. const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool();
  47236. connectionPool.offerLast(session);
  47237. this.sessionCache.set(url, connectionPool);
  47238. return session;
  47239. }
  47240. /**
  47241. * Delete a session from the connection pool.
  47242. * @param authority The authority of the session to delete.
  47243. * @param session The session to delete.
  47244. */
  47245. deleteSession(authority, session) {
  47246. const existingConnectionPool = this.sessionCache.get(authority);
  47247. if (!existingConnectionPool) {
  47248. return;
  47249. }
  47250. if (!existingConnectionPool.contains(session)) {
  47251. return;
  47252. }
  47253. existingConnectionPool.remove(session);
  47254. this.sessionCache.set(authority, existingConnectionPool);
  47255. }
  47256. release(requestContext, session) {
  47257. var _a7;
  47258. const cacheKey2 = this.getUrlString(requestContext);
  47259. (_a7 = this.sessionCache.get(cacheKey2)) == null ? void 0 : _a7.offerLast(session);
  47260. }
  47261. destroy() {
  47262. for (const [key, connectionPool] of this.sessionCache) {
  47263. for (const session of connectionPool) {
  47264. if (!session.destroyed) {
  47265. session.destroy();
  47266. }
  47267. connectionPool.remove(session);
  47268. }
  47269. this.sessionCache.delete(key);
  47270. }
  47271. }
  47272. setMaxConcurrentStreams(maxConcurrentStreams) {
  47273. if (maxConcurrentStreams && maxConcurrentStreams <= 0) {
  47274. throw new RangeError("maxConcurrentStreams must be greater than zero.");
  47275. }
  47276. this.config.maxConcurrency = maxConcurrentStreams;
  47277. }
  47278. setDisableConcurrentStreams(disableConcurrentStreams) {
  47279. this.config.disableConcurrency = disableConcurrentStreams;
  47280. }
  47281. getUrlString(request) {
  47282. return request.destination.toString();
  47283. }
  47284. }, __name(_a4, "NodeHttp2ConnectionManager"), _a4);
  47285. var _a5;
  47286. var NodeHttp2Handler = (_a5 = class {
  47287. constructor(options) {
  47288. this.metadata = { handlerProtocol: "h2" };
  47289. this.connectionManager = new NodeHttp2ConnectionManager({});
  47290. this.configProvider = new Promise((resolve2, reject) => {
  47291. if (typeof options === "function") {
  47292. options().then((opts) => {
  47293. resolve2(opts || {});
  47294. }).catch(reject);
  47295. } else {
  47296. resolve2(options || {});
  47297. }
  47298. });
  47299. }
  47300. /**
  47301. * @returns the input if it is an HttpHandler of any class,
  47302. * or instantiates a new instance of this handler.
  47303. */
  47304. static create(instanceOrOptions) {
  47305. if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") {
  47306. return instanceOrOptions;
  47307. }
  47308. return new _a5(instanceOrOptions);
  47309. }
  47310. destroy() {
  47311. this.connectionManager.destroy();
  47312. }
  47313. async handle(request, { abortSignal } = {}) {
  47314. if (!this.config) {
  47315. this.config = await this.configProvider;
  47316. this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false);
  47317. if (this.config.maxConcurrentStreams) {
  47318. this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams);
  47319. }
  47320. }
  47321. const { requestTimeout, disableConcurrentStreams } = this.config;
  47322. return new Promise((_resolve, _reject) => {
  47323. var _a7;
  47324. let fulfilled = false;
  47325. let writeRequestBodyPromise = void 0;
  47326. const resolve2 = /* @__PURE__ */ __name(async (arg) => {
  47327. await writeRequestBodyPromise;
  47328. _resolve(arg);
  47329. }, "resolve");
  47330. const reject = /* @__PURE__ */ __name(async (arg) => {
  47331. await writeRequestBodyPromise;
  47332. _reject(arg);
  47333. }, "reject");
  47334. if (abortSignal == null ? void 0 : abortSignal.aborted) {
  47335. fulfilled = true;
  47336. const abortError = new Error("Request aborted");
  47337. abortError.name = "AbortError";
  47338. reject(abortError);
  47339. return;
  47340. }
  47341. const { hostname, method, port, protocol, query } = request;
  47342. let auth = "";
  47343. if (request.username != null || request.password != null) {
  47344. const username = request.username ?? "";
  47345. const password = request.password ?? "";
  47346. auth = `${username}:${password}@`;
  47347. }
  47348. const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`;
  47349. const requestContext = { destination: new URL(authority) };
  47350. const session = this.connectionManager.lease(requestContext, {
  47351. requestTimeout: (_a7 = this.config) == null ? void 0 : _a7.sessionTimeout,
  47352. disableConcurrentStreams: disableConcurrentStreams || false
  47353. });
  47354. const rejectWithDestroy = /* @__PURE__ */ __name((err2) => {
  47355. if (disableConcurrentStreams) {
  47356. this.destroySession(session);
  47357. }
  47358. fulfilled = true;
  47359. reject(err2);
  47360. }, "rejectWithDestroy");
  47361. const queryString = (0, import_querystring_builder.buildQueryString)(query || {});
  47362. let path4 = request.path;
  47363. if (queryString) {
  47364. path4 += `?${queryString}`;
  47365. }
  47366. if (request.fragment) {
  47367. path4 += `#${request.fragment}`;
  47368. }
  47369. const req = session.request({
  47370. ...request.headers,
  47371. [import_http22.constants.HTTP2_HEADER_PATH]: path4,
  47372. [import_http22.constants.HTTP2_HEADER_METHOD]: method
  47373. });
  47374. session.ref();
  47375. req.on("response", (headers) => {
  47376. const httpResponse = new import_protocol_http15.HttpResponse({
  47377. statusCode: headers[":status"] || -1,
  47378. headers: getTransformedHeaders(headers),
  47379. body: req
  47380. });
  47381. fulfilled = true;
  47382. resolve2({ response: httpResponse });
  47383. if (disableConcurrentStreams) {
  47384. session.close();
  47385. this.connectionManager.deleteSession(authority, session);
  47386. }
  47387. });
  47388. if (requestTimeout) {
  47389. req.setTimeout(requestTimeout, () => {
  47390. req.close();
  47391. const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`);
  47392. timeoutError.name = "TimeoutError";
  47393. rejectWithDestroy(timeoutError);
  47394. });
  47395. }
  47396. if (abortSignal) {
  47397. const onAbort = /* @__PURE__ */ __name(() => {
  47398. req.close();
  47399. const abortError = new Error("Request aborted");
  47400. abortError.name = "AbortError";
  47401. rejectWithDestroy(abortError);
  47402. }, "onAbort");
  47403. if (typeof abortSignal.addEventListener === "function") {
  47404. const signal = abortSignal;
  47405. signal.addEventListener("abort", onAbort, { once: true });
  47406. req.once("close", () => signal.removeEventListener("abort", onAbort));
  47407. } else {
  47408. abortSignal.onabort = onAbort;
  47409. }
  47410. }
  47411. req.on("frameError", (type, code, id) => {
  47412. rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`));
  47413. });
  47414. req.on("error", rejectWithDestroy);
  47415. req.on("aborted", () => {
  47416. rejectWithDestroy(
  47417. new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`)
  47418. );
  47419. });
  47420. req.on("close", () => {
  47421. session.unref();
  47422. if (disableConcurrentStreams) {
  47423. session.destroy();
  47424. }
  47425. if (!fulfilled) {
  47426. rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response"));
  47427. }
  47428. });
  47429. writeRequestBodyPromise = writeRequestBody(req, request, requestTimeout);
  47430. });
  47431. }
  47432. updateHttpClientConfig(key, value) {
  47433. this.config = void 0;
  47434. this.configProvider = this.configProvider.then((config) => {
  47435. return {
  47436. ...config,
  47437. [key]: value
  47438. };
  47439. });
  47440. }
  47441. httpHandlerConfigs() {
  47442. return this.config ?? {};
  47443. }
  47444. /**
  47445. * Destroys a session.
  47446. * @param session - the session to destroy.
  47447. */
  47448. destroySession(session) {
  47449. if (!session.destroyed) {
  47450. session.destroy();
  47451. }
  47452. }
  47453. }, __name(_a5, "NodeHttp2Handler"), _a5);
  47454. var _a6;
  47455. var Collector = (_a6 = class extends import_stream3.Writable {
  47456. constructor() {
  47457. super(...arguments);
  47458. this.bufferedBytes = [];
  47459. }
  47460. _write(chunk, encoding, callback) {
  47461. this.bufferedBytes.push(chunk);
  47462. callback();
  47463. }
  47464. }, __name(_a6, "Collector"), _a6);
  47465. var streamCollector3 = /* @__PURE__ */ __name((stream) => {
  47466. if (isReadableStreamInstance(stream)) {
  47467. return collectReadableStream(stream);
  47468. }
  47469. return new Promise((resolve2, reject) => {
  47470. const collector = new Collector();
  47471. stream.pipe(collector);
  47472. stream.on("error", (err2) => {
  47473. collector.end();
  47474. reject(err2);
  47475. });
  47476. collector.on("error", reject);
  47477. collector.on("finish", function() {
  47478. const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes));
  47479. resolve2(bytes);
  47480. });
  47481. });
  47482. }, "streamCollector");
  47483. var isReadableStreamInstance = /* @__PURE__ */ __name((stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream, "isReadableStreamInstance");
  47484. async function collectReadableStream(stream) {
  47485. const chunks = [];
  47486. const reader = stream.getReader();
  47487. let isDone = false;
  47488. let length = 0;
  47489. while (!isDone) {
  47490. const { done, value } = await reader.read();
  47491. if (value) {
  47492. chunks.push(value);
  47493. length += value.length;
  47494. }
  47495. isDone = done;
  47496. }
  47497. const collected = new Uint8Array(length);
  47498. let offset = 0;
  47499. for (const chunk of chunks) {
  47500. collected.set(chunk, offset);
  47501. offset += chunk.length;
  47502. }
  47503. return collected;
  47504. }
  47505. __name(collectReadableStream, "collectReadableStream");
  47506. }
  47507. });
  47508. // ../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js
  47509. var require_dist_cjs15 = __commonJS({
  47510. "../node_modules/.pnpm/@smithy+fetch-http-handler@5.0.4/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js"(exports2, module2) {
  47511. var __defProp3 = Object.defineProperty;
  47512. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  47513. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  47514. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  47515. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  47516. var __export2 = (target, all) => {
  47517. for (var name in all)
  47518. __defProp3(target, name, { get: all[name], enumerable: true });
  47519. };
  47520. var __copyProps3 = (to, from, except, desc) => {
  47521. if (from && typeof from === "object" || typeof from === "function") {
  47522. for (let key of __getOwnPropNames3(from))
  47523. if (!__hasOwnProp3.call(to, key) && key !== except)
  47524. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  47525. }
  47526. return to;
  47527. };
  47528. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  47529. var src_exports = {};
  47530. __export2(src_exports, {
  47531. FetchHttpHandler: () => FetchHttpHandler,
  47532. keepAliveSupport: () => keepAliveSupport,
  47533. streamCollector: () => streamCollector3
  47534. });
  47535. module2.exports = __toCommonJS2(src_exports);
  47536. var import_protocol_http15 = require_dist_cjs2();
  47537. var import_querystring_builder = require_dist_cjs13();
  47538. function createRequest(url, requestOptions) {
  47539. return new Request(url, requestOptions);
  47540. }
  47541. __name(createRequest, "createRequest");
  47542. function requestTimeout(timeoutInMs = 0) {
  47543. return new Promise((resolve2, reject) => {
  47544. if (timeoutInMs) {
  47545. setTimeout(() => {
  47546. const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`);
  47547. timeoutError.name = "TimeoutError";
  47548. reject(timeoutError);
  47549. }, timeoutInMs);
  47550. }
  47551. });
  47552. }
  47553. __name(requestTimeout, "requestTimeout");
  47554. var keepAliveSupport = {
  47555. supported: void 0
  47556. };
  47557. var _a2;
  47558. var FetchHttpHandler = (_a2 = class {
  47559. /**
  47560. * @returns the input if it is an HttpHandler of any class,
  47561. * or instantiates a new instance of this handler.
  47562. */
  47563. static create(instanceOrOptions) {
  47564. if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") {
  47565. return instanceOrOptions;
  47566. }
  47567. return new _a2(instanceOrOptions);
  47568. }
  47569. constructor(options) {
  47570. if (typeof options === "function") {
  47571. this.configProvider = options().then((opts) => opts || {});
  47572. } else {
  47573. this.config = options ?? {};
  47574. this.configProvider = Promise.resolve(this.config);
  47575. }
  47576. if (keepAliveSupport.supported === void 0) {
  47577. keepAliveSupport.supported = Boolean(
  47578. typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]")
  47579. );
  47580. }
  47581. }
  47582. destroy() {
  47583. }
  47584. async handle(request, { abortSignal } = {}) {
  47585. var _a3;
  47586. if (!this.config) {
  47587. this.config = await this.configProvider;
  47588. }
  47589. const requestTimeoutInMs = this.config.requestTimeout;
  47590. const keepAlive = this.config.keepAlive === true;
  47591. const credentials2 = this.config.credentials;
  47592. if (abortSignal == null ? void 0 : abortSignal.aborted) {
  47593. const abortError = new Error("Request aborted");
  47594. abortError.name = "AbortError";
  47595. return Promise.reject(abortError);
  47596. }
  47597. let path4 = request.path;
  47598. const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {});
  47599. if (queryString) {
  47600. path4 += `?${queryString}`;
  47601. }
  47602. if (request.fragment) {
  47603. path4 += `#${request.fragment}`;
  47604. }
  47605. let auth = "";
  47606. if (request.username != null || request.password != null) {
  47607. const username = request.username ?? "";
  47608. const password = request.password ?? "";
  47609. auth = `${username}:${password}@`;
  47610. }
  47611. const { port, method } = request;
  47612. const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path4}`;
  47613. const body = method === "GET" || method === "HEAD" ? void 0 : request.body;
  47614. const requestOptions = {
  47615. body,
  47616. headers: new Headers(request.headers),
  47617. method,
  47618. credentials: credentials2
  47619. };
  47620. if ((_a3 = this.config) == null ? void 0 : _a3.cache) {
  47621. requestOptions.cache = this.config.cache;
  47622. }
  47623. if (body) {
  47624. requestOptions.duplex = "half";
  47625. }
  47626. if (typeof AbortController !== "undefined") {
  47627. requestOptions.signal = abortSignal;
  47628. }
  47629. if (keepAliveSupport.supported) {
  47630. requestOptions.keepalive = keepAlive;
  47631. }
  47632. if (typeof this.config.requestInit === "function") {
  47633. Object.assign(requestOptions, this.config.requestInit(request));
  47634. }
  47635. let removeSignalEventListener = /* @__PURE__ */ __name(() => {
  47636. }, "removeSignalEventListener");
  47637. const fetchRequest = createRequest(url, requestOptions);
  47638. const raceOfPromises = [
  47639. fetch(fetchRequest).then((response) => {
  47640. const fetchHeaders = response.headers;
  47641. const transformedHeaders = {};
  47642. for (const pair of fetchHeaders.entries()) {
  47643. transformedHeaders[pair[0]] = pair[1];
  47644. }
  47645. const hasReadableStream = response.body != void 0;
  47646. if (!hasReadableStream) {
  47647. return response.blob().then((body2) => ({
  47648. response: new import_protocol_http15.HttpResponse({
  47649. headers: transformedHeaders,
  47650. reason: response.statusText,
  47651. statusCode: response.status,
  47652. body: body2
  47653. })
  47654. }));
  47655. }
  47656. return {
  47657. response: new import_protocol_http15.HttpResponse({
  47658. headers: transformedHeaders,
  47659. reason: response.statusText,
  47660. statusCode: response.status,
  47661. body: response.body
  47662. })
  47663. };
  47664. }),
  47665. requestTimeout(requestTimeoutInMs)
  47666. ];
  47667. if (abortSignal) {
  47668. raceOfPromises.push(
  47669. new Promise((resolve2, reject) => {
  47670. const onAbort = /* @__PURE__ */ __name(() => {
  47671. const abortError = new Error("Request aborted");
  47672. abortError.name = "AbortError";
  47673. reject(abortError);
  47674. }, "onAbort");
  47675. if (typeof abortSignal.addEventListener === "function") {
  47676. const signal = abortSignal;
  47677. signal.addEventListener("abort", onAbort, { once: true });
  47678. removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener");
  47679. } else {
  47680. abortSignal.onabort = onAbort;
  47681. }
  47682. })
  47683. );
  47684. }
  47685. return Promise.race(raceOfPromises).finally(removeSignalEventListener);
  47686. }
  47687. updateHttpClientConfig(key, value) {
  47688. this.config = void 0;
  47689. this.configProvider = this.configProvider.then((config) => {
  47690. config[key] = value;
  47691. return config;
  47692. });
  47693. }
  47694. httpHandlerConfigs() {
  47695. return this.config ?? {};
  47696. }
  47697. }, __name(_a2, "FetchHttpHandler"), _a2);
  47698. var import_util_base645 = require_dist_cjs11();
  47699. var streamCollector3 = /* @__PURE__ */ __name(async (stream) => {
  47700. var _a3;
  47701. if (typeof Blob === "function" && stream instanceof Blob || ((_a3 = stream.constructor) == null ? void 0 : _a3.name) === "Blob") {
  47702. if (Blob.prototype.arrayBuffer !== void 0) {
  47703. return new Uint8Array(await stream.arrayBuffer());
  47704. }
  47705. return collectBlob(stream);
  47706. }
  47707. return collectStream(stream);
  47708. }, "streamCollector");
  47709. async function collectBlob(blob) {
  47710. const base64 = await readToBase64(blob);
  47711. const arrayBuffer = (0, import_util_base645.fromBase64)(base64);
  47712. return new Uint8Array(arrayBuffer);
  47713. }
  47714. __name(collectBlob, "collectBlob");
  47715. async function collectStream(stream) {
  47716. const chunks = [];
  47717. const reader = stream.getReader();
  47718. let isDone = false;
  47719. let length = 0;
  47720. while (!isDone) {
  47721. const { done, value } = await reader.read();
  47722. if (value) {
  47723. chunks.push(value);
  47724. length += value.length;
  47725. }
  47726. isDone = done;
  47727. }
  47728. const collected = new Uint8Array(length);
  47729. let offset = 0;
  47730. for (const chunk of chunks) {
  47731. collected.set(chunk, offset);
  47732. offset += chunk.length;
  47733. }
  47734. return collected;
  47735. }
  47736. __name(collectStream, "collectStream");
  47737. function readToBase64(blob) {
  47738. return new Promise((resolve2, reject) => {
  47739. const reader = new FileReader();
  47740. reader.onloadend = () => {
  47741. if (reader.readyState !== 2) {
  47742. return reject(new Error("Reader aborted too early"));
  47743. }
  47744. const result = reader.result ?? "";
  47745. const commaIndex = result.indexOf(",");
  47746. const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
  47747. resolve2(result.substring(dataOffset));
  47748. };
  47749. reader.onabort = () => reject(new Error("Read aborted"));
  47750. reader.onerror = () => reject(reader.error);
  47751. reader.readAsDataURL(blob);
  47752. });
  47753. }
  47754. __name(readToBase64, "readToBase64");
  47755. }
  47756. });
  47757. // ../node_modules/.pnpm/@smithy+util-hex-encoding@4.0.0/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js
  47758. var require_dist_cjs16 = __commonJS({
  47759. "../node_modules/.pnpm/@smithy+util-hex-encoding@4.0.0/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js"(exports2, module2) {
  47760. var __defProp3 = Object.defineProperty;
  47761. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  47762. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  47763. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  47764. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  47765. var __export2 = (target, all) => {
  47766. for (var name in all)
  47767. __defProp3(target, name, { get: all[name], enumerable: true });
  47768. };
  47769. var __copyProps3 = (to, from, except, desc) => {
  47770. if (from && typeof from === "object" || typeof from === "function") {
  47771. for (let key of __getOwnPropNames3(from))
  47772. if (!__hasOwnProp3.call(to, key) && key !== except)
  47773. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  47774. }
  47775. return to;
  47776. };
  47777. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  47778. var src_exports = {};
  47779. __export2(src_exports, {
  47780. fromHex: () => fromHex,
  47781. toHex: () => toHex
  47782. });
  47783. module2.exports = __toCommonJS2(src_exports);
  47784. var SHORT_TO_HEX = {};
  47785. var HEX_TO_SHORT = {};
  47786. for (let i4 = 0; i4 < 256; i4++) {
  47787. let encodedByte = i4.toString(16).toLowerCase();
  47788. if (encodedByte.length === 1) {
  47789. encodedByte = `0${encodedByte}`;
  47790. }
  47791. SHORT_TO_HEX[i4] = encodedByte;
  47792. HEX_TO_SHORT[encodedByte] = i4;
  47793. }
  47794. function fromHex(encoded) {
  47795. if (encoded.length % 2 !== 0) {
  47796. throw new Error("Hex encoded strings must have an even number length");
  47797. }
  47798. const out = new Uint8Array(encoded.length / 2);
  47799. for (let i4 = 0; i4 < encoded.length; i4 += 2) {
  47800. const encodedByte = encoded.slice(i4, i4 + 2).toLowerCase();
  47801. if (encodedByte in HEX_TO_SHORT) {
  47802. out[i4 / 2] = HEX_TO_SHORT[encodedByte];
  47803. } else {
  47804. throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
  47805. }
  47806. }
  47807. return out;
  47808. }
  47809. __name(fromHex, "fromHex");
  47810. function toHex(bytes) {
  47811. let out = "";
  47812. for (let i4 = 0; i4 < bytes.byteLength; i4++) {
  47813. out += SHORT_TO_HEX[bytes[i4]];
  47814. }
  47815. return out;
  47816. }
  47817. __name(toHex, "toHex");
  47818. }
  47819. });
  47820. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js
  47821. var require_sdk_stream_mixin_browser = __commonJS({
  47822. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js"(exports2) {
  47823. "use strict";
  47824. Object.defineProperty(exports2, "__esModule", { value: true });
  47825. exports2.sdkStreamMixin = void 0;
  47826. var fetch_http_handler_1 = require_dist_cjs15();
  47827. var util_base64_1 = require_dist_cjs11();
  47828. var util_hex_encoding_1 = require_dist_cjs16();
  47829. var util_utf8_1 = require_dist_cjs10();
  47830. var stream_type_check_1 = require_stream_type_check();
  47831. var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
  47832. var sdkStreamMixin3 = (stream) => {
  47833. var _a2, _b;
  47834. if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) {
  47835. const name = ((_b = (_a2 = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a2 === void 0 ? void 0 : _a2.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream;
  47836. throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`);
  47837. }
  47838. let transformed = false;
  47839. const transformToByteArray = async () => {
  47840. if (transformed) {
  47841. throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
  47842. }
  47843. transformed = true;
  47844. return await (0, fetch_http_handler_1.streamCollector)(stream);
  47845. };
  47846. const blobToWebStream = (blob) => {
  47847. if (typeof blob.stream !== "function") {
  47848. throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");
  47849. }
  47850. return blob.stream();
  47851. };
  47852. return Object.assign(stream, {
  47853. transformToByteArray,
  47854. transformToString: async (encoding) => {
  47855. const buf = await transformToByteArray();
  47856. if (encoding === "base64") {
  47857. return (0, util_base64_1.toBase64)(buf);
  47858. } else if (encoding === "hex") {
  47859. return (0, util_hex_encoding_1.toHex)(buf);
  47860. } else if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") {
  47861. return (0, util_utf8_1.toUtf8)(buf);
  47862. } else if (typeof TextDecoder === "function") {
  47863. return new TextDecoder(encoding).decode(buf);
  47864. } else {
  47865. throw new Error("TextDecoder is not available, please make sure polyfill is provided.");
  47866. }
  47867. },
  47868. transformToWebStream: () => {
  47869. if (transformed) {
  47870. throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
  47871. }
  47872. transformed = true;
  47873. if (isBlobInstance(stream)) {
  47874. return blobToWebStream(stream);
  47875. } else if ((0, stream_type_check_1.isReadableStream)(stream)) {
  47876. return stream;
  47877. } else {
  47878. throw new Error(`Cannot transform payload to web stream, got ${stream}`);
  47879. }
  47880. }
  47881. });
  47882. };
  47883. exports2.sdkStreamMixin = sdkStreamMixin3;
  47884. var isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob;
  47885. }
  47886. });
  47887. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js
  47888. var require_sdk_stream_mixin = __commonJS({
  47889. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js"(exports2) {
  47890. "use strict";
  47891. Object.defineProperty(exports2, "__esModule", { value: true });
  47892. exports2.sdkStreamMixin = void 0;
  47893. var node_http_handler_1 = require_dist_cjs14();
  47894. var util_buffer_from_1 = require_dist_cjs9();
  47895. var stream_1 = require("stream");
  47896. var sdk_stream_mixin_browser_1 = require_sdk_stream_mixin_browser();
  47897. var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.";
  47898. var sdkStreamMixin3 = (stream) => {
  47899. var _a2, _b;
  47900. if (!(stream instanceof stream_1.Readable)) {
  47901. try {
  47902. return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream);
  47903. } catch (e4) {
  47904. const name = ((_b = (_a2 = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a2 === void 0 ? void 0 : _a2.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream;
  47905. throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`);
  47906. }
  47907. }
  47908. let transformed = false;
  47909. const transformToByteArray = async () => {
  47910. if (transformed) {
  47911. throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
  47912. }
  47913. transformed = true;
  47914. return await (0, node_http_handler_1.streamCollector)(stream);
  47915. };
  47916. return Object.assign(stream, {
  47917. transformToByteArray,
  47918. transformToString: async (encoding) => {
  47919. const buf = await transformToByteArray();
  47920. if (encoding === void 0 || Buffer.isEncoding(encoding)) {
  47921. return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding);
  47922. } else {
  47923. const decoder = new TextDecoder(encoding);
  47924. return decoder.decode(buf);
  47925. }
  47926. },
  47927. transformToWebStream: () => {
  47928. if (transformed) {
  47929. throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
  47930. }
  47931. if (stream.readableFlowing !== null) {
  47932. throw new Error("The stream has been consumed by other callbacks.");
  47933. }
  47934. if (typeof stream_1.Readable.toWeb !== "function") {
  47935. throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");
  47936. }
  47937. transformed = true;
  47938. return stream_1.Readable.toWeb(stream);
  47939. }
  47940. });
  47941. };
  47942. exports2.sdkStreamMixin = sdkStreamMixin3;
  47943. }
  47944. });
  47945. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js
  47946. var require_splitStream_browser = __commonJS({
  47947. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js"(exports2) {
  47948. "use strict";
  47949. Object.defineProperty(exports2, "__esModule", { value: true });
  47950. exports2.splitStream = splitStream2;
  47951. async function splitStream2(stream) {
  47952. if (typeof stream.stream === "function") {
  47953. stream = stream.stream();
  47954. }
  47955. const readableStream = stream;
  47956. return readableStream.tee();
  47957. }
  47958. }
  47959. });
  47960. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.js
  47961. var require_splitStream = __commonJS({
  47962. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/splitStream.js"(exports2) {
  47963. "use strict";
  47964. Object.defineProperty(exports2, "__esModule", { value: true });
  47965. exports2.splitStream = splitStream2;
  47966. var stream_1 = require("stream");
  47967. var splitStream_browser_1 = require_splitStream_browser();
  47968. var stream_type_check_1 = require_stream_type_check();
  47969. async function splitStream2(stream) {
  47970. if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) {
  47971. return (0, splitStream_browser_1.splitStream)(stream);
  47972. }
  47973. const stream1 = new stream_1.PassThrough();
  47974. const stream2 = new stream_1.PassThrough();
  47975. stream.pipe(stream1);
  47976. stream.pipe(stream2);
  47977. return [stream1, stream2];
  47978. }
  47979. }
  47980. });
  47981. // ../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/index.js
  47982. var require_dist_cjs17 = __commonJS({
  47983. "../node_modules/.pnpm/@smithy+util-stream@4.2.2/node_modules/@smithy/util-stream/dist-cjs/index.js"(exports2, module2) {
  47984. var __defProp3 = Object.defineProperty;
  47985. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  47986. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  47987. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  47988. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  47989. var __export2 = (target, all) => {
  47990. for (var name in all)
  47991. __defProp3(target, name, { get: all[name], enumerable: true });
  47992. };
  47993. var __copyProps3 = (to, from, except, desc) => {
  47994. if (from && typeof from === "object" || typeof from === "function") {
  47995. for (let key of __getOwnPropNames3(from))
  47996. if (!__hasOwnProp3.call(to, key) && key !== except)
  47997. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  47998. }
  47999. return to;
  48000. };
  48001. var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
  48002. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  48003. var src_exports = {};
  48004. __export2(src_exports, {
  48005. Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter2
  48006. });
  48007. module2.exports = __toCommonJS2(src_exports);
  48008. var import_util_base645 = require_dist_cjs11();
  48009. var import_util_utf85 = require_dist_cjs10();
  48010. function transformToString(payload, encoding = "utf-8") {
  48011. if (encoding === "base64") {
  48012. return (0, import_util_base645.toBase64)(payload);
  48013. }
  48014. return (0, import_util_utf85.toUtf8)(payload);
  48015. }
  48016. __name(transformToString, "transformToString");
  48017. function transformFromString(str, encoding) {
  48018. if (encoding === "base64") {
  48019. return Uint8ArrayBlobAdapter2.mutate((0, import_util_base645.fromBase64)(str));
  48020. }
  48021. return Uint8ArrayBlobAdapter2.mutate((0, import_util_utf85.fromUtf8)(str));
  48022. }
  48023. __name(transformFromString, "transformFromString");
  48024. var _a2;
  48025. var Uint8ArrayBlobAdapter2 = (_a2 = class extends Uint8Array {
  48026. /**
  48027. * @param source - such as a string or Stream.
  48028. * @returns a new Uint8ArrayBlobAdapter extending Uint8Array.
  48029. */
  48030. static fromString(source, encoding = "utf-8") {
  48031. switch (typeof source) {
  48032. case "string":
  48033. return transformFromString(source, encoding);
  48034. default:
  48035. throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`);
  48036. }
  48037. }
  48038. /**
  48039. * @param source - Uint8Array to be mutated.
  48040. * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter.
  48041. */
  48042. static mutate(source) {
  48043. Object.setPrototypeOf(source, _a2.prototype);
  48044. return source;
  48045. }
  48046. /**
  48047. * @param encoding - default 'utf-8'.
  48048. * @returns the blob as string.
  48049. */
  48050. transformToString(encoding = "utf-8") {
  48051. return transformToString(this, encoding);
  48052. }
  48053. }, __name(_a2, "Uint8ArrayBlobAdapter"), _a2);
  48054. __reExport(src_exports, require_ChecksumStream(), module2.exports);
  48055. __reExport(src_exports, require_createChecksumStream(), module2.exports);
  48056. __reExport(src_exports, require_createBufferedReadable(), module2.exports);
  48057. __reExport(src_exports, require_getAwsChunkedEncodingStream(), module2.exports);
  48058. __reExport(src_exports, require_headStream(), module2.exports);
  48059. __reExport(src_exports, require_sdk_stream_mixin(), module2.exports);
  48060. __reExport(src_exports, require_splitStream(), module2.exports);
  48061. __reExport(src_exports, require_stream_type_check(), module2.exports);
  48062. }
  48063. });
  48064. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js
  48065. var import_util_stream, collectBody2;
  48066. var init_collect_stream_body = __esm({
  48067. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js"() {
  48068. import_util_stream = __toESM(require_dist_cjs17());
  48069. collectBody2 = async (streamBody = new Uint8Array(), context) => {
  48070. if (streamBody instanceof Uint8Array) {
  48071. return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody);
  48072. }
  48073. if (!streamBody) {
  48074. return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array());
  48075. }
  48076. const fromContext = context.streamCollector(streamBody);
  48077. return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext);
  48078. };
  48079. }
  48080. });
  48081. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js
  48082. function extendedEncodeURIComponent2(str) {
  48083. return encodeURIComponent(str).replace(/[!'()*]/g, function(c3) {
  48084. return "%" + c3.charCodeAt(0).toString(16).toUpperCase();
  48085. });
  48086. }
  48087. var init_extended_encode_uri_component = __esm({
  48088. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js"() {
  48089. }
  48090. });
  48091. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js
  48092. var deref;
  48093. var init_deref = __esm({
  48094. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/deref.js"() {
  48095. deref = (schemaRef) => {
  48096. if (typeof schemaRef === "function") {
  48097. return schemaRef();
  48098. }
  48099. return schemaRef;
  48100. };
  48101. }
  48102. });
  48103. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js
  48104. var import_protocol_http2, import_util_middleware3;
  48105. var init_schemaDeserializationMiddleware = __esm({
  48106. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() {
  48107. import_protocol_http2 = __toESM(require_dist_cjs2());
  48108. import_util_middleware3 = __toESM(require_dist_cjs6());
  48109. }
  48110. });
  48111. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js
  48112. var import_util_middleware4;
  48113. var init_schemaSerializationMiddleware = __esm({
  48114. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() {
  48115. import_util_middleware4 = __toESM(require_dist_cjs6());
  48116. }
  48117. });
  48118. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js
  48119. var init_getSchemaSerdePlugin = __esm({
  48120. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() {
  48121. init_schemaDeserializationMiddleware();
  48122. init_schemaSerializationMiddleware();
  48123. }
  48124. });
  48125. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js
  48126. var TypeRegistry;
  48127. var init_TypeRegistry = __esm({
  48128. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js"() {
  48129. TypeRegistry = class _TypeRegistry {
  48130. constructor(namespace, schemas = /* @__PURE__ */ new Map()) {
  48131. this.namespace = namespace;
  48132. this.schemas = schemas;
  48133. }
  48134. static for(namespace) {
  48135. if (!_TypeRegistry.registries.has(namespace)) {
  48136. _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace));
  48137. }
  48138. return _TypeRegistry.registries.get(namespace);
  48139. }
  48140. register(shapeId, schema6) {
  48141. const qualifiedName = this.normalizeShapeId(shapeId);
  48142. const registry = _TypeRegistry.for(this.getNamespace(shapeId));
  48143. registry.schemas.set(qualifiedName, schema6);
  48144. }
  48145. getSchema(shapeId) {
  48146. const id = this.normalizeShapeId(shapeId);
  48147. if (!this.schemas.has(id)) {
  48148. throw new Error(`@smithy/core/schema - schema not found for ${id}`);
  48149. }
  48150. return this.schemas.get(id);
  48151. }
  48152. getBaseException() {
  48153. for (const [id, schema6] of this.schemas.entries()) {
  48154. if (id.startsWith("smithyts.client.synthetic.") && id.endsWith("ServiceException")) {
  48155. return schema6;
  48156. }
  48157. }
  48158. return void 0;
  48159. }
  48160. find(predicate) {
  48161. return [...this.schemas.values()].find(predicate);
  48162. }
  48163. destroy() {
  48164. _TypeRegistry.registries.delete(this.namespace);
  48165. this.schemas.clear();
  48166. }
  48167. normalizeShapeId(shapeId) {
  48168. if (shapeId.includes("#")) {
  48169. return shapeId;
  48170. }
  48171. return this.namespace + "#" + shapeId;
  48172. }
  48173. getNamespace(shapeId) {
  48174. return this.normalizeShapeId(shapeId).split("#")[0];
  48175. }
  48176. };
  48177. TypeRegistry.registries = /* @__PURE__ */ new Map();
  48178. }
  48179. });
  48180. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js
  48181. var Schema;
  48182. var init_Schema = __esm({
  48183. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js"() {
  48184. Schema = class {
  48185. constructor(name, traits) {
  48186. this.name = name;
  48187. this.traits = traits;
  48188. }
  48189. };
  48190. }
  48191. });
  48192. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js
  48193. var ListSchema;
  48194. var init_ListSchema = __esm({
  48195. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js"() {
  48196. init_TypeRegistry();
  48197. init_Schema();
  48198. ListSchema = class extends Schema {
  48199. constructor(name, traits, valueSchema) {
  48200. super(name, traits);
  48201. this.name = name;
  48202. this.traits = traits;
  48203. this.valueSchema = valueSchema;
  48204. }
  48205. };
  48206. }
  48207. });
  48208. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js
  48209. var MapSchema;
  48210. var init_MapSchema = __esm({
  48211. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js"() {
  48212. init_TypeRegistry();
  48213. init_Schema();
  48214. MapSchema = class extends Schema {
  48215. constructor(name, traits, keySchema, valueSchema) {
  48216. super(name, traits);
  48217. this.name = name;
  48218. this.traits = traits;
  48219. this.keySchema = keySchema;
  48220. this.valueSchema = valueSchema;
  48221. }
  48222. };
  48223. }
  48224. });
  48225. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js
  48226. var init_OperationSchema = __esm({
  48227. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js"() {
  48228. init_TypeRegistry();
  48229. init_Schema();
  48230. }
  48231. });
  48232. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js
  48233. var StructureSchema;
  48234. var init_StructureSchema = __esm({
  48235. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() {
  48236. init_TypeRegistry();
  48237. init_Schema();
  48238. StructureSchema = class extends Schema {
  48239. constructor(name, traits, memberNames, memberList) {
  48240. super(name, traits);
  48241. this.name = name;
  48242. this.traits = traits;
  48243. this.memberNames = memberNames;
  48244. this.memberList = memberList;
  48245. this.members = {};
  48246. for (let i4 = 0; i4 < memberNames.length; ++i4) {
  48247. this.members[memberNames[i4]] = Array.isArray(memberList[i4]) ? memberList[i4] : [memberList[i4], 0];
  48248. }
  48249. }
  48250. };
  48251. }
  48252. });
  48253. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js
  48254. var init_ErrorSchema = __esm({
  48255. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() {
  48256. init_TypeRegistry();
  48257. init_StructureSchema();
  48258. }
  48259. });
  48260. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js
  48261. var SCHEMA;
  48262. var init_sentinels = __esm({
  48263. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js"() {
  48264. SCHEMA = {
  48265. BLOB: 21,
  48266. STREAMING_BLOB: 42,
  48267. BOOLEAN: 2,
  48268. STRING: 0,
  48269. NUMERIC: 1,
  48270. BIG_INTEGER: 17,
  48271. BIG_DECIMAL: 19,
  48272. DOCUMENT: 15,
  48273. TIMESTAMP_DEFAULT: 4,
  48274. TIMESTAMP_DATE_TIME: 5,
  48275. TIMESTAMP_HTTP_DATE: 6,
  48276. TIMESTAMP_EPOCH_SECONDS: 7,
  48277. LIST_MODIFIER: 64,
  48278. MAP_MODIFIER: 128
  48279. };
  48280. }
  48281. });
  48282. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js
  48283. var SimpleSchema;
  48284. var init_SimpleSchema = __esm({
  48285. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() {
  48286. init_TypeRegistry();
  48287. init_Schema();
  48288. SimpleSchema = class extends Schema {
  48289. constructor(name, schemaRef, traits) {
  48290. super(name, traits);
  48291. this.name = name;
  48292. this.schemaRef = schemaRef;
  48293. this.traits = traits;
  48294. }
  48295. };
  48296. }
  48297. });
  48298. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js
  48299. var NormalizedSchema;
  48300. var init_NormalizedSchema = __esm({
  48301. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() {
  48302. init_deref();
  48303. init_ListSchema();
  48304. init_MapSchema();
  48305. init_sentinels();
  48306. init_SimpleSchema();
  48307. init_StructureSchema();
  48308. NormalizedSchema = class _NormalizedSchema {
  48309. constructor(ref, memberName) {
  48310. var _a2, _b;
  48311. this.ref = ref;
  48312. this.memberName = memberName;
  48313. const traitStack = [];
  48314. let _ref = ref;
  48315. let schema6 = ref;
  48316. this._isMemberSchema = false;
  48317. while (Array.isArray(_ref)) {
  48318. traitStack.push(_ref[1]);
  48319. _ref = _ref[0];
  48320. schema6 = deref(_ref);
  48321. this._isMemberSchema = true;
  48322. }
  48323. if (traitStack.length > 0) {
  48324. this.memberTraits = {};
  48325. for (let i4 = traitStack.length - 1; i4 >= 0; --i4) {
  48326. const traitSet = traitStack[i4];
  48327. Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet));
  48328. }
  48329. } else {
  48330. this.memberTraits = 0;
  48331. }
  48332. if (schema6 instanceof _NormalizedSchema) {
  48333. this.name = schema6.name;
  48334. this.traits = schema6.traits;
  48335. this._isMemberSchema = schema6._isMemberSchema;
  48336. this.schema = schema6.schema;
  48337. this.memberTraits = Object.assign({}, schema6.getMemberTraits(), this.getMemberTraits());
  48338. this.normalizedTraits = void 0;
  48339. this.ref = schema6.ref;
  48340. this.memberName = memberName ?? schema6.memberName;
  48341. return;
  48342. }
  48343. this.schema = deref(schema6);
  48344. if (this.schema && typeof this.schema === "object") {
  48345. this.traits = ((_a2 = this.schema) == null ? void 0 : _a2.traits) ?? {};
  48346. } else {
  48347. this.traits = 0;
  48348. }
  48349. this.name = (typeof this.schema === "object" ? (_b = this.schema) == null ? void 0 : _b.name : void 0) ?? this.memberName ?? this.getSchemaName();
  48350. if (this._isMemberSchema && !memberName) {
  48351. throw new Error(`@smithy/core/schema - NormalizedSchema member schema ${this.getName(true)} must initialize with memberName argument.`);
  48352. }
  48353. }
  48354. static of(ref, memberName) {
  48355. if (ref instanceof _NormalizedSchema) {
  48356. return ref;
  48357. }
  48358. return new _NormalizedSchema(ref, memberName);
  48359. }
  48360. static translateTraits(indicator) {
  48361. if (typeof indicator === "object") {
  48362. return indicator;
  48363. }
  48364. indicator = indicator | 0;
  48365. const traits = {};
  48366. if ((indicator & 1) === 1) {
  48367. traits.httpLabel = 1;
  48368. }
  48369. if ((indicator >> 1 & 1) === 1) {
  48370. traits.idempotent = 1;
  48371. }
  48372. if ((indicator >> 2 & 1) === 1) {
  48373. traits.idempotencyToken = 1;
  48374. }
  48375. if ((indicator >> 3 & 1) === 1) {
  48376. traits.sensitive = 1;
  48377. }
  48378. if ((indicator >> 4 & 1) === 1) {
  48379. traits.httpPayload = 1;
  48380. }
  48381. if ((indicator >> 5 & 1) === 1) {
  48382. traits.httpResponseCode = 1;
  48383. }
  48384. if ((indicator >> 6 & 1) === 1) {
  48385. traits.httpQueryParams = 1;
  48386. }
  48387. return traits;
  48388. }
  48389. static memberFrom(memberSchema, memberName) {
  48390. if (memberSchema instanceof _NormalizedSchema) {
  48391. memberSchema.memberName = memberName;
  48392. memberSchema._isMemberSchema = true;
  48393. return memberSchema;
  48394. }
  48395. return new _NormalizedSchema(memberSchema, memberName);
  48396. }
  48397. getSchema() {
  48398. if (this.schema instanceof _NormalizedSchema) {
  48399. return this.schema = this.schema.getSchema();
  48400. }
  48401. if (this.schema instanceof SimpleSchema) {
  48402. return deref(this.schema.schemaRef);
  48403. }
  48404. return deref(this.schema);
  48405. }
  48406. getName(withNamespace = false) {
  48407. if (!withNamespace) {
  48408. if (this.name && this.name.includes("#")) {
  48409. return this.name.split("#")[1];
  48410. }
  48411. }
  48412. return this.name || void 0;
  48413. }
  48414. getMemberName() {
  48415. if (!this.isMemberSchema()) {
  48416. throw new Error(`@smithy/core/schema - cannot get member name on non-member schema: ${this.getName(true)}`);
  48417. }
  48418. return this.memberName;
  48419. }
  48420. isMemberSchema() {
  48421. return this._isMemberSchema;
  48422. }
  48423. isUnitSchema() {
  48424. return this.getSchema() === "unit";
  48425. }
  48426. isListSchema() {
  48427. const inner = this.getSchema();
  48428. if (typeof inner === "number") {
  48429. return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER;
  48430. }
  48431. return inner instanceof ListSchema;
  48432. }
  48433. isMapSchema() {
  48434. const inner = this.getSchema();
  48435. if (typeof inner === "number") {
  48436. return inner >= SCHEMA.MAP_MODIFIER && inner <= 255;
  48437. }
  48438. return inner instanceof MapSchema;
  48439. }
  48440. isDocumentSchema() {
  48441. return this.getSchema() === SCHEMA.DOCUMENT;
  48442. }
  48443. isStructSchema() {
  48444. const inner = this.getSchema();
  48445. return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema;
  48446. }
  48447. isBlobSchema() {
  48448. return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB;
  48449. }
  48450. isTimestampSchema() {
  48451. const schema6 = this.getSchema();
  48452. return typeof schema6 === "number" && schema6 >= SCHEMA.TIMESTAMP_DEFAULT && schema6 <= SCHEMA.TIMESTAMP_EPOCH_SECONDS;
  48453. }
  48454. isStringSchema() {
  48455. return this.getSchema() === SCHEMA.STRING;
  48456. }
  48457. isBooleanSchema() {
  48458. return this.getSchema() === SCHEMA.BOOLEAN;
  48459. }
  48460. isNumericSchema() {
  48461. return this.getSchema() === SCHEMA.NUMERIC;
  48462. }
  48463. isBigIntegerSchema() {
  48464. return this.getSchema() === SCHEMA.BIG_INTEGER;
  48465. }
  48466. isBigDecimalSchema() {
  48467. return this.getSchema() === SCHEMA.BIG_DECIMAL;
  48468. }
  48469. isStreaming() {
  48470. const streaming = !!this.getMergedTraits().streaming;
  48471. if (streaming) {
  48472. return true;
  48473. }
  48474. return this.getSchema() === SCHEMA.STREAMING_BLOB;
  48475. }
  48476. getMergedTraits() {
  48477. if (this.normalizedTraits) {
  48478. return this.normalizedTraits;
  48479. }
  48480. this.normalizedTraits = {
  48481. ...this.getOwnTraits(),
  48482. ...this.getMemberTraits()
  48483. };
  48484. return this.normalizedTraits;
  48485. }
  48486. getMemberTraits() {
  48487. return _NormalizedSchema.translateTraits(this.memberTraits);
  48488. }
  48489. getOwnTraits() {
  48490. return _NormalizedSchema.translateTraits(this.traits);
  48491. }
  48492. getKeySchema() {
  48493. if (this.isDocumentSchema()) {
  48494. return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "key");
  48495. }
  48496. if (!this.isMapSchema()) {
  48497. throw new Error(`@smithy/core/schema - cannot get key schema for non-map schema: ${this.getName(true)}`);
  48498. }
  48499. const schema6 = this.getSchema();
  48500. if (typeof schema6 === "number") {
  48501. return _NormalizedSchema.memberFrom([63 & schema6, 0], "key");
  48502. }
  48503. return _NormalizedSchema.memberFrom([schema6.keySchema, 0], "key");
  48504. }
  48505. getValueSchema() {
  48506. const schema6 = this.getSchema();
  48507. if (typeof schema6 === "number") {
  48508. if (this.isMapSchema()) {
  48509. return _NormalizedSchema.memberFrom([63 & schema6, 0], "value");
  48510. } else if (this.isListSchema()) {
  48511. return _NormalizedSchema.memberFrom([63 & schema6, 0], "member");
  48512. }
  48513. }
  48514. if (schema6 && typeof schema6 === "object") {
  48515. if (this.isStructSchema()) {
  48516. throw new Error(`cannot call getValueSchema() with StructureSchema ${this.getName(true)}`);
  48517. }
  48518. const collection = schema6;
  48519. if ("valueSchema" in collection) {
  48520. if (this.isMapSchema()) {
  48521. return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "value");
  48522. } else if (this.isListSchema()) {
  48523. return _NormalizedSchema.memberFrom([collection.valueSchema, 0], "member");
  48524. }
  48525. }
  48526. }
  48527. if (this.isDocumentSchema()) {
  48528. return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], "value");
  48529. }
  48530. throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have a value member.`);
  48531. }
  48532. getMemberSchema(member) {
  48533. if (this.isStructSchema()) {
  48534. const struct = this.getSchema();
  48535. if (!(member in struct.members)) {
  48536. throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have a member with name=${member}.`);
  48537. }
  48538. return _NormalizedSchema.memberFrom(struct.members[member], member);
  48539. }
  48540. if (this.isDocumentSchema()) {
  48541. return _NormalizedSchema.memberFrom([SCHEMA.DOCUMENT, 0], member);
  48542. }
  48543. throw new Error(`@smithy/core/schema - the schema ${this.getName(true)} does not have members.`);
  48544. }
  48545. getMemberSchemas() {
  48546. const { schema: schema6 } = this;
  48547. const struct = schema6;
  48548. if (!struct || typeof struct !== "object") {
  48549. return {};
  48550. }
  48551. if ("members" in struct) {
  48552. const buffer = {};
  48553. for (const member of struct.memberNames) {
  48554. buffer[member] = this.getMemberSchema(member);
  48555. }
  48556. return buffer;
  48557. }
  48558. return {};
  48559. }
  48560. *structIterator() {
  48561. if (!this.isStructSchema()) {
  48562. throw new Error("@smithy/core/schema - cannot acquire structIterator on non-struct schema.");
  48563. }
  48564. const struct = this.getSchema();
  48565. for (let i4 = 0; i4 < struct.memberNames.length; ++i4) {
  48566. yield [struct.memberNames[i4], _NormalizedSchema.memberFrom([struct.memberList[i4], 0], struct.memberNames[i4])];
  48567. }
  48568. }
  48569. getSchemaName() {
  48570. var _a2;
  48571. const schema6 = this.getSchema();
  48572. if (typeof schema6 === "number") {
  48573. const _schema = 63 & schema6;
  48574. const container = 192 & schema6;
  48575. const type = ((_a2 = Object.entries(SCHEMA).find(([, value]) => {
  48576. return value === _schema;
  48577. })) == null ? void 0 : _a2[0]) ?? "Unknown";
  48578. switch (container) {
  48579. case SCHEMA.MAP_MODIFIER:
  48580. return `${type}Map`;
  48581. case SCHEMA.LIST_MODIFIER:
  48582. return `${type}List`;
  48583. case 0:
  48584. return type;
  48585. }
  48586. }
  48587. return "Unknown";
  48588. }
  48589. };
  48590. }
  48591. });
  48592. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js
  48593. var init_schema = __esm({
  48594. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/schema/index.js"() {
  48595. init_deref();
  48596. init_getSchemaSerdePlugin();
  48597. init_ListSchema();
  48598. init_MapSchema();
  48599. init_OperationSchema();
  48600. init_ErrorSchema();
  48601. init_NormalizedSchema();
  48602. init_Schema();
  48603. init_SimpleSchema();
  48604. init_StructureSchema();
  48605. init_sentinels();
  48606. init_TypeRegistry();
  48607. }
  48608. });
  48609. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js
  48610. var copyDocumentWithTransform2;
  48611. var init_copyDocumentWithTransform = __esm({
  48612. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js"() {
  48613. init_schema();
  48614. copyDocumentWithTransform2 = (source, schemaRef, transform = (_3) => _3) => {
  48615. const ns = NormalizedSchema.of(schemaRef);
  48616. switch (typeof source) {
  48617. case "undefined":
  48618. case "boolean":
  48619. case "number":
  48620. case "string":
  48621. case "bigint":
  48622. case "symbol":
  48623. return transform(source, ns);
  48624. case "function":
  48625. case "object":
  48626. if (source === null) {
  48627. return transform(null, ns);
  48628. }
  48629. if (Array.isArray(source)) {
  48630. const newArray = new Array(source.length);
  48631. let i4 = 0;
  48632. for (const item of source) {
  48633. newArray[i4++] = copyDocumentWithTransform2(item, ns.getValueSchema(), transform);
  48634. }
  48635. return transform(newArray, ns);
  48636. }
  48637. if ("byteLength" in source) {
  48638. const newBytes = new Uint8Array(source.byteLength);
  48639. newBytes.set(source, 0);
  48640. return transform(newBytes, ns);
  48641. }
  48642. if (source instanceof Date) {
  48643. return transform(source, ns);
  48644. }
  48645. const newObject = {};
  48646. if (ns.isMapSchema()) {
  48647. for (const key of Object.keys(source)) {
  48648. newObject[key] = copyDocumentWithTransform2(source[key], ns.getValueSchema(), transform);
  48649. }
  48650. } else if (ns.isStructSchema()) {
  48651. for (const [key, memberSchema] of ns.structIterator()) {
  48652. newObject[key] = copyDocumentWithTransform2(source[key], memberSchema, transform);
  48653. }
  48654. } else if (ns.isDocumentSchema()) {
  48655. for (const key of Object.keys(source)) {
  48656. newObject[key] = copyDocumentWithTransform2(source[key], ns.getValueSchema(), transform);
  48657. }
  48658. }
  48659. return transform(newObject, ns);
  48660. default:
  48661. return transform(source, ns);
  48662. }
  48663. };
  48664. }
  48665. });
  48666. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js
  48667. var parseBoolean2, expectBoolean2, expectNumber2, MAX_FLOAT, expectFloat322, expectLong2, expectInt2, expectInt322, expectShort2, expectByte2, expectSizedInt, castInt, expectNonNull2, expectObject2, expectString2, expectUnion2, strictParseDouble2, strictParseFloat2, strictParseFloat322, NUMBER_REGEX, parseNumber, limitedParseDouble2, handleFloat2, limitedParseFloat2, limitedParseFloat322, parseFloatString, strictParseLong2, strictParseInt2, strictParseInt322, strictParseShort2, strictParseByte2, stackTraceWarning, logger2;
  48668. var init_parse_utils = __esm({
  48669. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js"() {
  48670. parseBoolean2 = (value) => {
  48671. switch (value) {
  48672. case "true":
  48673. return true;
  48674. case "false":
  48675. return false;
  48676. default:
  48677. throw new Error(`Unable to parse boolean value "${value}"`);
  48678. }
  48679. };
  48680. expectBoolean2 = (value) => {
  48681. if (value === null || value === void 0) {
  48682. return void 0;
  48683. }
  48684. if (typeof value === "number") {
  48685. if (value === 0 || value === 1) {
  48686. logger2.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
  48687. }
  48688. if (value === 0) {
  48689. return false;
  48690. }
  48691. if (value === 1) {
  48692. return true;
  48693. }
  48694. }
  48695. if (typeof value === "string") {
  48696. const lower2 = value.toLowerCase();
  48697. if (lower2 === "false" || lower2 === "true") {
  48698. logger2.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`));
  48699. }
  48700. if (lower2 === "false") {
  48701. return false;
  48702. }
  48703. if (lower2 === "true") {
  48704. return true;
  48705. }
  48706. }
  48707. if (typeof value === "boolean") {
  48708. return value;
  48709. }
  48710. throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`);
  48711. };
  48712. expectNumber2 = (value) => {
  48713. if (value === null || value === void 0) {
  48714. return void 0;
  48715. }
  48716. if (typeof value === "string") {
  48717. const parsed = parseFloat(value);
  48718. if (!Number.isNaN(parsed)) {
  48719. if (String(parsed) !== String(value)) {
  48720. logger2.warn(stackTraceWarning(`Expected number but observed string: ${value}`));
  48721. }
  48722. return parsed;
  48723. }
  48724. }
  48725. if (typeof value === "number") {
  48726. return value;
  48727. }
  48728. throw new TypeError(`Expected number, got ${typeof value}: ${value}`);
  48729. };
  48730. MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
  48731. expectFloat322 = (value) => {
  48732. const expected = expectNumber2(value);
  48733. if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) {
  48734. if (Math.abs(expected) > MAX_FLOAT) {
  48735. throw new TypeError(`Expected 32-bit float, got ${value}`);
  48736. }
  48737. }
  48738. return expected;
  48739. };
  48740. expectLong2 = (value) => {
  48741. if (value === null || value === void 0) {
  48742. return void 0;
  48743. }
  48744. if (Number.isInteger(value) && !Number.isNaN(value)) {
  48745. return value;
  48746. }
  48747. throw new TypeError(`Expected integer, got ${typeof value}: ${value}`);
  48748. };
  48749. expectInt2 = expectLong2;
  48750. expectInt322 = (value) => expectSizedInt(value, 32);
  48751. expectShort2 = (value) => expectSizedInt(value, 16);
  48752. expectByte2 = (value) => expectSizedInt(value, 8);
  48753. expectSizedInt = (value, size) => {
  48754. const expected = expectLong2(value);
  48755. if (expected !== void 0 && castInt(expected, size) !== expected) {
  48756. throw new TypeError(`Expected ${size}-bit integer, got ${value}`);
  48757. }
  48758. return expected;
  48759. };
  48760. castInt = (value, size) => {
  48761. switch (size) {
  48762. case 32:
  48763. return Int32Array.of(value)[0];
  48764. case 16:
  48765. return Int16Array.of(value)[0];
  48766. case 8:
  48767. return Int8Array.of(value)[0];
  48768. }
  48769. };
  48770. expectNonNull2 = (value, location) => {
  48771. if (value === null || value === void 0) {
  48772. if (location) {
  48773. throw new TypeError(`Expected a non-null value for ${location}`);
  48774. }
  48775. throw new TypeError("Expected a non-null value");
  48776. }
  48777. return value;
  48778. };
  48779. expectObject2 = (value) => {
  48780. if (value === null || value === void 0) {
  48781. return void 0;
  48782. }
  48783. if (typeof value === "object" && !Array.isArray(value)) {
  48784. return value;
  48785. }
  48786. const receivedType = Array.isArray(value) ? "array" : typeof value;
  48787. throw new TypeError(`Expected object, got ${receivedType}: ${value}`);
  48788. };
  48789. expectString2 = (value) => {
  48790. if (value === null || value === void 0) {
  48791. return void 0;
  48792. }
  48793. if (typeof value === "string") {
  48794. return value;
  48795. }
  48796. if (["boolean", "number", "bigint"].includes(typeof value)) {
  48797. logger2.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));
  48798. return String(value);
  48799. }
  48800. throw new TypeError(`Expected string, got ${typeof value}: ${value}`);
  48801. };
  48802. expectUnion2 = (value) => {
  48803. if (value === null || value === void 0) {
  48804. return void 0;
  48805. }
  48806. const asObject = expectObject2(value);
  48807. const setKeys = Object.entries(asObject).filter(([, v6]) => v6 != null).map(([k3]) => k3);
  48808. if (setKeys.length === 0) {
  48809. throw new TypeError(`Unions must have exactly one non-null member. None were found.`);
  48810. }
  48811. if (setKeys.length > 1) {
  48812. throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`);
  48813. }
  48814. return asObject;
  48815. };
  48816. strictParseDouble2 = (value) => {
  48817. if (typeof value == "string") {
  48818. return expectNumber2(parseNumber(value));
  48819. }
  48820. return expectNumber2(value);
  48821. };
  48822. strictParseFloat2 = strictParseDouble2;
  48823. strictParseFloat322 = (value) => {
  48824. if (typeof value == "string") {
  48825. return expectFloat322(parseNumber(value));
  48826. }
  48827. return expectFloat322(value);
  48828. };
  48829. NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;
  48830. parseNumber = (value) => {
  48831. const matches = value.match(NUMBER_REGEX);
  48832. if (matches === null || matches[0].length !== value.length) {
  48833. throw new TypeError(`Expected real number, got implicit NaN`);
  48834. }
  48835. return parseFloat(value);
  48836. };
  48837. limitedParseDouble2 = (value) => {
  48838. if (typeof value == "string") {
  48839. return parseFloatString(value);
  48840. }
  48841. return expectNumber2(value);
  48842. };
  48843. handleFloat2 = limitedParseDouble2;
  48844. limitedParseFloat2 = limitedParseDouble2;
  48845. limitedParseFloat322 = (value) => {
  48846. if (typeof value == "string") {
  48847. return parseFloatString(value);
  48848. }
  48849. return expectFloat322(value);
  48850. };
  48851. parseFloatString = (value) => {
  48852. switch (value) {
  48853. case "NaN":
  48854. return NaN;
  48855. case "Infinity":
  48856. return Infinity;
  48857. case "-Infinity":
  48858. return -Infinity;
  48859. default:
  48860. throw new Error(`Unable to parse float value: ${value}`);
  48861. }
  48862. };
  48863. strictParseLong2 = (value) => {
  48864. if (typeof value === "string") {
  48865. return expectLong2(parseNumber(value));
  48866. }
  48867. return expectLong2(value);
  48868. };
  48869. strictParseInt2 = strictParseLong2;
  48870. strictParseInt322 = (value) => {
  48871. if (typeof value === "string") {
  48872. return expectInt322(parseNumber(value));
  48873. }
  48874. return expectInt322(value);
  48875. };
  48876. strictParseShort2 = (value) => {
  48877. if (typeof value === "string") {
  48878. return expectShort2(parseNumber(value));
  48879. }
  48880. return expectShort2(value);
  48881. };
  48882. strictParseByte2 = (value) => {
  48883. if (typeof value === "string") {
  48884. return expectByte2(parseNumber(value));
  48885. }
  48886. return expectByte2(value);
  48887. };
  48888. stackTraceWarning = (message) => {
  48889. return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s4) => !s4.includes("stackTraceWarning")).join("\n");
  48890. };
  48891. logger2 = {
  48892. warn: console.warn
  48893. };
  48894. }
  48895. });
  48896. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js
  48897. function dateToUtcString2(date) {
  48898. const year = date.getUTCFullYear();
  48899. const month = date.getUTCMonth();
  48900. const dayOfWeek = date.getUTCDay();
  48901. const dayOfMonthInt = date.getUTCDate();
  48902. const hoursInt = date.getUTCHours();
  48903. const minutesInt = date.getUTCMinutes();
  48904. const secondsInt = date.getUTCSeconds();
  48905. const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`;
  48906. const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`;
  48907. const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`;
  48908. const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`;
  48909. return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`;
  48910. }
  48911. var DAYS, MONTHS, RFC3339, parseRfc3339DateTime2, RFC3339_WITH_OFFSET, parseRfc3339DateTimeWithOffset2, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, parseRfc7231DateTime2, parseEpochTimestamp2, buildDate, parseTwoDigitYear, FIFTY_YEARS_IN_MILLIS, adjustRfc850Year, parseMonthByShortName, DAYS_IN_MONTH, validateDayOfMonth, isLeapYear, parseDateValue, parseMilliseconds, parseOffsetToMilliseconds, stripLeadingZeroes;
  48912. var init_date_utils = __esm({
  48913. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js"() {
  48914. init_parse_utils();
  48915. DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  48916. MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  48917. RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);
  48918. parseRfc3339DateTime2 = (value) => {
  48919. if (value === null || value === void 0) {
  48920. return void 0;
  48921. }
  48922. if (typeof value !== "string") {
  48923. throw new TypeError("RFC-3339 date-times must be expressed as strings");
  48924. }
  48925. const match2 = RFC3339.exec(value);
  48926. if (!match2) {
  48927. throw new TypeError("Invalid RFC-3339 date-time value");
  48928. }
  48929. const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
  48930. const year = strictParseShort2(stripLeadingZeroes(yearStr));
  48931. const month = parseDateValue(monthStr, "month", 1, 12);
  48932. const day = parseDateValue(dayStr, "day", 1, 31);
  48933. return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
  48934. };
  48935. RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);
  48936. parseRfc3339DateTimeWithOffset2 = (value) => {
  48937. if (value === null || value === void 0) {
  48938. return void 0;
  48939. }
  48940. if (typeof value !== "string") {
  48941. throw new TypeError("RFC-3339 date-times must be expressed as strings");
  48942. }
  48943. const match2 = RFC3339_WITH_OFFSET.exec(value);
  48944. if (!match2) {
  48945. throw new TypeError("Invalid RFC-3339 date-time value");
  48946. }
  48947. const [_3, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match2;
  48948. const year = strictParseShort2(stripLeadingZeroes(yearStr));
  48949. const month = parseDateValue(monthStr, "month", 1, 12);
  48950. const day = parseDateValue(dayStr, "day", 1, 31);
  48951. const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds });
  48952. if (offsetStr.toUpperCase() != "Z") {
  48953. date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr));
  48954. }
  48955. return date;
  48956. };
  48957. IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
  48958. RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);
  48959. ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);
  48960. parseRfc7231DateTime2 = (value) => {
  48961. if (value === null || value === void 0) {
  48962. return void 0;
  48963. }
  48964. if (typeof value !== "string") {
  48965. throw new TypeError("RFC-7231 date-times must be expressed as strings");
  48966. }
  48967. let match2 = IMF_FIXDATE.exec(value);
  48968. if (match2) {
  48969. const [_3, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
  48970. return buildDate(strictParseShort2(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds });
  48971. }
  48972. match2 = RFC_850_DATE.exec(value);
  48973. if (match2) {
  48974. const [_3, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match2;
  48975. return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), {
  48976. hours,
  48977. minutes,
  48978. seconds,
  48979. fractionalMilliseconds
  48980. }));
  48981. }
  48982. match2 = ASC_TIME.exec(value);
  48983. if (match2) {
  48984. const [_3, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match2;
  48985. return buildDate(strictParseShort2(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds });
  48986. }
  48987. throw new TypeError("Invalid RFC-7231 date-time value");
  48988. };
  48989. parseEpochTimestamp2 = (value) => {
  48990. if (value === null || value === void 0) {
  48991. return void 0;
  48992. }
  48993. let valueAsDouble;
  48994. if (typeof value === "number") {
  48995. valueAsDouble = value;
  48996. } else if (typeof value === "string") {
  48997. valueAsDouble = strictParseDouble2(value);
  48998. } else if (typeof value === "object" && value.tag === 1) {
  48999. valueAsDouble = value.value;
  49000. } else {
  49001. throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");
  49002. }
  49003. if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) {
  49004. throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");
  49005. }
  49006. return new Date(Math.round(valueAsDouble * 1e3));
  49007. };
  49008. buildDate = (year, month, day, time) => {
  49009. const adjustedMonth = month - 1;
  49010. validateDayOfMonth(year, adjustedMonth, day);
  49011. return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds)));
  49012. };
  49013. parseTwoDigitYear = (value) => {
  49014. const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear();
  49015. const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort2(stripLeadingZeroes(value));
  49016. if (valueInThisCentury < thisYear) {
  49017. return valueInThisCentury + 100;
  49018. }
  49019. return valueInThisCentury;
  49020. };
  49021. FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3;
  49022. adjustRfc850Year = (input) => {
  49023. if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) {
  49024. return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds()));
  49025. }
  49026. return input;
  49027. };
  49028. parseMonthByShortName = (value) => {
  49029. const monthIdx = MONTHS.indexOf(value);
  49030. if (monthIdx < 0) {
  49031. throw new TypeError(`Invalid month: ${value}`);
  49032. }
  49033. return monthIdx + 1;
  49034. };
  49035. DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  49036. validateDayOfMonth = (year, month, day) => {
  49037. let maxDays = DAYS_IN_MONTH[month];
  49038. if (month === 1 && isLeapYear(year)) {
  49039. maxDays = 29;
  49040. }
  49041. if (day > maxDays) {
  49042. throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`);
  49043. }
  49044. };
  49045. isLeapYear = (year) => {
  49046. return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
  49047. };
  49048. parseDateValue = (value, type, lower2, upper) => {
  49049. const dateVal = strictParseByte2(stripLeadingZeroes(value));
  49050. if (dateVal < lower2 || dateVal > upper) {
  49051. throw new TypeError(`${type} must be between ${lower2} and ${upper}, inclusive`);
  49052. }
  49053. return dateVal;
  49054. };
  49055. parseMilliseconds = (value) => {
  49056. if (value === null || value === void 0) {
  49057. return 0;
  49058. }
  49059. return strictParseFloat322("0." + value) * 1e3;
  49060. };
  49061. parseOffsetToMilliseconds = (value) => {
  49062. const directionStr = value[0];
  49063. let direction = 1;
  49064. if (directionStr == "+") {
  49065. direction = 1;
  49066. } else if (directionStr == "-") {
  49067. direction = -1;
  49068. } else {
  49069. throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);
  49070. }
  49071. const hour = Number(value.substring(1, 3));
  49072. const minute = Number(value.substring(4, 6));
  49073. return direction * (hour * 60 + minute) * 60 * 1e3;
  49074. };
  49075. stripLeadingZeroes = (value) => {
  49076. let idx = 0;
  49077. while (idx < value.length - 1 && value.charAt(idx) === "0") {
  49078. idx++;
  49079. }
  49080. if (idx === 0) {
  49081. return value;
  49082. }
  49083. return value.slice(idx);
  49084. };
  49085. }
  49086. });
  49087. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js
  49088. var LazyJsonString2;
  49089. var init_lazy_json = __esm({
  49090. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js"() {
  49091. LazyJsonString2 = function LazyJsonString3(val2) {
  49092. const str = Object.assign(new String(val2), {
  49093. deserializeJSON() {
  49094. return JSON.parse(String(val2));
  49095. },
  49096. toString() {
  49097. return String(val2);
  49098. },
  49099. toJSON() {
  49100. return String(val2);
  49101. }
  49102. });
  49103. return str;
  49104. };
  49105. LazyJsonString2.from = (object) => {
  49106. if (object && typeof object === "object" && (object instanceof LazyJsonString2 || "deserializeJSON" in object)) {
  49107. return object;
  49108. } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) {
  49109. return LazyJsonString2(String(object));
  49110. }
  49111. return LazyJsonString2(JSON.stringify(object));
  49112. };
  49113. LazyJsonString2.fromObject = LazyJsonString2.from;
  49114. }
  49115. });
  49116. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js
  49117. function quoteHeader2(part) {
  49118. if (part.includes(",") || part.includes('"')) {
  49119. part = `"${part.replace(/"/g, '\\"')}"`;
  49120. }
  49121. return part;
  49122. }
  49123. var init_quote_header = __esm({
  49124. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js"() {
  49125. }
  49126. });
  49127. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js
  49128. function splitEvery2(value, delimiter, numDelimiters) {
  49129. if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) {
  49130. throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery.");
  49131. }
  49132. const segments = value.split(delimiter);
  49133. if (numDelimiters === 1) {
  49134. return segments;
  49135. }
  49136. const compoundSegments = [];
  49137. let currentSegment = "";
  49138. for (let i4 = 0; i4 < segments.length; i4++) {
  49139. if (currentSegment === "") {
  49140. currentSegment = segments[i4];
  49141. } else {
  49142. currentSegment += delimiter + segments[i4];
  49143. }
  49144. if ((i4 + 1) % numDelimiters === 0) {
  49145. compoundSegments.push(currentSegment);
  49146. currentSegment = "";
  49147. }
  49148. }
  49149. if (currentSegment !== "") {
  49150. compoundSegments.push(currentSegment);
  49151. }
  49152. return compoundSegments;
  49153. }
  49154. var init_split_every = __esm({
  49155. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-every.js"() {
  49156. }
  49157. });
  49158. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js
  49159. var splitHeader2;
  49160. var init_split_header = __esm({
  49161. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/split-header.js"() {
  49162. splitHeader2 = (value) => {
  49163. const z2 = value.length;
  49164. const values = [];
  49165. let withinQuotes = false;
  49166. let prevChar = void 0;
  49167. let anchor = 0;
  49168. for (let i4 = 0; i4 < z2; ++i4) {
  49169. const char = value[i4];
  49170. switch (char) {
  49171. case `"`:
  49172. if (prevChar !== "\\") {
  49173. withinQuotes = !withinQuotes;
  49174. }
  49175. break;
  49176. case ",":
  49177. if (!withinQuotes) {
  49178. values.push(value.slice(anchor, i4));
  49179. anchor = i4 + 1;
  49180. }
  49181. break;
  49182. default:
  49183. }
  49184. prevChar = char;
  49185. }
  49186. values.push(value.slice(anchor));
  49187. return values.map((v6) => {
  49188. v6 = v6.trim();
  49189. const z3 = v6.length;
  49190. if (z3 < 2) {
  49191. return v6;
  49192. }
  49193. if (v6[0] === `"` && v6[z3 - 1] === `"`) {
  49194. v6 = v6.slice(1, z3 - 1);
  49195. }
  49196. return v6.replace(/\\"/g, '"');
  49197. });
  49198. };
  49199. }
  49200. });
  49201. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js
  49202. function nv2(string2) {
  49203. return new NumericValue2(string2, "bigDecimal");
  49204. }
  49205. var NumericValue2;
  49206. var init_NumericValue = __esm({
  49207. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js"() {
  49208. NumericValue2 = class {
  49209. constructor(string2, type) {
  49210. this.string = string2;
  49211. this.type = type;
  49212. }
  49213. };
  49214. }
  49215. });
  49216. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js
  49217. var serde_exports = {};
  49218. __export(serde_exports, {
  49219. LazyJsonString: () => LazyJsonString2,
  49220. NumericValue: () => NumericValue2,
  49221. copyDocumentWithTransform: () => copyDocumentWithTransform2,
  49222. dateToUtcString: () => dateToUtcString2,
  49223. expectBoolean: () => expectBoolean2,
  49224. expectByte: () => expectByte2,
  49225. expectFloat32: () => expectFloat322,
  49226. expectInt: () => expectInt2,
  49227. expectInt32: () => expectInt322,
  49228. expectLong: () => expectLong2,
  49229. expectNonNull: () => expectNonNull2,
  49230. expectNumber: () => expectNumber2,
  49231. expectObject: () => expectObject2,
  49232. expectShort: () => expectShort2,
  49233. expectString: () => expectString2,
  49234. expectUnion: () => expectUnion2,
  49235. handleFloat: () => handleFloat2,
  49236. limitedParseDouble: () => limitedParseDouble2,
  49237. limitedParseFloat: () => limitedParseFloat2,
  49238. limitedParseFloat32: () => limitedParseFloat322,
  49239. logger: () => logger2,
  49240. nv: () => nv2,
  49241. parseBoolean: () => parseBoolean2,
  49242. parseEpochTimestamp: () => parseEpochTimestamp2,
  49243. parseRfc3339DateTime: () => parseRfc3339DateTime2,
  49244. parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset2,
  49245. parseRfc7231DateTime: () => parseRfc7231DateTime2,
  49246. quoteHeader: () => quoteHeader2,
  49247. splitEvery: () => splitEvery2,
  49248. splitHeader: () => splitHeader2,
  49249. strictParseByte: () => strictParseByte2,
  49250. strictParseDouble: () => strictParseDouble2,
  49251. strictParseFloat: () => strictParseFloat2,
  49252. strictParseFloat32: () => strictParseFloat322,
  49253. strictParseInt: () => strictParseInt2,
  49254. strictParseInt32: () => strictParseInt322,
  49255. strictParseLong: () => strictParseLong2,
  49256. strictParseShort: () => strictParseShort2
  49257. });
  49258. var init_serde = __esm({
  49259. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/serde/index.js"() {
  49260. init_copyDocumentWithTransform();
  49261. init_date_utils();
  49262. init_lazy_json();
  49263. init_parse_utils();
  49264. init_quote_header();
  49265. init_split_every();
  49266. init_split_header();
  49267. init_NumericValue();
  49268. }
  49269. });
  49270. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js
  49271. var import_protocol_http3, import_util_stream2, HttpProtocol;
  49272. var init_HttpProtocol = __esm({
  49273. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() {
  49274. init_schema();
  49275. init_serde();
  49276. import_protocol_http3 = __toESM(require_dist_cjs2());
  49277. import_util_stream2 = __toESM(require_dist_cjs17());
  49278. init_collect_stream_body();
  49279. HttpProtocol = class {
  49280. constructor(options) {
  49281. this.options = options;
  49282. }
  49283. getRequestType() {
  49284. return import_protocol_http3.HttpRequest;
  49285. }
  49286. getResponseType() {
  49287. return import_protocol_http3.HttpResponse;
  49288. }
  49289. setSerdeContext(serdeContext) {
  49290. this.serdeContext = serdeContext;
  49291. this.serializer.setSerdeContext(serdeContext);
  49292. this.deserializer.setSerdeContext(serdeContext);
  49293. if (this.getPayloadCodec()) {
  49294. this.getPayloadCodec().setSerdeContext(serdeContext);
  49295. }
  49296. }
  49297. updateServiceEndpoint(request, endpoint) {
  49298. if ("url" in endpoint) {
  49299. request.protocol = endpoint.url.protocol;
  49300. request.hostname = endpoint.url.hostname;
  49301. request.port = endpoint.url.port ? Number(endpoint.url.port) : void 0;
  49302. request.path = endpoint.url.pathname;
  49303. request.fragment = endpoint.url.hash || void 0;
  49304. request.username = endpoint.url.username || void 0;
  49305. request.password = endpoint.url.password || void 0;
  49306. for (const [k3, v6] of endpoint.url.searchParams.entries()) {
  49307. if (!request.query) {
  49308. request.query = {};
  49309. }
  49310. request.query[k3] = v6;
  49311. }
  49312. return request;
  49313. } else {
  49314. request.protocol = endpoint.protocol;
  49315. request.hostname = endpoint.hostname;
  49316. request.port = endpoint.port ? Number(endpoint.port) : void 0;
  49317. request.path = endpoint.path;
  49318. request.query = {
  49319. ...endpoint.query
  49320. };
  49321. return request;
  49322. }
  49323. }
  49324. setHostPrefix(request, operationSchema, input) {
  49325. var _a2;
  49326. const operationNs = NormalizedSchema.of(operationSchema);
  49327. const inputNs = NormalizedSchema.of(operationSchema.input);
  49328. if (operationNs.getMergedTraits().endpoint) {
  49329. let hostPrefix = (_a2 = operationNs.getMergedTraits().endpoint) == null ? void 0 : _a2[0];
  49330. if (typeof hostPrefix === "string") {
  49331. const hostLabelInputs = [...inputNs.structIterator()].filter(([, member]) => member.getMergedTraits().hostLabel);
  49332. for (const [name] of hostLabelInputs) {
  49333. const replacement = input[name];
  49334. if (typeof replacement !== "string") {
  49335. throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`);
  49336. }
  49337. hostPrefix = hostPrefix.replace(`{${name}}`, replacement);
  49338. }
  49339. request.hostname = hostPrefix + request.hostname;
  49340. }
  49341. }
  49342. }
  49343. deserializeMetadata(output) {
  49344. return {
  49345. httpStatusCode: output.statusCode,
  49346. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  49347. extendedRequestId: output.headers["x-amz-id-2"],
  49348. cfId: output.headers["x-amz-cf-id"]
  49349. };
  49350. }
  49351. async deserializeHttpMessage(schema6, context, response, headerBindings, dataObject) {
  49352. const deserializer = this.deserializer;
  49353. const ns = NormalizedSchema.of(schema6);
  49354. const nonHttpBindingMembers = [];
  49355. for (const [memberName, memberSchema] of ns.structIterator()) {
  49356. const memberTraits = memberSchema.getMemberTraits();
  49357. if (memberTraits.httpPayload) {
  49358. const isStreaming = memberSchema.isStreaming();
  49359. if (isStreaming) {
  49360. const isEventStream = memberSchema.isStructSchema();
  49361. if (isEventStream) {
  49362. const context2 = this.serdeContext;
  49363. if (!context2.eventStreamMarshaller) {
  49364. throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");
  49365. }
  49366. const memberSchemas = memberSchema.getMemberSchemas();
  49367. dataObject[memberName] = context2.eventStreamMarshaller.deserialize(response.body, async (event) => {
  49368. const unionMember = Object.keys(event).find((key) => {
  49369. return key !== "__type";
  49370. }) ?? "";
  49371. if (unionMember in memberSchemas) {
  49372. const eventStreamSchema = memberSchemas[unionMember];
  49373. return {
  49374. [unionMember]: await deserializer.read(eventStreamSchema, event[unionMember].body)
  49375. };
  49376. } else {
  49377. return {
  49378. $unknown: event
  49379. };
  49380. }
  49381. });
  49382. } else {
  49383. dataObject[memberName] = (0, import_util_stream2.sdkStreamMixin)(response.body);
  49384. }
  49385. } else if (response.body) {
  49386. const bytes = await collectBody2(response.body, context);
  49387. if (bytes.byteLength > 0) {
  49388. dataObject[memberName] = await deserializer.read(memberSchema, bytes);
  49389. }
  49390. }
  49391. } else if (memberTraits.httpHeader) {
  49392. const key = String(memberTraits.httpHeader).toLowerCase();
  49393. const value = response.headers[key];
  49394. if (null != value) {
  49395. if (memberSchema.isListSchema()) {
  49396. const headerListValueSchema = memberSchema.getValueSchema();
  49397. let sections;
  49398. if (headerListValueSchema.isTimestampSchema() && headerListValueSchema.getSchema() === SCHEMA.TIMESTAMP_DEFAULT) {
  49399. sections = splitEvery2(value, ",", 2);
  49400. } else {
  49401. sections = splitHeader2(value);
  49402. }
  49403. const list = [];
  49404. for (const section of sections) {
  49405. list.push(await deserializer.read([headerListValueSchema, { httpHeader: key }], section.trim()));
  49406. }
  49407. dataObject[memberName] = list;
  49408. } else {
  49409. dataObject[memberName] = await deserializer.read(memberSchema, value);
  49410. }
  49411. }
  49412. } else if (memberTraits.httpPrefixHeaders !== void 0) {
  49413. dataObject[memberName] = {};
  49414. for (const [header, value] of Object.entries(response.headers)) {
  49415. if (!headerBindings.has(header) && header.startsWith(memberTraits.httpPrefixHeaders)) {
  49416. dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read([memberSchema.getValueSchema(), { httpHeader: header }], value);
  49417. }
  49418. }
  49419. } else if (memberTraits.httpResponseCode) {
  49420. dataObject[memberName] = response.statusCode;
  49421. } else {
  49422. nonHttpBindingMembers.push(memberName);
  49423. }
  49424. }
  49425. return nonHttpBindingMembers;
  49426. }
  49427. };
  49428. }
  49429. });
  49430. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js
  49431. var import_protocol_http4, HttpBindingProtocol;
  49432. var init_HttpBindingProtocol = __esm({
  49433. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js"() {
  49434. init_schema();
  49435. import_protocol_http4 = __toESM(require_dist_cjs2());
  49436. init_collect_stream_body();
  49437. init_extended_encode_uri_component();
  49438. init_HttpProtocol();
  49439. HttpBindingProtocol = class extends HttpProtocol {
  49440. async serializeRequest(operationSchema, input, context) {
  49441. const serializer = this.serializer;
  49442. const query = {};
  49443. const headers = {};
  49444. const endpoint = await context.endpoint();
  49445. const ns = NormalizedSchema.of(operationSchema == null ? void 0 : operationSchema.input);
  49446. const schema6 = ns.getSchema();
  49447. let hasNonHttpBindingMember = false;
  49448. let payload;
  49449. const request = new import_protocol_http4.HttpRequest({
  49450. protocol: "",
  49451. hostname: "",
  49452. port: void 0,
  49453. path: "",
  49454. fragment: void 0,
  49455. query,
  49456. headers,
  49457. body: void 0
  49458. });
  49459. if (endpoint) {
  49460. this.updateServiceEndpoint(request, endpoint);
  49461. this.setHostPrefix(request, operationSchema, input);
  49462. const opTraits = NormalizedSchema.translateTraits(operationSchema.traits);
  49463. if (opTraits.http) {
  49464. request.method = opTraits.http[0];
  49465. const [path4, search] = opTraits.http[1].split("?");
  49466. if (request.path == "/") {
  49467. request.path = path4;
  49468. } else {
  49469. request.path += path4;
  49470. }
  49471. const traitSearchParams = new URLSearchParams(search ?? "");
  49472. Object.assign(query, Object.fromEntries(traitSearchParams));
  49473. }
  49474. }
  49475. const _input = {
  49476. ...input
  49477. };
  49478. for (const memberName of Object.keys(_input)) {
  49479. const memberNs = ns.getMemberSchema(memberName);
  49480. if (memberNs === void 0) {
  49481. continue;
  49482. }
  49483. const memberTraits = memberNs.getMergedTraits();
  49484. const inputMember = _input[memberName];
  49485. if (memberTraits.httpPayload) {
  49486. const isStreaming = memberNs.isStreaming();
  49487. if (isStreaming) {
  49488. const isEventStream = memberNs.isStructSchema();
  49489. if (isEventStream) {
  49490. throw new Error("serialization of event streams is not yet implemented");
  49491. } else {
  49492. payload = inputMember;
  49493. }
  49494. } else {
  49495. serializer.write(memberNs, inputMember);
  49496. payload = serializer.flush();
  49497. }
  49498. } else if (memberTraits.httpLabel) {
  49499. serializer.write(memberNs, inputMember);
  49500. const replacement = serializer.flush();
  49501. if (request.path.includes(`{${memberName}+}`)) {
  49502. request.path = request.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent2).join("/"));
  49503. } else if (request.path.includes(`{${memberName}}`)) {
  49504. request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent2(replacement));
  49505. }
  49506. delete _input[memberName];
  49507. } else if (memberTraits.httpHeader) {
  49508. serializer.write(memberNs, inputMember);
  49509. headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush());
  49510. delete _input[memberName];
  49511. } else if (typeof memberTraits.httpPrefixHeaders === "string") {
  49512. for (const [key, val2] of Object.entries(inputMember)) {
  49513. const amalgam = memberTraits.httpPrefixHeaders + key;
  49514. serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val2);
  49515. headers[amalgam.toLowerCase()] = serializer.flush();
  49516. }
  49517. delete _input[memberName];
  49518. } else if (memberTraits.httpQuery || memberTraits.httpQueryParams) {
  49519. this.serializeQuery(memberNs, inputMember, query);
  49520. delete _input[memberName];
  49521. } else {
  49522. hasNonHttpBindingMember = true;
  49523. }
  49524. }
  49525. if (hasNonHttpBindingMember && input) {
  49526. serializer.write(schema6, _input);
  49527. payload = serializer.flush();
  49528. }
  49529. request.headers = headers;
  49530. request.query = query;
  49531. request.body = payload;
  49532. return request;
  49533. }
  49534. serializeQuery(ns, data, query) {
  49535. const serializer = this.serializer;
  49536. const traits = ns.getMergedTraits();
  49537. if (traits.httpQueryParams) {
  49538. for (const [key, val2] of Object.entries(data)) {
  49539. if (!(key in query)) {
  49540. this.serializeQuery(NormalizedSchema.of([
  49541. ns.getValueSchema(),
  49542. {
  49543. ...traits,
  49544. httpQuery: key,
  49545. httpQueryParams: void 0
  49546. }
  49547. ]), val2, query);
  49548. }
  49549. }
  49550. return;
  49551. }
  49552. if (ns.isListSchema()) {
  49553. const sparse = !!ns.getMergedTraits().sparse;
  49554. const buffer = [];
  49555. for (const item of data) {
  49556. serializer.write([ns.getValueSchema(), traits], item);
  49557. const serializable = serializer.flush();
  49558. if (sparse || serializable !== void 0) {
  49559. buffer.push(serializable);
  49560. }
  49561. }
  49562. query[traits.httpQuery] = buffer;
  49563. } else {
  49564. serializer.write([ns, traits], data);
  49565. query[traits.httpQuery] = serializer.flush();
  49566. }
  49567. }
  49568. async deserializeResponse(operationSchema, context, response) {
  49569. const deserializer = this.deserializer;
  49570. const ns = NormalizedSchema.of(operationSchema.output);
  49571. const dataObject = {};
  49572. if (response.statusCode >= 300) {
  49573. const bytes = await collectBody2(response.body, context);
  49574. if (bytes.byteLength > 0) {
  49575. Object.assign(dataObject, await deserializer.read(SCHEMA.DOCUMENT, bytes));
  49576. }
  49577. await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response));
  49578. throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.");
  49579. }
  49580. for (const header in response.headers) {
  49581. const value = response.headers[header];
  49582. delete response.headers[header];
  49583. response.headers[header.toLowerCase()] = value;
  49584. }
  49585. const headerBindings = new Set(Object.values(ns.getMemberSchemas()).map((schema6) => {
  49586. return schema6.getMergedTraits().httpHeader;
  49587. }).filter(Boolean));
  49588. const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, headerBindings, dataObject);
  49589. if (nonHttpBindingMembers.length) {
  49590. const bytes = await collectBody2(response.body, context);
  49591. if (bytes.byteLength > 0) {
  49592. const dataFromBody = await deserializer.read(ns, bytes);
  49593. for (const member of nonHttpBindingMembers) {
  49594. dataObject[member] = dataFromBody[member];
  49595. }
  49596. }
  49597. }
  49598. const output = {
  49599. $metadata: this.deserializeMetadata(response),
  49600. ...dataObject
  49601. };
  49602. return output;
  49603. }
  49604. };
  49605. }
  49606. });
  49607. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js
  49608. var import_protocol_http5, RpcProtocol;
  49609. var init_RpcProtocol = __esm({
  49610. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js"() {
  49611. init_schema();
  49612. import_protocol_http5 = __toESM(require_dist_cjs2());
  49613. init_collect_stream_body();
  49614. init_HttpProtocol();
  49615. RpcProtocol = class extends HttpProtocol {
  49616. async serializeRequest(operationSchema, input, context) {
  49617. const serializer = this.serializer;
  49618. const query = {};
  49619. const headers = {};
  49620. const endpoint = await context.endpoint();
  49621. const ns = NormalizedSchema.of(operationSchema == null ? void 0 : operationSchema.input);
  49622. const schema6 = ns.getSchema();
  49623. let payload;
  49624. const request = new import_protocol_http5.HttpRequest({
  49625. protocol: "",
  49626. hostname: "",
  49627. port: void 0,
  49628. path: "/",
  49629. fragment: void 0,
  49630. query,
  49631. headers,
  49632. body: void 0
  49633. });
  49634. if (endpoint) {
  49635. this.updateServiceEndpoint(request, endpoint);
  49636. this.setHostPrefix(request, operationSchema, input);
  49637. }
  49638. const _input = {
  49639. ...input
  49640. };
  49641. if (input) {
  49642. serializer.write(schema6, _input);
  49643. payload = serializer.flush();
  49644. }
  49645. request.headers = headers;
  49646. request.query = query;
  49647. request.body = payload;
  49648. request.method = "POST";
  49649. return request;
  49650. }
  49651. async deserializeResponse(operationSchema, context, response) {
  49652. const deserializer = this.deserializer;
  49653. const ns = NormalizedSchema.of(operationSchema.output);
  49654. const dataObject = {};
  49655. if (response.statusCode >= 300) {
  49656. const bytes2 = await collectBody2(response.body, context);
  49657. if (bytes2.byteLength > 0) {
  49658. Object.assign(dataObject, await deserializer.read(SCHEMA.DOCUMENT, bytes2));
  49659. }
  49660. await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response));
  49661. throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.");
  49662. }
  49663. for (const header in response.headers) {
  49664. const value = response.headers[header];
  49665. delete response.headers[header];
  49666. response.headers[header.toLowerCase()] = value;
  49667. }
  49668. const bytes = await collectBody2(response.body, context);
  49669. if (bytes.byteLength > 0) {
  49670. Object.assign(dataObject, await deserializer.read(ns, bytes));
  49671. }
  49672. const output = {
  49673. $metadata: this.deserializeMetadata(response),
  49674. ...dataObject
  49675. };
  49676. return output;
  49677. }
  49678. };
  49679. }
  49680. });
  49681. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js
  49682. var resolvedPath2;
  49683. var init_resolve_path = __esm({
  49684. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js"() {
  49685. init_extended_encode_uri_component();
  49686. resolvedPath2 = (resolvedPath3, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {
  49687. if (input != null && input[memberName] !== void 0) {
  49688. const labelValue = labelValueProvider();
  49689. if (labelValue.length <= 0) {
  49690. throw new Error("Empty value provided for input HTTP label: " + memberName + ".");
  49691. }
  49692. resolvedPath3 = resolvedPath3.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent2(segment)).join("/") : extendedEncodeURIComponent2(labelValue));
  49693. } else {
  49694. throw new Error("No value provided for input HTTP label: " + memberName + ".");
  49695. }
  49696. return resolvedPath3;
  49697. };
  49698. }
  49699. });
  49700. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js
  49701. function requestBuilder(input, context) {
  49702. return new RequestBuilder(input, context);
  49703. }
  49704. var import_protocol_http6, RequestBuilder;
  49705. var init_requestBuilder = __esm({
  49706. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js"() {
  49707. import_protocol_http6 = __toESM(require_dist_cjs2());
  49708. init_resolve_path();
  49709. RequestBuilder = class {
  49710. constructor(input, context) {
  49711. this.input = input;
  49712. this.context = context;
  49713. this.query = {};
  49714. this.method = "";
  49715. this.headers = {};
  49716. this.path = "";
  49717. this.body = null;
  49718. this.hostname = "";
  49719. this.resolvePathStack = [];
  49720. }
  49721. async build() {
  49722. const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint();
  49723. this.path = basePath;
  49724. for (const resolvePath of this.resolvePathStack) {
  49725. resolvePath(this.path);
  49726. }
  49727. return new import_protocol_http6.HttpRequest({
  49728. protocol,
  49729. hostname: this.hostname || hostname,
  49730. port,
  49731. method: this.method,
  49732. path: this.path,
  49733. query: this.query,
  49734. body: this.body,
  49735. headers: this.headers
  49736. });
  49737. }
  49738. hn(hostname) {
  49739. this.hostname = hostname;
  49740. return this;
  49741. }
  49742. bp(uriLabel) {
  49743. this.resolvePathStack.push((basePath) => {
  49744. this.path = `${(basePath == null ? void 0 : basePath.endsWith("/")) ? basePath.slice(0, -1) : basePath || ""}` + uriLabel;
  49745. });
  49746. return this;
  49747. }
  49748. p(memberName, labelValueProvider, uriLabel, isGreedyLabel) {
  49749. this.resolvePathStack.push((path4) => {
  49750. this.path = resolvedPath2(path4, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel);
  49751. });
  49752. return this;
  49753. }
  49754. h(headers) {
  49755. this.headers = headers;
  49756. return this;
  49757. }
  49758. q(query) {
  49759. this.query = query;
  49760. return this;
  49761. }
  49762. b(body) {
  49763. this.body = body;
  49764. return this;
  49765. }
  49766. m(method) {
  49767. this.method = method;
  49768. return this;
  49769. }
  49770. };
  49771. }
  49772. });
  49773. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js
  49774. function determineTimestampFormat(ns, settings) {
  49775. if (settings.timestampFormat.useTrait) {
  49776. if (ns.isTimestampSchema() && (ns.getSchema() === SCHEMA.TIMESTAMP_DATE_TIME || ns.getSchema() === SCHEMA.TIMESTAMP_HTTP_DATE || ns.getSchema() === SCHEMA.TIMESTAMP_EPOCH_SECONDS)) {
  49777. return ns.getSchema();
  49778. }
  49779. }
  49780. const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits();
  49781. const bindingFormat = settings.httpBindings ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) ? SCHEMA.TIMESTAMP_HTTP_DATE : Boolean(httpQuery) || Boolean(httpLabel) ? SCHEMA.TIMESTAMP_DATE_TIME : void 0 : void 0;
  49782. return bindingFormat ?? settings.timestampFormat.default;
  49783. }
  49784. var init_determineTimestampFormat = __esm({
  49785. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js"() {
  49786. init_schema();
  49787. }
  49788. });
  49789. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js
  49790. var import_util_base64, import_util_utf8, FromStringShapeDeserializer;
  49791. var init_FromStringShapeDeserializer = __esm({
  49792. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js"() {
  49793. init_schema();
  49794. init_serde();
  49795. import_util_base64 = __toESM(require_dist_cjs11());
  49796. import_util_utf8 = __toESM(require_dist_cjs10());
  49797. init_determineTimestampFormat();
  49798. FromStringShapeDeserializer = class {
  49799. constructor(settings) {
  49800. this.settings = settings;
  49801. }
  49802. setSerdeContext(serdeContext) {
  49803. this.serdeContext = serdeContext;
  49804. }
  49805. read(_schema, data) {
  49806. var _a2;
  49807. const ns = NormalizedSchema.of(_schema);
  49808. if (ns.isListSchema()) {
  49809. return splitHeader2(data).map((item) => this.read(ns.getValueSchema(), item));
  49810. }
  49811. if (ns.isBlobSchema()) {
  49812. return (((_a2 = this.serdeContext) == null ? void 0 : _a2.base64Decoder) ?? import_util_base64.fromBase64)(data);
  49813. }
  49814. if (ns.isTimestampSchema()) {
  49815. const format = determineTimestampFormat(ns, this.settings);
  49816. switch (format) {
  49817. case SCHEMA.TIMESTAMP_DATE_TIME:
  49818. return parseRfc3339DateTimeWithOffset2(data);
  49819. case SCHEMA.TIMESTAMP_HTTP_DATE:
  49820. return parseRfc7231DateTime2(data);
  49821. case SCHEMA.TIMESTAMP_EPOCH_SECONDS:
  49822. return parseEpochTimestamp2(data);
  49823. default:
  49824. console.warn("Missing timestamp format, parsing value with Date constructor:", data);
  49825. return new Date(data);
  49826. }
  49827. }
  49828. if (ns.isStringSchema()) {
  49829. const mediaType = ns.getMergedTraits().mediaType;
  49830. let intermediateValue = data;
  49831. if (mediaType) {
  49832. if (ns.getMergedTraits().httpHeader) {
  49833. intermediateValue = this.base64ToUtf8(intermediateValue);
  49834. }
  49835. const isJson = mediaType === "application/json" || mediaType.endsWith("+json");
  49836. if (isJson) {
  49837. intermediateValue = LazyJsonString2.from(intermediateValue);
  49838. }
  49839. return intermediateValue;
  49840. }
  49841. }
  49842. switch (true) {
  49843. case ns.isNumericSchema():
  49844. return Number(data);
  49845. case ns.isBigIntegerSchema():
  49846. return BigInt(data);
  49847. case ns.isBigDecimalSchema():
  49848. return new NumericValue2(data, "bigDecimal");
  49849. case ns.isBooleanSchema():
  49850. return String(data).toLowerCase() === "true";
  49851. }
  49852. return data;
  49853. }
  49854. base64ToUtf8(base64String) {
  49855. var _a2, _b;
  49856. return (((_a2 = this.serdeContext) == null ? void 0 : _a2.utf8Encoder) ?? import_util_utf8.toUtf8)((((_b = this.serdeContext) == null ? void 0 : _b.base64Decoder) ?? import_util_base64.fromBase64)(base64String));
  49857. }
  49858. };
  49859. }
  49860. });
  49861. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js
  49862. var import_util_utf82, HttpInterceptingShapeDeserializer;
  49863. var init_HttpInterceptingShapeDeserializer = __esm({
  49864. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() {
  49865. init_schema();
  49866. import_util_utf82 = __toESM(require_dist_cjs10());
  49867. init_FromStringShapeDeserializer();
  49868. HttpInterceptingShapeDeserializer = class {
  49869. constructor(codecDeserializer, codecSettings) {
  49870. this.codecDeserializer = codecDeserializer;
  49871. this.stringDeserializer = new FromStringShapeDeserializer(codecSettings);
  49872. }
  49873. setSerdeContext(serdeContext) {
  49874. this.stringDeserializer.setSerdeContext(serdeContext);
  49875. this.codecDeserializer.setSerdeContext(serdeContext);
  49876. this.serdeContext = serdeContext;
  49877. }
  49878. read(schema6, data) {
  49879. var _a2, _b;
  49880. const ns = NormalizedSchema.of(schema6);
  49881. const traits = ns.getMergedTraits();
  49882. const toString = ((_a2 = this.serdeContext) == null ? void 0 : _a2.utf8Encoder) ?? import_util_utf82.toUtf8;
  49883. if (traits.httpHeader || traits.httpResponseCode) {
  49884. return this.stringDeserializer.read(ns, toString(data));
  49885. }
  49886. if (traits.httpPayload) {
  49887. if (ns.isBlobSchema()) {
  49888. const toBytes = ((_b = this.serdeContext) == null ? void 0 : _b.utf8Decoder) ?? import_util_utf82.fromUtf8;
  49889. if (typeof data === "string") {
  49890. return toBytes(data);
  49891. }
  49892. return data;
  49893. } else if (ns.isStringSchema()) {
  49894. if ("byteLength" in data) {
  49895. return toString(data);
  49896. }
  49897. return data;
  49898. }
  49899. }
  49900. return this.codecDeserializer.read(ns, data);
  49901. }
  49902. };
  49903. }
  49904. });
  49905. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js
  49906. var import_util_base642, ToStringShapeSerializer;
  49907. var init_ToStringShapeSerializer = __esm({
  49908. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js"() {
  49909. init_schema();
  49910. init_serde();
  49911. import_util_base642 = __toESM(require_dist_cjs11());
  49912. init_determineTimestampFormat();
  49913. ToStringShapeSerializer = class {
  49914. constructor(settings) {
  49915. this.settings = settings;
  49916. this.stringBuffer = "";
  49917. this.serdeContext = void 0;
  49918. }
  49919. setSerdeContext(serdeContext) {
  49920. this.serdeContext = serdeContext;
  49921. }
  49922. write(schema6, value) {
  49923. var _a2, _b;
  49924. const ns = NormalizedSchema.of(schema6);
  49925. switch (typeof value) {
  49926. case "object":
  49927. if (value === null) {
  49928. this.stringBuffer = "null";
  49929. return;
  49930. }
  49931. if (ns.isTimestampSchema()) {
  49932. if (!(value instanceof Date)) {
  49933. throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`);
  49934. }
  49935. const format = determineTimestampFormat(ns, this.settings);
  49936. switch (format) {
  49937. case SCHEMA.TIMESTAMP_DATE_TIME:
  49938. this.stringBuffer = value.toISOString().replace(".000Z", "Z");
  49939. break;
  49940. case SCHEMA.TIMESTAMP_HTTP_DATE:
  49941. this.stringBuffer = dateToUtcString2(value);
  49942. break;
  49943. case SCHEMA.TIMESTAMP_EPOCH_SECONDS:
  49944. this.stringBuffer = String(value.getTime() / 1e3);
  49945. break;
  49946. default:
  49947. console.warn("Missing timestamp format, using epoch seconds", value);
  49948. this.stringBuffer = String(value.getTime() / 1e3);
  49949. }
  49950. return;
  49951. }
  49952. if (ns.isBlobSchema() && "byteLength" in value) {
  49953. this.stringBuffer = (((_a2 = this.serdeContext) == null ? void 0 : _a2.base64Encoder) ?? import_util_base642.toBase64)(value);
  49954. return;
  49955. }
  49956. if (ns.isListSchema() && Array.isArray(value)) {
  49957. let buffer = "";
  49958. for (const item of value) {
  49959. this.write([ns.getValueSchema(), ns.getMergedTraits()], item);
  49960. const headerItem = this.flush();
  49961. const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : quoteHeader2(headerItem);
  49962. if (buffer !== "") {
  49963. buffer += ", ";
  49964. }
  49965. buffer += serialized;
  49966. }
  49967. this.stringBuffer = buffer;
  49968. return;
  49969. }
  49970. this.stringBuffer = JSON.stringify(value, null, 2);
  49971. break;
  49972. case "string":
  49973. const mediaType = ns.getMergedTraits().mediaType;
  49974. let intermediateValue = value;
  49975. if (mediaType) {
  49976. const isJson = mediaType === "application/json" || mediaType.endsWith("+json");
  49977. if (isJson) {
  49978. intermediateValue = LazyJsonString2.from(intermediateValue);
  49979. }
  49980. if (ns.getMergedTraits().httpHeader) {
  49981. this.stringBuffer = (((_b = this.serdeContext) == null ? void 0 : _b.base64Encoder) ?? import_util_base642.toBase64)(intermediateValue.toString());
  49982. return;
  49983. }
  49984. }
  49985. this.stringBuffer = value;
  49986. break;
  49987. default:
  49988. this.stringBuffer = String(value);
  49989. }
  49990. }
  49991. flush() {
  49992. const buffer = this.stringBuffer;
  49993. this.stringBuffer = "";
  49994. return buffer;
  49995. }
  49996. };
  49997. }
  49998. });
  49999. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js
  50000. var HttpInterceptingShapeSerializer;
  50001. var init_HttpInterceptingShapeSerializer = __esm({
  50002. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js"() {
  50003. init_schema();
  50004. init_ToStringShapeSerializer();
  50005. HttpInterceptingShapeSerializer = class {
  50006. constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) {
  50007. this.codecSerializer = codecSerializer;
  50008. this.stringSerializer = stringSerializer;
  50009. }
  50010. setSerdeContext(serdeContext) {
  50011. this.codecSerializer.setSerdeContext(serdeContext);
  50012. this.stringSerializer.setSerdeContext(serdeContext);
  50013. }
  50014. write(schema6, value) {
  50015. const ns = NormalizedSchema.of(schema6);
  50016. const traits = ns.getMergedTraits();
  50017. if (traits.httpHeader || traits.httpLabel || traits.httpQuery) {
  50018. this.stringSerializer.write(ns, value);
  50019. this.buffer = this.stringSerializer.flush();
  50020. return;
  50021. }
  50022. return this.codecSerializer.write(ns, value);
  50023. }
  50024. flush() {
  50025. if (this.buffer !== void 0) {
  50026. const buffer = this.buffer;
  50027. this.buffer = void 0;
  50028. return buffer;
  50029. }
  50030. return this.codecSerializer.flush();
  50031. }
  50032. };
  50033. }
  50034. });
  50035. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js
  50036. var protocols_exports = {};
  50037. __export(protocols_exports, {
  50038. FromStringShapeDeserializer: () => FromStringShapeDeserializer,
  50039. HttpBindingProtocol: () => HttpBindingProtocol,
  50040. HttpInterceptingShapeDeserializer: () => HttpInterceptingShapeDeserializer,
  50041. HttpInterceptingShapeSerializer: () => HttpInterceptingShapeSerializer,
  50042. RequestBuilder: () => RequestBuilder,
  50043. RpcProtocol: () => RpcProtocol,
  50044. ToStringShapeSerializer: () => ToStringShapeSerializer,
  50045. collectBody: () => collectBody2,
  50046. determineTimestampFormat: () => determineTimestampFormat,
  50047. extendedEncodeURIComponent: () => extendedEncodeURIComponent2,
  50048. requestBuilder: () => requestBuilder,
  50049. resolvedPath: () => resolvedPath2
  50050. });
  50051. var init_protocols = __esm({
  50052. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/submodules/protocols/index.js"() {
  50053. init_collect_stream_body();
  50054. init_extended_encode_uri_component();
  50055. init_HttpBindingProtocol();
  50056. init_RpcProtocol();
  50057. init_requestBuilder();
  50058. init_resolve_path();
  50059. init_FromStringShapeDeserializer();
  50060. init_HttpInterceptingShapeDeserializer();
  50061. init_HttpInterceptingShapeSerializer();
  50062. init_ToStringShapeSerializer();
  50063. init_determineTimestampFormat();
  50064. }
  50065. });
  50066. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js
  50067. var init_requestBuilder2 = __esm({
  50068. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() {
  50069. init_protocols();
  50070. }
  50071. });
  50072. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js
  50073. function setFeature(context, feature, value) {
  50074. if (!context.__smithy_context) {
  50075. context.__smithy_context = {
  50076. features: {}
  50077. };
  50078. } else if (!context.__smithy_context.features) {
  50079. context.__smithy_context.features = {};
  50080. }
  50081. context.__smithy_context.features[feature] = value;
  50082. }
  50083. var init_setFeature = __esm({
  50084. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/setFeature.js"() {
  50085. }
  50086. });
  50087. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js
  50088. var DefaultIdentityProviderConfig;
  50089. var init_DefaultIdentityProviderConfig = __esm({
  50090. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() {
  50091. DefaultIdentityProviderConfig = class {
  50092. constructor(config) {
  50093. this.authSchemes = /* @__PURE__ */ new Map();
  50094. for (const [key, value] of Object.entries(config)) {
  50095. if (value !== void 0) {
  50096. this.authSchemes.set(key, value);
  50097. }
  50098. }
  50099. }
  50100. getIdentityProvider(schemeId) {
  50101. return this.authSchemes.get(schemeId);
  50102. }
  50103. };
  50104. }
  50105. });
  50106. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js
  50107. var import_protocol_http7, import_types4, HttpApiKeyAuthSigner;
  50108. var init_httpApiKeyAuth = __esm({
  50109. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() {
  50110. import_protocol_http7 = __toESM(require_dist_cjs2());
  50111. import_types4 = __toESM(require_dist_cjs());
  50112. HttpApiKeyAuthSigner = class {
  50113. async sign(httpRequest, identity, signingProperties) {
  50114. if (!signingProperties) {
  50115. throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");
  50116. }
  50117. if (!signingProperties.name) {
  50118. throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing");
  50119. }
  50120. if (!signingProperties.in) {
  50121. throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing");
  50122. }
  50123. if (!identity.apiKey) {
  50124. throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined");
  50125. }
  50126. const clonedRequest = import_protocol_http7.HttpRequest.clone(httpRequest);
  50127. if (signingProperties.in === import_types4.HttpApiKeyAuthLocation.QUERY) {
  50128. clonedRequest.query[signingProperties.name] = identity.apiKey;
  50129. } else if (signingProperties.in === import_types4.HttpApiKeyAuthLocation.HEADER) {
  50130. clonedRequest.headers[signingProperties.name] = signingProperties.scheme ? `${signingProperties.scheme} ${identity.apiKey}` : identity.apiKey;
  50131. } else {
  50132. throw new Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `" + signingProperties.in + "`");
  50133. }
  50134. return clonedRequest;
  50135. }
  50136. };
  50137. }
  50138. });
  50139. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js
  50140. var import_protocol_http8, HttpBearerAuthSigner;
  50141. var init_httpBearerAuth = __esm({
  50142. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() {
  50143. import_protocol_http8 = __toESM(require_dist_cjs2());
  50144. HttpBearerAuthSigner = class {
  50145. async sign(httpRequest, identity, signingProperties) {
  50146. const clonedRequest = import_protocol_http8.HttpRequest.clone(httpRequest);
  50147. if (!identity.token) {
  50148. throw new Error("request could not be signed with `token` since the `token` is not defined");
  50149. }
  50150. clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`;
  50151. return clonedRequest;
  50152. }
  50153. };
  50154. }
  50155. });
  50156. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js
  50157. var NoAuthSigner;
  50158. var init_noAuth = __esm({
  50159. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() {
  50160. NoAuthSigner = class {
  50161. async sign(httpRequest, identity, signingProperties) {
  50162. return httpRequest;
  50163. }
  50164. };
  50165. }
  50166. });
  50167. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js
  50168. var init_httpAuthSchemes = __esm({
  50169. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() {
  50170. init_httpApiKeyAuth();
  50171. init_httpBearerAuth();
  50172. init_noAuth();
  50173. }
  50174. });
  50175. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js
  50176. var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider;
  50177. var init_memoizeIdentityProvider = __esm({
  50178. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() {
  50179. createIsIdentityExpiredFunction = (expirationMs) => (identity) => doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs;
  50180. EXPIRATION_MS = 3e5;
  50181. isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);
  50182. doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0;
  50183. memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => {
  50184. if (provider === void 0) {
  50185. return void 0;
  50186. }
  50187. const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
  50188. let resolved;
  50189. let pending;
  50190. let hasResult;
  50191. let isConstant = false;
  50192. const coalesceProvider = async (options) => {
  50193. if (!pending) {
  50194. pending = normalizedProvider(options);
  50195. }
  50196. try {
  50197. resolved = await pending;
  50198. hasResult = true;
  50199. isConstant = false;
  50200. } finally {
  50201. pending = void 0;
  50202. }
  50203. return resolved;
  50204. };
  50205. if (isExpired === void 0) {
  50206. return async (options) => {
  50207. if (!hasResult || (options == null ? void 0 : options.forceRefresh)) {
  50208. resolved = await coalesceProvider(options);
  50209. }
  50210. return resolved;
  50211. };
  50212. }
  50213. return async (options) => {
  50214. if (!hasResult || (options == null ? void 0 : options.forceRefresh)) {
  50215. resolved = await coalesceProvider(options);
  50216. }
  50217. if (isConstant) {
  50218. return resolved;
  50219. }
  50220. if (!requiresRefresh(resolved)) {
  50221. isConstant = true;
  50222. return resolved;
  50223. }
  50224. if (isExpired(resolved)) {
  50225. await coalesceProvider(options);
  50226. return resolved;
  50227. }
  50228. return resolved;
  50229. };
  50230. };
  50231. }
  50232. });
  50233. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js
  50234. var init_util_identity_and_auth = __esm({
  50235. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() {
  50236. init_DefaultIdentityProviderConfig();
  50237. init_httpAuthSchemes();
  50238. init_memoizeIdentityProvider();
  50239. }
  50240. });
  50241. // ../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js
  50242. var dist_es_exports = {};
  50243. __export(dist_es_exports, {
  50244. DefaultIdentityProviderConfig: () => DefaultIdentityProviderConfig,
  50245. EXPIRATION_MS: () => EXPIRATION_MS,
  50246. HttpApiKeyAuthSigner: () => HttpApiKeyAuthSigner,
  50247. HttpBearerAuthSigner: () => HttpBearerAuthSigner,
  50248. NoAuthSigner: () => NoAuthSigner,
  50249. createIsIdentityExpiredFunction: () => createIsIdentityExpiredFunction,
  50250. createPaginator: () => createPaginator,
  50251. doesIdentityRequireRefresh: () => doesIdentityRequireRefresh,
  50252. getHttpAuthSchemeEndpointRuleSetPlugin: () => getHttpAuthSchemeEndpointRuleSetPlugin,
  50253. getHttpAuthSchemePlugin: () => getHttpAuthSchemePlugin,
  50254. getHttpSigningPlugin: () => getHttpSigningPlugin,
  50255. getSmithyContext: () => getSmithyContext,
  50256. httpAuthSchemeEndpointRuleSetMiddlewareOptions: () => httpAuthSchemeEndpointRuleSetMiddlewareOptions,
  50257. httpAuthSchemeMiddleware: () => httpAuthSchemeMiddleware,
  50258. httpAuthSchemeMiddlewareOptions: () => httpAuthSchemeMiddlewareOptions,
  50259. httpSigningMiddleware: () => httpSigningMiddleware,
  50260. httpSigningMiddlewareOptions: () => httpSigningMiddlewareOptions,
  50261. isIdentityExpired: () => isIdentityExpired,
  50262. memoizeIdentityProvider: () => memoizeIdentityProvider,
  50263. normalizeProvider: () => normalizeProvider,
  50264. requestBuilder: () => requestBuilder,
  50265. setFeature: () => setFeature
  50266. });
  50267. var init_dist_es = __esm({
  50268. "../node_modules/.pnpm/@smithy+core@3.5.1/node_modules/@smithy/core/dist-es/index.js"() {
  50269. init_getSmithyContext();
  50270. init_middleware_http_auth_scheme();
  50271. init_middleware_http_signing();
  50272. init_normalizeProvider();
  50273. init_createPaginator();
  50274. init_requestBuilder2();
  50275. init_setFeature();
  50276. init_util_identity_and_auth();
  50277. }
  50278. });
  50279. // ../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-cjs/index.js
  50280. var require_dist_cjs18 = __commonJS({
  50281. "../node_modules/.pnpm/@smithy+util-endpoints@3.0.6/node_modules/@smithy/util-endpoints/dist-cjs/index.js"(exports2, module2) {
  50282. var __defProp3 = Object.defineProperty;
  50283. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  50284. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  50285. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  50286. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  50287. var __export2 = (target, all) => {
  50288. for (var name in all)
  50289. __defProp3(target, name, { get: all[name], enumerable: true });
  50290. };
  50291. var __copyProps3 = (to, from, except, desc) => {
  50292. if (from && typeof from === "object" || typeof from === "function") {
  50293. for (let key of __getOwnPropNames3(from))
  50294. if (!__hasOwnProp3.call(to, key) && key !== except)
  50295. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  50296. }
  50297. return to;
  50298. };
  50299. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  50300. var src_exports = {};
  50301. __export2(src_exports, {
  50302. EndpointCache: () => EndpointCache3,
  50303. EndpointError: () => EndpointError2,
  50304. customEndpointFunctions: () => customEndpointFunctions3,
  50305. isIpAddress: () => isIpAddress2,
  50306. isValidHostLabel: () => isValidHostLabel,
  50307. resolveEndpoint: () => resolveEndpoint4
  50308. });
  50309. module2.exports = __toCommonJS2(src_exports);
  50310. var _a2;
  50311. var EndpointCache3 = (_a2 = class {
  50312. /**
  50313. * @param [size] - desired average maximum capacity. A buffer of 10 additional keys will be allowed
  50314. * before keys are dropped.
  50315. * @param [params] - list of params to consider as part of the cache key.
  50316. *
  50317. * If the params list is not populated, no caching will happen.
  50318. * This may be out of order depending on how the object is created and arrives to this class.
  50319. */
  50320. constructor({ size, params }) {
  50321. this.data = /* @__PURE__ */ new Map();
  50322. this.parameters = [];
  50323. this.capacity = size ?? 50;
  50324. if (params) {
  50325. this.parameters = params;
  50326. }
  50327. }
  50328. /**
  50329. * @param endpointParams - query for endpoint.
  50330. * @param resolver - provider of the value if not present.
  50331. * @returns endpoint corresponding to the query.
  50332. */
  50333. get(endpointParams, resolver) {
  50334. const key = this.hash(endpointParams);
  50335. if (key === false) {
  50336. return resolver();
  50337. }
  50338. if (!this.data.has(key)) {
  50339. if (this.data.size > this.capacity + 10) {
  50340. const keys = this.data.keys();
  50341. let i4 = 0;
  50342. while (true) {
  50343. const { value, done } = keys.next();
  50344. this.data.delete(value);
  50345. if (done || ++i4 > 10) {
  50346. break;
  50347. }
  50348. }
  50349. }
  50350. this.data.set(key, resolver());
  50351. }
  50352. return this.data.get(key);
  50353. }
  50354. size() {
  50355. return this.data.size;
  50356. }
  50357. /**
  50358. * @returns cache key or false if not cachable.
  50359. */
  50360. hash(endpointParams) {
  50361. let buffer = "";
  50362. const { parameters } = this;
  50363. if (parameters.length === 0) {
  50364. return false;
  50365. }
  50366. for (const param of parameters) {
  50367. const val2 = String(endpointParams[param] ?? "");
  50368. if (val2.includes("|;")) {
  50369. return false;
  50370. }
  50371. buffer += val2 + "|;";
  50372. }
  50373. return buffer;
  50374. }
  50375. }, __name(_a2, "EndpointCache"), _a2);
  50376. var IP_V4_REGEX = new RegExp(
  50377. `^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`
  50378. );
  50379. var isIpAddress2 = /* @__PURE__ */ __name((value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"), "isIpAddress");
  50380. var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
  50381. var isValidHostLabel = /* @__PURE__ */ __name((value, allowSubDomains = false) => {
  50382. if (!allowSubDomains) {
  50383. return VALID_HOST_LABEL_REGEX.test(value);
  50384. }
  50385. const labels = value.split(".");
  50386. for (const label of labels) {
  50387. if (!isValidHostLabel(label)) {
  50388. return false;
  50389. }
  50390. }
  50391. return true;
  50392. }, "isValidHostLabel");
  50393. var customEndpointFunctions3 = {};
  50394. var debugId = "endpoints";
  50395. function toDebugString(input) {
  50396. if (typeof input !== "object" || input == null) {
  50397. return input;
  50398. }
  50399. if ("ref" in input) {
  50400. return `$${toDebugString(input.ref)}`;
  50401. }
  50402. if ("fn" in input) {
  50403. return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`;
  50404. }
  50405. return JSON.stringify(input, null, 2);
  50406. }
  50407. __name(toDebugString, "toDebugString");
  50408. var _a3;
  50409. var EndpointError2 = (_a3 = class extends Error {
  50410. constructor(message) {
  50411. super(message);
  50412. this.name = "EndpointError";
  50413. }
  50414. }, __name(_a3, "EndpointError"), _a3);
  50415. var booleanEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "booleanEquals");
  50416. var getAttrPathList = /* @__PURE__ */ __name((path4) => {
  50417. const parts = path4.split(".");
  50418. const pathList = [];
  50419. for (const part of parts) {
  50420. const squareBracketIndex = part.indexOf("[");
  50421. if (squareBracketIndex !== -1) {
  50422. if (part.indexOf("]") !== part.length - 1) {
  50423. throw new EndpointError2(`Path: '${path4}' does not end with ']'`);
  50424. }
  50425. const arrayIndex = part.slice(squareBracketIndex + 1, -1);
  50426. if (Number.isNaN(parseInt(arrayIndex))) {
  50427. throw new EndpointError2(`Invalid array index: '${arrayIndex}' in path: '${path4}'`);
  50428. }
  50429. if (squareBracketIndex !== 0) {
  50430. pathList.push(part.slice(0, squareBracketIndex));
  50431. }
  50432. pathList.push(arrayIndex);
  50433. } else {
  50434. pathList.push(part);
  50435. }
  50436. }
  50437. return pathList;
  50438. }, "getAttrPathList");
  50439. var getAttr = /* @__PURE__ */ __name((value, path4) => getAttrPathList(path4).reduce((acc, index6) => {
  50440. if (typeof acc !== "object") {
  50441. throw new EndpointError2(`Index '${index6}' in '${path4}' not found in '${JSON.stringify(value)}'`);
  50442. } else if (Array.isArray(acc)) {
  50443. return acc[parseInt(index6)];
  50444. }
  50445. return acc[index6];
  50446. }, value), "getAttr");
  50447. var isSet = /* @__PURE__ */ __name((value) => value != null, "isSet");
  50448. var not = /* @__PURE__ */ __name((value) => !value, "not");
  50449. var import_types32 = require_dist_cjs();
  50450. var DEFAULT_PORTS = {
  50451. [import_types32.EndpointURLScheme.HTTP]: 80,
  50452. [import_types32.EndpointURLScheme.HTTPS]: 443
  50453. };
  50454. var parseURL = /* @__PURE__ */ __name((value) => {
  50455. const whatwgURL = (() => {
  50456. try {
  50457. if (value instanceof URL) {
  50458. return value;
  50459. }
  50460. if (typeof value === "object" && "hostname" in value) {
  50461. const { hostname: hostname2, port, protocol: protocol2 = "", path: path4 = "", query = {} } = value;
  50462. const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path4}`);
  50463. url.search = Object.entries(query).map(([k3, v6]) => `${k3}=${v6}`).join("&");
  50464. return url;
  50465. }
  50466. return new URL(value);
  50467. } catch (error2) {
  50468. return null;
  50469. }
  50470. })();
  50471. if (!whatwgURL) {
  50472. console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);
  50473. return null;
  50474. }
  50475. const urlString = whatwgURL.href;
  50476. const { host, hostname, pathname, protocol, search } = whatwgURL;
  50477. if (search) {
  50478. return null;
  50479. }
  50480. const scheme = protocol.slice(0, -1);
  50481. if (!Object.values(import_types32.EndpointURLScheme).includes(scheme)) {
  50482. return null;
  50483. }
  50484. const isIp = isIpAddress2(hostname);
  50485. const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`);
  50486. const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`;
  50487. return {
  50488. scheme,
  50489. authority,
  50490. path: pathname,
  50491. normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`,
  50492. isIp
  50493. };
  50494. }, "parseURL");
  50495. var stringEquals = /* @__PURE__ */ __name((value1, value2) => value1 === value2, "stringEquals");
  50496. var substring = /* @__PURE__ */ __name((input, start, stop, reverse) => {
  50497. if (start >= stop || input.length < stop) {
  50498. return null;
  50499. }
  50500. if (!reverse) {
  50501. return input.substring(start, stop);
  50502. }
  50503. return input.substring(input.length - stop, input.length - start);
  50504. }, "substring");
  50505. var uriEncode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/[!*'()]/g, (c3) => `%${c3.charCodeAt(0).toString(16).toUpperCase()}`), "uriEncode");
  50506. var endpointFunctions = {
  50507. booleanEquals,
  50508. getAttr,
  50509. isSet,
  50510. isValidHostLabel,
  50511. not,
  50512. parseURL,
  50513. stringEquals,
  50514. substring,
  50515. uriEncode
  50516. };
  50517. var evaluateTemplate = /* @__PURE__ */ __name((template, options) => {
  50518. const evaluatedTemplateArr = [];
  50519. const templateContext = {
  50520. ...options.endpointParams,
  50521. ...options.referenceRecord
  50522. };
  50523. let currentIndex = 0;
  50524. while (currentIndex < template.length) {
  50525. const openingBraceIndex = template.indexOf("{", currentIndex);
  50526. if (openingBraceIndex === -1) {
  50527. evaluatedTemplateArr.push(template.slice(currentIndex));
  50528. break;
  50529. }
  50530. evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));
  50531. const closingBraceIndex = template.indexOf("}", openingBraceIndex);
  50532. if (closingBraceIndex === -1) {
  50533. evaluatedTemplateArr.push(template.slice(openingBraceIndex));
  50534. break;
  50535. }
  50536. if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") {
  50537. evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));
  50538. currentIndex = closingBraceIndex + 2;
  50539. }
  50540. const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);
  50541. if (parameterName.includes("#")) {
  50542. const [refName, attrName] = parameterName.split("#");
  50543. evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));
  50544. } else {
  50545. evaluatedTemplateArr.push(templateContext[parameterName]);
  50546. }
  50547. currentIndex = closingBraceIndex + 1;
  50548. }
  50549. return evaluatedTemplateArr.join("");
  50550. }, "evaluateTemplate");
  50551. var getReferenceValue = /* @__PURE__ */ __name(({ ref }, options) => {
  50552. const referenceRecord = {
  50553. ...options.endpointParams,
  50554. ...options.referenceRecord
  50555. };
  50556. return referenceRecord[ref];
  50557. }, "getReferenceValue");
  50558. var evaluateExpression = /* @__PURE__ */ __name((obj, keyName, options) => {
  50559. if (typeof obj === "string") {
  50560. return evaluateTemplate(obj, options);
  50561. } else if (obj["fn"]) {
  50562. return callFunction(obj, options);
  50563. } else if (obj["ref"]) {
  50564. return getReferenceValue(obj, options);
  50565. }
  50566. throw new EndpointError2(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
  50567. }, "evaluateExpression");
  50568. var callFunction = /* @__PURE__ */ __name(({ fn, argv }, options) => {
  50569. const evaluatedArgs = argv.map(
  50570. (arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options)
  50571. );
  50572. const fnSegments = fn.split(".");
  50573. if (fnSegments[0] in customEndpointFunctions3 && fnSegments[1] != null) {
  50574. return customEndpointFunctions3[fnSegments[0]][fnSegments[1]](...evaluatedArgs);
  50575. }
  50576. return endpointFunctions[fn](...evaluatedArgs);
  50577. }, "callFunction");
  50578. var evaluateCondition = /* @__PURE__ */ __name(({ assign, ...fnArgs }, options) => {
  50579. var _a4, _b;
  50580. if (assign && assign in options.referenceRecord) {
  50581. throw new EndpointError2(`'${assign}' is already defined in Reference Record.`);
  50582. }
  50583. const value = callFunction(fnArgs, options);
  50584. (_b = (_a4 = options.logger) == null ? void 0 : _a4.debug) == null ? void 0 : _b.call(_a4, `${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);
  50585. return {
  50586. result: value === "" ? true : !!value,
  50587. ...assign != null && { toAssign: { name: assign, value } }
  50588. };
  50589. }, "evaluateCondition");
  50590. var evaluateConditions = /* @__PURE__ */ __name((conditions = [], options) => {
  50591. var _a4, _b;
  50592. const conditionsReferenceRecord = {};
  50593. for (const condition of conditions) {
  50594. const { result, toAssign } = evaluateCondition(condition, {
  50595. ...options,
  50596. referenceRecord: {
  50597. ...options.referenceRecord,
  50598. ...conditionsReferenceRecord
  50599. }
  50600. });
  50601. if (!result) {
  50602. return { result };
  50603. }
  50604. if (toAssign) {
  50605. conditionsReferenceRecord[toAssign.name] = toAssign.value;
  50606. (_b = (_a4 = options.logger) == null ? void 0 : _a4.debug) == null ? void 0 : _b.call(_a4, `${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`);
  50607. }
  50608. }
  50609. return { result: true, referenceRecord: conditionsReferenceRecord };
  50610. }, "evaluateConditions");
  50611. var getEndpointHeaders = /* @__PURE__ */ __name((headers, options) => Object.entries(headers).reduce(
  50612. (acc, [headerKey, headerVal]) => ({
  50613. ...acc,
  50614. [headerKey]: headerVal.map((headerValEntry) => {
  50615. const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options);
  50616. if (typeof processedExpr !== "string") {
  50617. throw new EndpointError2(`Header '${headerKey}' value '${processedExpr}' is not a string`);
  50618. }
  50619. return processedExpr;
  50620. })
  50621. }),
  50622. {}
  50623. ), "getEndpointHeaders");
  50624. var getEndpointProperty = /* @__PURE__ */ __name((property, options) => {
  50625. if (Array.isArray(property)) {
  50626. return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options));
  50627. }
  50628. switch (typeof property) {
  50629. case "string":
  50630. return evaluateTemplate(property, options);
  50631. case "object":
  50632. if (property === null) {
  50633. throw new EndpointError2(`Unexpected endpoint property: ${property}`);
  50634. }
  50635. return getEndpointProperties(property, options);
  50636. case "boolean":
  50637. return property;
  50638. default:
  50639. throw new EndpointError2(`Unexpected endpoint property type: ${typeof property}`);
  50640. }
  50641. }, "getEndpointProperty");
  50642. var getEndpointProperties = /* @__PURE__ */ __name((properties, options) => Object.entries(properties).reduce(
  50643. (acc, [propertyKey, propertyVal]) => ({
  50644. ...acc,
  50645. [propertyKey]: getEndpointProperty(propertyVal, options)
  50646. }),
  50647. {}
  50648. ), "getEndpointProperties");
  50649. var getEndpointUrl = /* @__PURE__ */ __name((endpointUrl, options) => {
  50650. const expression = evaluateExpression(endpointUrl, "Endpoint URL", options);
  50651. if (typeof expression === "string") {
  50652. try {
  50653. return new URL(expression);
  50654. } catch (error2) {
  50655. console.error(`Failed to construct URL with ${expression}`, error2);
  50656. throw error2;
  50657. }
  50658. }
  50659. throw new EndpointError2(`Endpoint URL must be a string, got ${typeof expression}`);
  50660. }, "getEndpointUrl");
  50661. var evaluateEndpointRule = /* @__PURE__ */ __name((endpointRule, options) => {
  50662. var _a4, _b;
  50663. const { conditions, endpoint } = endpointRule;
  50664. const { result, referenceRecord } = evaluateConditions(conditions, options);
  50665. if (!result) {
  50666. return;
  50667. }
  50668. const endpointRuleOptions = {
  50669. ...options,
  50670. referenceRecord: { ...options.referenceRecord, ...referenceRecord }
  50671. };
  50672. const { url, properties, headers } = endpoint;
  50673. (_b = (_a4 = options.logger) == null ? void 0 : _a4.debug) == null ? void 0 : _b.call(_a4, `${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);
  50674. return {
  50675. ...headers != void 0 && {
  50676. headers: getEndpointHeaders(headers, endpointRuleOptions)
  50677. },
  50678. ...properties != void 0 && {
  50679. properties: getEndpointProperties(properties, endpointRuleOptions)
  50680. },
  50681. url: getEndpointUrl(url, endpointRuleOptions)
  50682. };
  50683. }, "evaluateEndpointRule");
  50684. var evaluateErrorRule = /* @__PURE__ */ __name((errorRule, options) => {
  50685. const { conditions, error: error2 } = errorRule;
  50686. const { result, referenceRecord } = evaluateConditions(conditions, options);
  50687. if (!result) {
  50688. return;
  50689. }
  50690. throw new EndpointError2(
  50691. evaluateExpression(error2, "Error", {
  50692. ...options,
  50693. referenceRecord: { ...options.referenceRecord, ...referenceRecord }
  50694. })
  50695. );
  50696. }, "evaluateErrorRule");
  50697. var evaluateTreeRule = /* @__PURE__ */ __name((treeRule, options) => {
  50698. const { conditions, rules } = treeRule;
  50699. const { result, referenceRecord } = evaluateConditions(conditions, options);
  50700. if (!result) {
  50701. return;
  50702. }
  50703. return evaluateRules(rules, {
  50704. ...options,
  50705. referenceRecord: { ...options.referenceRecord, ...referenceRecord }
  50706. });
  50707. }, "evaluateTreeRule");
  50708. var evaluateRules = /* @__PURE__ */ __name((rules, options) => {
  50709. for (const rule of rules) {
  50710. if (rule.type === "endpoint") {
  50711. const endpointOrUndefined = evaluateEndpointRule(rule, options);
  50712. if (endpointOrUndefined) {
  50713. return endpointOrUndefined;
  50714. }
  50715. } else if (rule.type === "error") {
  50716. evaluateErrorRule(rule, options);
  50717. } else if (rule.type === "tree") {
  50718. const endpointOrUndefined = evaluateTreeRule(rule, options);
  50719. if (endpointOrUndefined) {
  50720. return endpointOrUndefined;
  50721. }
  50722. } else {
  50723. throw new EndpointError2(`Unknown endpoint rule: ${rule}`);
  50724. }
  50725. }
  50726. throw new EndpointError2(`Rules evaluation failed`);
  50727. }, "evaluateRules");
  50728. var resolveEndpoint4 = /* @__PURE__ */ __name((ruleSetObject, options) => {
  50729. var _a4, _b, _c, _d;
  50730. const { endpointParams, logger: logger3 } = options;
  50731. const { parameters, rules } = ruleSetObject;
  50732. (_b = (_a4 = options.logger) == null ? void 0 : _a4.debug) == null ? void 0 : _b.call(_a4, `${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);
  50733. const paramsWithDefault = Object.entries(parameters).filter(([, v6]) => v6.default != null).map(([k3, v6]) => [k3, v6.default]);
  50734. if (paramsWithDefault.length > 0) {
  50735. for (const [paramKey, paramDefaultValue] of paramsWithDefault) {
  50736. endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;
  50737. }
  50738. }
  50739. const requiredParams = Object.entries(parameters).filter(([, v6]) => v6.required).map(([k3]) => k3);
  50740. for (const requiredParam of requiredParams) {
  50741. if (endpointParams[requiredParam] == null) {
  50742. throw new EndpointError2(`Missing required parameter: '${requiredParam}'`);
  50743. }
  50744. }
  50745. const endpoint = evaluateRules(rules, { endpointParams, logger: logger3, referenceRecord: {} });
  50746. (_d = (_c = options.logger) == null ? void 0 : _c.debug) == null ? void 0 : _d.call(_c, `${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
  50747. return endpoint;
  50748. }, "resolveEndpoint");
  50749. }
  50750. });
  50751. // ../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js
  50752. var require_dist_cjs19 = __commonJS({
  50753. "../node_modules/.pnpm/@aws-sdk+util-endpoints@3.808.0/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js"(exports2, module2) {
  50754. "use strict";
  50755. var __defProp3 = Object.defineProperty;
  50756. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  50757. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  50758. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  50759. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  50760. var __export2 = (target, all) => {
  50761. for (var name in all)
  50762. __defProp3(target, name, { get: all[name], enumerable: true });
  50763. };
  50764. var __copyProps3 = (to, from, except, desc) => {
  50765. if (from && typeof from === "object" || typeof from === "function") {
  50766. for (let key of __getOwnPropNames3(from))
  50767. if (!__hasOwnProp3.call(to, key) && key !== except)
  50768. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  50769. }
  50770. return to;
  50771. };
  50772. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  50773. var index_exports = {};
  50774. __export2(index_exports, {
  50775. ConditionObject: () => import_util_endpoints5.ConditionObject,
  50776. DeprecatedObject: () => import_util_endpoints5.DeprecatedObject,
  50777. EndpointError: () => import_util_endpoints5.EndpointError,
  50778. EndpointObject: () => import_util_endpoints5.EndpointObject,
  50779. EndpointObjectHeaders: () => import_util_endpoints5.EndpointObjectHeaders,
  50780. EndpointObjectProperties: () => import_util_endpoints5.EndpointObjectProperties,
  50781. EndpointParams: () => import_util_endpoints5.EndpointParams,
  50782. EndpointResolverOptions: () => import_util_endpoints5.EndpointResolverOptions,
  50783. EndpointRuleObject: () => import_util_endpoints5.EndpointRuleObject,
  50784. ErrorRuleObject: () => import_util_endpoints5.ErrorRuleObject,
  50785. EvaluateOptions: () => import_util_endpoints5.EvaluateOptions,
  50786. Expression: () => import_util_endpoints5.Expression,
  50787. FunctionArgv: () => import_util_endpoints5.FunctionArgv,
  50788. FunctionObject: () => import_util_endpoints5.FunctionObject,
  50789. FunctionReturn: () => import_util_endpoints5.FunctionReturn,
  50790. ParameterObject: () => import_util_endpoints5.ParameterObject,
  50791. ReferenceObject: () => import_util_endpoints5.ReferenceObject,
  50792. ReferenceRecord: () => import_util_endpoints5.ReferenceRecord,
  50793. RuleSetObject: () => import_util_endpoints5.RuleSetObject,
  50794. RuleSetRules: () => import_util_endpoints5.RuleSetRules,
  50795. TreeRuleObject: () => import_util_endpoints5.TreeRuleObject,
  50796. awsEndpointFunctions: () => awsEndpointFunctions3,
  50797. getUserAgentPrefix: () => getUserAgentPrefix,
  50798. isIpAddress: () => import_util_endpoints5.isIpAddress,
  50799. partition: () => partition,
  50800. resolveEndpoint: () => import_util_endpoints5.resolveEndpoint,
  50801. setPartitionInfo: () => setPartitionInfo,
  50802. useDefaultPartitionInfo: () => useDefaultPartitionInfo
  50803. });
  50804. module2.exports = __toCommonJS2(index_exports);
  50805. var import_util_endpoints5 = require_dist_cjs18();
  50806. var isVirtualHostableS3Bucket = /* @__PURE__ */ __name((value, allowSubDomains = false) => {
  50807. if (allowSubDomains) {
  50808. for (const label of value.split(".")) {
  50809. if (!isVirtualHostableS3Bucket(label)) {
  50810. return false;
  50811. }
  50812. }
  50813. return true;
  50814. }
  50815. if (!(0, import_util_endpoints5.isValidHostLabel)(value)) {
  50816. return false;
  50817. }
  50818. if (value.length < 3 || value.length > 63) {
  50819. return false;
  50820. }
  50821. if (value !== value.toLowerCase()) {
  50822. return false;
  50823. }
  50824. if ((0, import_util_endpoints5.isIpAddress)(value)) {
  50825. return false;
  50826. }
  50827. return true;
  50828. }, "isVirtualHostableS3Bucket");
  50829. var ARN_DELIMITER = ":";
  50830. var RESOURCE_DELIMITER = "/";
  50831. var parseArn = /* @__PURE__ */ __name((value) => {
  50832. const segments = value.split(ARN_DELIMITER);
  50833. if (segments.length < 6) return null;
  50834. const [arn, partition2, service, region, accountId, ...resourcePath] = segments;
  50835. if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") return null;
  50836. const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat();
  50837. return {
  50838. partition: partition2,
  50839. service,
  50840. region,
  50841. accountId,
  50842. resourceId
  50843. };
  50844. }, "parseArn");
  50845. var partitions_default = {
  50846. partitions: [{
  50847. id: "aws",
  50848. outputs: {
  50849. dnsSuffix: "amazonaws.com",
  50850. dualStackDnsSuffix: "api.aws",
  50851. implicitGlobalRegion: "us-east-1",
  50852. name: "aws",
  50853. supportsDualStack: true,
  50854. supportsFIPS: true
  50855. },
  50856. regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",
  50857. regions: {
  50858. "af-south-1": {
  50859. description: "Africa (Cape Town)"
  50860. },
  50861. "ap-east-1": {
  50862. description: "Asia Pacific (Hong Kong)"
  50863. },
  50864. "ap-northeast-1": {
  50865. description: "Asia Pacific (Tokyo)"
  50866. },
  50867. "ap-northeast-2": {
  50868. description: "Asia Pacific (Seoul)"
  50869. },
  50870. "ap-northeast-3": {
  50871. description: "Asia Pacific (Osaka)"
  50872. },
  50873. "ap-south-1": {
  50874. description: "Asia Pacific (Mumbai)"
  50875. },
  50876. "ap-south-2": {
  50877. description: "Asia Pacific (Hyderabad)"
  50878. },
  50879. "ap-southeast-1": {
  50880. description: "Asia Pacific (Singapore)"
  50881. },
  50882. "ap-southeast-2": {
  50883. description: "Asia Pacific (Sydney)"
  50884. },
  50885. "ap-southeast-3": {
  50886. description: "Asia Pacific (Jakarta)"
  50887. },
  50888. "ap-southeast-4": {
  50889. description: "Asia Pacific (Melbourne)"
  50890. },
  50891. "ap-southeast-5": {
  50892. description: "Asia Pacific (Malaysia)"
  50893. },
  50894. "ap-southeast-7": {
  50895. description: "Asia Pacific (Thailand)"
  50896. },
  50897. "aws-global": {
  50898. description: "AWS Standard global region"
  50899. },
  50900. "ca-central-1": {
  50901. description: "Canada (Central)"
  50902. },
  50903. "ca-west-1": {
  50904. description: "Canada West (Calgary)"
  50905. },
  50906. "eu-central-1": {
  50907. description: "Europe (Frankfurt)"
  50908. },
  50909. "eu-central-2": {
  50910. description: "Europe (Zurich)"
  50911. },
  50912. "eu-north-1": {
  50913. description: "Europe (Stockholm)"
  50914. },
  50915. "eu-south-1": {
  50916. description: "Europe (Milan)"
  50917. },
  50918. "eu-south-2": {
  50919. description: "Europe (Spain)"
  50920. },
  50921. "eu-west-1": {
  50922. description: "Europe (Ireland)"
  50923. },
  50924. "eu-west-2": {
  50925. description: "Europe (London)"
  50926. },
  50927. "eu-west-3": {
  50928. description: "Europe (Paris)"
  50929. },
  50930. "il-central-1": {
  50931. description: "Israel (Tel Aviv)"
  50932. },
  50933. "me-central-1": {
  50934. description: "Middle East (UAE)"
  50935. },
  50936. "me-south-1": {
  50937. description: "Middle East (Bahrain)"
  50938. },
  50939. "mx-central-1": {
  50940. description: "Mexico (Central)"
  50941. },
  50942. "sa-east-1": {
  50943. description: "South America (Sao Paulo)"
  50944. },
  50945. "us-east-1": {
  50946. description: "US East (N. Virginia)"
  50947. },
  50948. "us-east-2": {
  50949. description: "US East (Ohio)"
  50950. },
  50951. "us-west-1": {
  50952. description: "US West (N. California)"
  50953. },
  50954. "us-west-2": {
  50955. description: "US West (Oregon)"
  50956. }
  50957. }
  50958. }, {
  50959. id: "aws-cn",
  50960. outputs: {
  50961. dnsSuffix: "amazonaws.com.cn",
  50962. dualStackDnsSuffix: "api.amazonwebservices.com.cn",
  50963. implicitGlobalRegion: "cn-northwest-1",
  50964. name: "aws-cn",
  50965. supportsDualStack: true,
  50966. supportsFIPS: true
  50967. },
  50968. regionRegex: "^cn\\-\\w+\\-\\d+$",
  50969. regions: {
  50970. "aws-cn-global": {
  50971. description: "AWS China global region"
  50972. },
  50973. "cn-north-1": {
  50974. description: "China (Beijing)"
  50975. },
  50976. "cn-northwest-1": {
  50977. description: "China (Ningxia)"
  50978. }
  50979. }
  50980. }, {
  50981. id: "aws-us-gov",
  50982. outputs: {
  50983. dnsSuffix: "amazonaws.com",
  50984. dualStackDnsSuffix: "api.aws",
  50985. implicitGlobalRegion: "us-gov-west-1",
  50986. name: "aws-us-gov",
  50987. supportsDualStack: true,
  50988. supportsFIPS: true
  50989. },
  50990. regionRegex: "^us\\-gov\\-\\w+\\-\\d+$",
  50991. regions: {
  50992. "aws-us-gov-global": {
  50993. description: "AWS GovCloud (US) global region"
  50994. },
  50995. "us-gov-east-1": {
  50996. description: "AWS GovCloud (US-East)"
  50997. },
  50998. "us-gov-west-1": {
  50999. description: "AWS GovCloud (US-West)"
  51000. }
  51001. }
  51002. }, {
  51003. id: "aws-iso",
  51004. outputs: {
  51005. dnsSuffix: "c2s.ic.gov",
  51006. dualStackDnsSuffix: "c2s.ic.gov",
  51007. implicitGlobalRegion: "us-iso-east-1",
  51008. name: "aws-iso",
  51009. supportsDualStack: false,
  51010. supportsFIPS: true
  51011. },
  51012. regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
  51013. regions: {
  51014. "aws-iso-global": {
  51015. description: "AWS ISO (US) global region"
  51016. },
  51017. "us-iso-east-1": {
  51018. description: "US ISO East"
  51019. },
  51020. "us-iso-west-1": {
  51021. description: "US ISO WEST"
  51022. }
  51023. }
  51024. }, {
  51025. id: "aws-iso-b",
  51026. outputs: {
  51027. dnsSuffix: "sc2s.sgov.gov",
  51028. dualStackDnsSuffix: "sc2s.sgov.gov",
  51029. implicitGlobalRegion: "us-isob-east-1",
  51030. name: "aws-iso-b",
  51031. supportsDualStack: false,
  51032. supportsFIPS: true
  51033. },
  51034. regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
  51035. regions: {
  51036. "aws-iso-b-global": {
  51037. description: "AWS ISOB (US) global region"
  51038. },
  51039. "us-isob-east-1": {
  51040. description: "US ISOB East (Ohio)"
  51041. }
  51042. }
  51043. }, {
  51044. id: "aws-iso-e",
  51045. outputs: {
  51046. dnsSuffix: "cloud.adc-e.uk",
  51047. dualStackDnsSuffix: "cloud.adc-e.uk",
  51048. implicitGlobalRegion: "eu-isoe-west-1",
  51049. name: "aws-iso-e",
  51050. supportsDualStack: false,
  51051. supportsFIPS: true
  51052. },
  51053. regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$",
  51054. regions: {
  51055. "aws-iso-e-global": {
  51056. description: "AWS ISOE (Europe) global region"
  51057. },
  51058. "eu-isoe-west-1": {
  51059. description: "EU ISOE West"
  51060. }
  51061. }
  51062. }, {
  51063. id: "aws-iso-f",
  51064. outputs: {
  51065. dnsSuffix: "csp.hci.ic.gov",
  51066. dualStackDnsSuffix: "csp.hci.ic.gov",
  51067. implicitGlobalRegion: "us-isof-south-1",
  51068. name: "aws-iso-f",
  51069. supportsDualStack: false,
  51070. supportsFIPS: true
  51071. },
  51072. regionRegex: "^us\\-isof\\-\\w+\\-\\d+$",
  51073. regions: {
  51074. "aws-iso-f-global": {
  51075. description: "AWS ISOF global region"
  51076. },
  51077. "us-isof-east-1": {
  51078. description: "US ISOF EAST"
  51079. },
  51080. "us-isof-south-1": {
  51081. description: "US ISOF SOUTH"
  51082. }
  51083. }
  51084. }, {
  51085. id: "aws-eusc",
  51086. outputs: {
  51087. dnsSuffix: "amazonaws.eu",
  51088. dualStackDnsSuffix: "amazonaws.eu",
  51089. implicitGlobalRegion: "eusc-de-east-1",
  51090. name: "aws-eusc",
  51091. supportsDualStack: false,
  51092. supportsFIPS: true
  51093. },
  51094. regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$",
  51095. regions: {
  51096. "eusc-de-east-1": {
  51097. description: "EU (Germany)"
  51098. }
  51099. }
  51100. }],
  51101. version: "1.1"
  51102. };
  51103. var selectedPartitionsInfo = partitions_default;
  51104. var selectedUserAgentPrefix = "";
  51105. var partition = /* @__PURE__ */ __name((value) => {
  51106. const { partitions } = selectedPartitionsInfo;
  51107. for (const partition2 of partitions) {
  51108. const { regions, outputs: outputs2 } = partition2;
  51109. for (const [region, regionData] of Object.entries(regions)) {
  51110. if (region === value) {
  51111. return {
  51112. ...outputs2,
  51113. ...regionData
  51114. };
  51115. }
  51116. }
  51117. }
  51118. for (const partition2 of partitions) {
  51119. const { regionRegex, outputs: outputs2 } = partition2;
  51120. if (new RegExp(regionRegex).test(value)) {
  51121. return {
  51122. ...outputs2
  51123. };
  51124. }
  51125. }
  51126. const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws");
  51127. if (!DEFAULT_PARTITION) {
  51128. throw new Error(
  51129. "Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist."
  51130. );
  51131. }
  51132. return {
  51133. ...DEFAULT_PARTITION.outputs
  51134. };
  51135. }, "partition");
  51136. var setPartitionInfo = /* @__PURE__ */ __name((partitionsInfo, userAgentPrefix = "") => {
  51137. selectedPartitionsInfo = partitionsInfo;
  51138. selectedUserAgentPrefix = userAgentPrefix;
  51139. }, "setPartitionInfo");
  51140. var useDefaultPartitionInfo = /* @__PURE__ */ __name(() => {
  51141. setPartitionInfo(partitions_default, "");
  51142. }, "useDefaultPartitionInfo");
  51143. var getUserAgentPrefix = /* @__PURE__ */ __name(() => selectedUserAgentPrefix, "getUserAgentPrefix");
  51144. var awsEndpointFunctions3 = {
  51145. isVirtualHostableS3Bucket,
  51146. parseArn,
  51147. partition
  51148. };
  51149. import_util_endpoints5.customEndpointFunctions.aws = awsEndpointFunctions3;
  51150. }
  51151. });
  51152. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js
  51153. var state, emitWarningIfUnsupportedVersion;
  51154. var init_emitWarningIfUnsupportedVersion = __esm({
  51155. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js"() {
  51156. state = {
  51157. warningEmitted: false
  51158. };
  51159. emitWarningIfUnsupportedVersion = (version3) => {
  51160. if (version3 && !state.warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 18) {
  51161. state.warningEmitted = true;
  51162. process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will
  51163. no longer support Node.js 16.x on January 6, 2025.
  51164. To continue receiving updates to AWS services, bug fixes, and security
  51165. updates please upgrade to a supported Node.js LTS version.
  51166. More information can be found at: https://a.co/74kJMmI`);
  51167. }
  51168. };
  51169. }
  51170. });
  51171. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js
  51172. function setCredentialFeature(credentials2, feature, value) {
  51173. if (!credentials2.$source) {
  51174. credentials2.$source = {};
  51175. }
  51176. credentials2.$source[feature] = value;
  51177. return credentials2;
  51178. }
  51179. var init_setCredentialFeature = __esm({
  51180. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js"() {
  51181. }
  51182. });
  51183. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js
  51184. function setFeature2(context, feature, value) {
  51185. if (!context.__aws_sdk_context) {
  51186. context.__aws_sdk_context = {
  51187. features: {}
  51188. };
  51189. } else if (!context.__aws_sdk_context.features) {
  51190. context.__aws_sdk_context.features = {};
  51191. }
  51192. context.__aws_sdk_context.features[feature] = value;
  51193. }
  51194. var init_setFeature2 = __esm({
  51195. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js"() {
  51196. }
  51197. });
  51198. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js
  51199. var client_exports = {};
  51200. __export(client_exports, {
  51201. emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion,
  51202. setCredentialFeature: () => setCredentialFeature,
  51203. setFeature: () => setFeature2,
  51204. state: () => state
  51205. });
  51206. var init_client = __esm({
  51207. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js"() {
  51208. init_emitWarningIfUnsupportedVersion();
  51209. init_setCredentialFeature();
  51210. init_setFeature2();
  51211. }
  51212. });
  51213. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js
  51214. var import_protocol_http9, getDateHeader;
  51215. var init_getDateHeader = __esm({
  51216. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js"() {
  51217. import_protocol_http9 = __toESM(require_dist_cjs2());
  51218. getDateHeader = (response) => {
  51219. var _a2, _b;
  51220. return import_protocol_http9.HttpResponse.isInstance(response) ? ((_a2 = response.headers) == null ? void 0 : _a2.date) ?? ((_b = response.headers) == null ? void 0 : _b.Date) : void 0;
  51221. };
  51222. }
  51223. });
  51224. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js
  51225. var getSkewCorrectedDate;
  51226. var init_getSkewCorrectedDate = __esm({
  51227. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js"() {
  51228. getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);
  51229. }
  51230. });
  51231. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js
  51232. var isClockSkewed;
  51233. var init_isClockSkewed = __esm({
  51234. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js"() {
  51235. init_getSkewCorrectedDate();
  51236. isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5;
  51237. }
  51238. });
  51239. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js
  51240. var getUpdatedSystemClockOffset;
  51241. var init_getUpdatedSystemClockOffset = __esm({
  51242. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js"() {
  51243. init_isClockSkewed();
  51244. getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => {
  51245. const clockTimeInMs = Date.parse(clockTime);
  51246. if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {
  51247. return clockTimeInMs - Date.now();
  51248. }
  51249. return currentSystemClockOffset;
  51250. };
  51251. }
  51252. });
  51253. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js
  51254. var init_utils6 = __esm({
  51255. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js"() {
  51256. init_getDateHeader();
  51257. init_getSkewCorrectedDate();
  51258. init_getUpdatedSystemClockOffset();
  51259. }
  51260. });
  51261. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js
  51262. var import_protocol_http10, throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer, AWSSDKSigV4Signer;
  51263. var init_AwsSdkSigV4Signer = __esm({
  51264. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js"() {
  51265. import_protocol_http10 = __toESM(require_dist_cjs2());
  51266. init_utils6();
  51267. throwSigningPropertyError = (name, property) => {
  51268. if (!property) {
  51269. throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);
  51270. }
  51271. return property;
  51272. };
  51273. validateSigningProperties = async (signingProperties) => {
  51274. var _a2, _b, _c;
  51275. const context = throwSigningPropertyError("context", signingProperties.context);
  51276. const config = throwSigningPropertyError("config", signingProperties.config);
  51277. const authScheme = (_c = (_b = (_a2 = context.endpointV2) == null ? void 0 : _a2.properties) == null ? void 0 : _b.authSchemes) == null ? void 0 : _c[0];
  51278. const signerFunction = throwSigningPropertyError("signer", config.signer);
  51279. const signer = await signerFunction(authScheme);
  51280. const signingRegion = signingProperties == null ? void 0 : signingProperties.signingRegion;
  51281. const signingRegionSet = signingProperties == null ? void 0 : signingProperties.signingRegionSet;
  51282. const signingName = signingProperties == null ? void 0 : signingProperties.signingName;
  51283. return {
  51284. config,
  51285. signer,
  51286. signingRegion,
  51287. signingRegionSet,
  51288. signingName
  51289. };
  51290. };
  51291. AwsSdkSigV4Signer = class {
  51292. async sign(httpRequest, identity, signingProperties) {
  51293. var _a2;
  51294. if (!import_protocol_http10.HttpRequest.isInstance(httpRequest)) {
  51295. throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
  51296. }
  51297. const validatedProps = await validateSigningProperties(signingProperties);
  51298. const { config, signer } = validatedProps;
  51299. let { signingRegion, signingName } = validatedProps;
  51300. const handlerExecutionContext = signingProperties.context;
  51301. if (((_a2 = handlerExecutionContext == null ? void 0 : handlerExecutionContext.authSchemes) == null ? void 0 : _a2.length) ?? 0 > 1) {
  51302. const [first, second] = handlerExecutionContext.authSchemes;
  51303. if ((first == null ? void 0 : first.name) === "sigv4a" && (second == null ? void 0 : second.name) === "sigv4") {
  51304. signingRegion = (second == null ? void 0 : second.signingRegion) ?? signingRegion;
  51305. signingName = (second == null ? void 0 : second.signingName) ?? signingName;
  51306. }
  51307. }
  51308. const signedRequest = await signer.sign(httpRequest, {
  51309. signingDate: getSkewCorrectedDate(config.systemClockOffset),
  51310. signingRegion,
  51311. signingService: signingName
  51312. });
  51313. return signedRequest;
  51314. }
  51315. errorHandler(signingProperties) {
  51316. return (error2) => {
  51317. const serverTime = error2.ServerTime ?? getDateHeader(error2.$response);
  51318. if (serverTime) {
  51319. const config = throwSigningPropertyError("config", signingProperties.config);
  51320. const initialSystemClockOffset = config.systemClockOffset;
  51321. config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset);
  51322. const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset;
  51323. if (clockSkewCorrected && error2.$metadata) {
  51324. error2.$metadata.clockSkewCorrected = true;
  51325. }
  51326. }
  51327. throw error2;
  51328. };
  51329. }
  51330. successHandler(httpResponse, signingProperties) {
  51331. const dateHeader = getDateHeader(httpResponse);
  51332. if (dateHeader) {
  51333. const config = throwSigningPropertyError("config", signingProperties.config);
  51334. config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset);
  51335. }
  51336. }
  51337. };
  51338. AWSSDKSigV4Signer = AwsSdkSigV4Signer;
  51339. }
  51340. });
  51341. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js
  51342. var import_protocol_http11, AwsSdkSigV4ASigner;
  51343. var init_AwsSdkSigV4ASigner = __esm({
  51344. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js"() {
  51345. import_protocol_http11 = __toESM(require_dist_cjs2());
  51346. init_utils6();
  51347. init_AwsSdkSigV4Signer();
  51348. AwsSdkSigV4ASigner = class extends AwsSdkSigV4Signer {
  51349. async sign(httpRequest, identity, signingProperties) {
  51350. var _a2;
  51351. if (!import_protocol_http11.HttpRequest.isInstance(httpRequest)) {
  51352. throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
  51353. }
  51354. const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties);
  51355. const configResolvedSigningRegionSet = await ((_a2 = config.sigv4aSigningRegionSet) == null ? void 0 : _a2.call(config));
  51356. const multiRegionOverride = (configResolvedSigningRegionSet ?? signingRegionSet ?? [signingRegion]).join(",");
  51357. const signedRequest = await signer.sign(httpRequest, {
  51358. signingDate: getSkewCorrectedDate(config.systemClockOffset),
  51359. signingRegion: multiRegionOverride,
  51360. signingService: signingName
  51361. });
  51362. return signedRequest;
  51363. }
  51364. };
  51365. }
  51366. });
  51367. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js
  51368. var getArrayForCommaSeparatedString;
  51369. var init_getArrayForCommaSeparatedString = __esm({
  51370. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js"() {
  51371. getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : [];
  51372. }
  51373. });
  51374. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js
  51375. var getBearerTokenEnvKey;
  51376. var init_getBearerTokenEnvKey = __esm({
  51377. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js"() {
  51378. getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`;
  51379. }
  51380. });
  51381. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js
  51382. var NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY, NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY, NODE_AUTH_SCHEME_PREFERENCE_OPTIONS;
  51383. var init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = __esm({
  51384. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js"() {
  51385. init_getArrayForCommaSeparatedString();
  51386. init_getBearerTokenEnvKey();
  51387. NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE";
  51388. NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference";
  51389. NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = {
  51390. environmentVariableSelector: (env3, options) => {
  51391. if (options == null ? void 0 : options.signingName) {
  51392. const bearerTokenKey = getBearerTokenEnvKey(options.signingName);
  51393. if (bearerTokenKey in env3)
  51394. return ["httpBearerAuth"];
  51395. }
  51396. if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env3))
  51397. return void 0;
  51398. return getArrayForCommaSeparatedString(env3[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]);
  51399. },
  51400. configFileSelector: (profile) => {
  51401. if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile))
  51402. return void 0;
  51403. return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]);
  51404. },
  51405. default: []
  51406. };
  51407. }
  51408. });
  51409. // ../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-cjs/index.js
  51410. var require_dist_cjs20 = __commonJS({
  51411. "../node_modules/.pnpm/@smithy+property-provider@4.0.4/node_modules/@smithy/property-provider/dist-cjs/index.js"(exports2, module2) {
  51412. var __defProp3 = Object.defineProperty;
  51413. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  51414. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  51415. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  51416. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  51417. var __export2 = (target, all) => {
  51418. for (var name in all)
  51419. __defProp3(target, name, { get: all[name], enumerable: true });
  51420. };
  51421. var __copyProps3 = (to, from, except, desc) => {
  51422. if (from && typeof from === "object" || typeof from === "function") {
  51423. for (let key of __getOwnPropNames3(from))
  51424. if (!__hasOwnProp3.call(to, key) && key !== except)
  51425. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  51426. }
  51427. return to;
  51428. };
  51429. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  51430. var src_exports = {};
  51431. __export2(src_exports, {
  51432. CredentialsProviderError: () => CredentialsProviderError,
  51433. ProviderError: () => ProviderError2,
  51434. TokenProviderError: () => TokenProviderError,
  51435. chain: () => chain,
  51436. fromStatic: () => fromStatic,
  51437. memoize: () => memoize
  51438. });
  51439. module2.exports = __toCommonJS2(src_exports);
  51440. var _a2;
  51441. var ProviderError2 = (_a2 = class extends Error {
  51442. constructor(message, options = true) {
  51443. var _a5;
  51444. let logger3;
  51445. let tryNextLink = true;
  51446. if (typeof options === "boolean") {
  51447. logger3 = void 0;
  51448. tryNextLink = options;
  51449. } else if (options != null && typeof options === "object") {
  51450. logger3 = options.logger;
  51451. tryNextLink = options.tryNextLink ?? true;
  51452. }
  51453. super(message);
  51454. this.name = "ProviderError";
  51455. this.tryNextLink = tryNextLink;
  51456. Object.setPrototypeOf(this, _a2.prototype);
  51457. (_a5 = logger3 == null ? void 0 : logger3.debug) == null ? void 0 : _a5.call(logger3, `@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`);
  51458. }
  51459. /**
  51460. * @deprecated use new operator.
  51461. */
  51462. static from(error2, options = true) {
  51463. return Object.assign(new this(error2.message, options), error2);
  51464. }
  51465. }, __name(_a2, "ProviderError"), _a2);
  51466. var _a3;
  51467. var CredentialsProviderError = (_a3 = class extends ProviderError2 {
  51468. /**
  51469. * @override
  51470. */
  51471. constructor(message, options = true) {
  51472. super(message, options);
  51473. this.name = "CredentialsProviderError";
  51474. Object.setPrototypeOf(this, _a3.prototype);
  51475. }
  51476. }, __name(_a3, "CredentialsProviderError"), _a3);
  51477. var _a4;
  51478. var TokenProviderError = (_a4 = class extends ProviderError2 {
  51479. /**
  51480. * @override
  51481. */
  51482. constructor(message, options = true) {
  51483. super(message, options);
  51484. this.name = "TokenProviderError";
  51485. Object.setPrototypeOf(this, _a4.prototype);
  51486. }
  51487. }, __name(_a4, "TokenProviderError"), _a4);
  51488. var chain = /* @__PURE__ */ __name((...providers) => async () => {
  51489. if (providers.length === 0) {
  51490. throw new ProviderError2("No providers in chain");
  51491. }
  51492. let lastProviderError;
  51493. for (const provider of providers) {
  51494. try {
  51495. const credentials2 = await provider();
  51496. return credentials2;
  51497. } catch (err2) {
  51498. lastProviderError = err2;
  51499. if (err2 == null ? void 0 : err2.tryNextLink) {
  51500. continue;
  51501. }
  51502. throw err2;
  51503. }
  51504. }
  51505. throw lastProviderError;
  51506. }, "chain");
  51507. var fromStatic = /* @__PURE__ */ __name((staticValue) => () => Promise.resolve(staticValue), "fromStatic");
  51508. var memoize = /* @__PURE__ */ __name((provider, isExpired, requiresRefresh) => {
  51509. let resolved;
  51510. let pending;
  51511. let hasResult;
  51512. let isConstant = false;
  51513. const coalesceProvider = /* @__PURE__ */ __name(async () => {
  51514. if (!pending) {
  51515. pending = provider();
  51516. }
  51517. try {
  51518. resolved = await pending;
  51519. hasResult = true;
  51520. isConstant = false;
  51521. } finally {
  51522. pending = void 0;
  51523. }
  51524. return resolved;
  51525. }, "coalesceProvider");
  51526. if (isExpired === void 0) {
  51527. return async (options) => {
  51528. if (!hasResult || (options == null ? void 0 : options.forceRefresh)) {
  51529. resolved = await coalesceProvider();
  51530. }
  51531. return resolved;
  51532. };
  51533. }
  51534. return async (options) => {
  51535. if (!hasResult || (options == null ? void 0 : options.forceRefresh)) {
  51536. resolved = await coalesceProvider();
  51537. }
  51538. if (isConstant) {
  51539. return resolved;
  51540. }
  51541. if (requiresRefresh && !requiresRefresh(resolved)) {
  51542. isConstant = true;
  51543. return resolved;
  51544. }
  51545. if (isExpired(resolved)) {
  51546. await coalesceProvider();
  51547. return resolved;
  51548. }
  51549. return resolved;
  51550. };
  51551. }, "memoize");
  51552. }
  51553. });
  51554. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js
  51555. var import_property_provider, resolveAwsSdkSigV4AConfig, NODE_SIGV4A_CONFIG_OPTIONS;
  51556. var init_resolveAwsSdkSigV4AConfig = __esm({
  51557. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js"() {
  51558. init_dist_es();
  51559. import_property_provider = __toESM(require_dist_cjs20());
  51560. resolveAwsSdkSigV4AConfig = (config) => {
  51561. config.sigv4aSigningRegionSet = normalizeProvider(config.sigv4aSigningRegionSet);
  51562. return config;
  51563. };
  51564. NODE_SIGV4A_CONFIG_OPTIONS = {
  51565. environmentVariableSelector(env3) {
  51566. if (env3.AWS_SIGV4A_SIGNING_REGION_SET) {
  51567. return env3.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_3) => _3.trim());
  51568. }
  51569. throw new import_property_provider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", {
  51570. tryNextLink: true
  51571. });
  51572. },
  51573. configFileSelector(profile) {
  51574. if (profile.sigv4a_signing_region_set) {
  51575. return (profile.sigv4a_signing_region_set ?? "").split(",").map((_3) => _3.trim());
  51576. }
  51577. throw new import_property_provider.ProviderError("sigv4a_signing_region_set not set in profile.", {
  51578. tryNextLink: true
  51579. });
  51580. },
  51581. default: void 0
  51582. };
  51583. }
  51584. });
  51585. // ../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-cjs/index.js
  51586. var require_dist_cjs21 = __commonJS({
  51587. "../node_modules/.pnpm/@smithy+signature-v4@5.1.2/node_modules/@smithy/signature-v4/dist-cjs/index.js"(exports2, module2) {
  51588. var __defProp3 = Object.defineProperty;
  51589. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  51590. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  51591. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  51592. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  51593. var __export2 = (target, all) => {
  51594. for (var name in all)
  51595. __defProp3(target, name, { get: all[name], enumerable: true });
  51596. };
  51597. var __copyProps3 = (to, from, except, desc) => {
  51598. if (from && typeof from === "object" || typeof from === "function") {
  51599. for (let key of __getOwnPropNames3(from))
  51600. if (!__hasOwnProp3.call(to, key) && key !== except)
  51601. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  51602. }
  51603. return to;
  51604. };
  51605. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  51606. var src_exports = {};
  51607. __export2(src_exports, {
  51608. ALGORITHM_IDENTIFIER: () => ALGORITHM_IDENTIFIER,
  51609. ALGORITHM_IDENTIFIER_V4A: () => ALGORITHM_IDENTIFIER_V4A,
  51610. ALGORITHM_QUERY_PARAM: () => ALGORITHM_QUERY_PARAM,
  51611. ALWAYS_UNSIGNABLE_HEADERS: () => ALWAYS_UNSIGNABLE_HEADERS,
  51612. AMZ_DATE_HEADER: () => AMZ_DATE_HEADER,
  51613. AMZ_DATE_QUERY_PARAM: () => AMZ_DATE_QUERY_PARAM,
  51614. AUTH_HEADER: () => AUTH_HEADER,
  51615. CREDENTIAL_QUERY_PARAM: () => CREDENTIAL_QUERY_PARAM,
  51616. DATE_HEADER: () => DATE_HEADER,
  51617. EVENT_ALGORITHM_IDENTIFIER: () => EVENT_ALGORITHM_IDENTIFIER,
  51618. EXPIRES_QUERY_PARAM: () => EXPIRES_QUERY_PARAM,
  51619. GENERATED_HEADERS: () => GENERATED_HEADERS,
  51620. HOST_HEADER: () => HOST_HEADER,
  51621. KEY_TYPE_IDENTIFIER: () => KEY_TYPE_IDENTIFIER,
  51622. MAX_CACHE_SIZE: () => MAX_CACHE_SIZE,
  51623. MAX_PRESIGNED_TTL: () => MAX_PRESIGNED_TTL,
  51624. PROXY_HEADER_PATTERN: () => PROXY_HEADER_PATTERN,
  51625. REGION_SET_PARAM: () => REGION_SET_PARAM,
  51626. SEC_HEADER_PATTERN: () => SEC_HEADER_PATTERN,
  51627. SHA256_HEADER: () => SHA256_HEADER,
  51628. SIGNATURE_HEADER: () => SIGNATURE_HEADER,
  51629. SIGNATURE_QUERY_PARAM: () => SIGNATURE_QUERY_PARAM,
  51630. SIGNED_HEADERS_QUERY_PARAM: () => SIGNED_HEADERS_QUERY_PARAM,
  51631. SignatureV4: () => SignatureV42,
  51632. SignatureV4Base: () => SignatureV4Base,
  51633. TOKEN_HEADER: () => TOKEN_HEADER,
  51634. TOKEN_QUERY_PARAM: () => TOKEN_QUERY_PARAM,
  51635. UNSIGNABLE_PATTERNS: () => UNSIGNABLE_PATTERNS,
  51636. UNSIGNED_PAYLOAD: () => UNSIGNED_PAYLOAD,
  51637. clearCredentialCache: () => clearCredentialCache,
  51638. createScope: () => createScope,
  51639. getCanonicalHeaders: () => getCanonicalHeaders,
  51640. getCanonicalQuery: () => getCanonicalQuery,
  51641. getPayloadHash: () => getPayloadHash,
  51642. getSigningKey: () => getSigningKey,
  51643. hasHeader: () => hasHeader,
  51644. moveHeadersToQuery: () => moveHeadersToQuery,
  51645. prepareRequest: () => prepareRequest,
  51646. signatureV4aContainer: () => signatureV4aContainer
  51647. });
  51648. module2.exports = __toCommonJS2(src_exports);
  51649. var import_util_utf85 = require_dist_cjs10();
  51650. var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
  51651. var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
  51652. var AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
  51653. var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
  51654. var EXPIRES_QUERY_PARAM = "X-Amz-Expires";
  51655. var SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
  51656. var TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
  51657. var REGION_SET_PARAM = "X-Amz-Region-Set";
  51658. var AUTH_HEADER = "authorization";
  51659. var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
  51660. var DATE_HEADER = "date";
  51661. var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];
  51662. var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
  51663. var SHA256_HEADER = "x-amz-content-sha256";
  51664. var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
  51665. var HOST_HEADER = "host";
  51666. var ALWAYS_UNSIGNABLE_HEADERS = {
  51667. authorization: true,
  51668. "cache-control": true,
  51669. connection: true,
  51670. expect: true,
  51671. from: true,
  51672. "keep-alive": true,
  51673. "max-forwards": true,
  51674. pragma: true,
  51675. referer: true,
  51676. te: true,
  51677. trailer: true,
  51678. "transfer-encoding": true,
  51679. upgrade: true,
  51680. "user-agent": true,
  51681. "x-amzn-trace-id": true
  51682. };
  51683. var PROXY_HEADER_PATTERN = /^proxy-/;
  51684. var SEC_HEADER_PATTERN = /^sec-/;
  51685. var UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i];
  51686. var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
  51687. var ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256";
  51688. var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
  51689. var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
  51690. var MAX_CACHE_SIZE = 50;
  51691. var KEY_TYPE_IDENTIFIER = "aws4_request";
  51692. var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;
  51693. var import_util_hex_encoding = require_dist_cjs16();
  51694. var import_util_utf86 = require_dist_cjs10();
  51695. var signingKeyCache = {};
  51696. var cacheQueue = [];
  51697. var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope");
  51698. var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials2, shortDate, region, service) => {
  51699. const credsHash = await hmac(sha256Constructor, credentials2.secretAccessKey, credentials2.accessKeyId);
  51700. const cacheKey2 = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.toHex)(credsHash)}:${credentials2.sessionToken}`;
  51701. if (cacheKey2 in signingKeyCache) {
  51702. return signingKeyCache[cacheKey2];
  51703. }
  51704. cacheQueue.push(cacheKey2);
  51705. while (cacheQueue.length > MAX_CACHE_SIZE) {
  51706. delete signingKeyCache[cacheQueue.shift()];
  51707. }
  51708. let key = `AWS4${credentials2.secretAccessKey}`;
  51709. for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) {
  51710. key = await hmac(sha256Constructor, key, signable);
  51711. }
  51712. return signingKeyCache[cacheKey2] = key;
  51713. }, "getSigningKey");
  51714. var clearCredentialCache = /* @__PURE__ */ __name(() => {
  51715. cacheQueue.length = 0;
  51716. Object.keys(signingKeyCache).forEach((cacheKey2) => {
  51717. delete signingKeyCache[cacheKey2];
  51718. });
  51719. }, "clearCredentialCache");
  51720. var hmac = /* @__PURE__ */ __name((ctor, secret, data) => {
  51721. const hash = new ctor(secret);
  51722. hash.update((0, import_util_utf86.toUint8Array)(data));
  51723. return hash.digest();
  51724. }, "hmac");
  51725. var getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => {
  51726. const canonical = {};
  51727. for (const headerName of Object.keys(headers).sort()) {
  51728. if (headers[headerName] == void 0) {
  51729. continue;
  51730. }
  51731. const canonicalHeaderName = headerName.toLowerCase();
  51732. if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || (unsignableHeaders == null ? void 0 : unsignableHeaders.has(canonicalHeaderName)) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) {
  51733. if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) {
  51734. continue;
  51735. }
  51736. }
  51737. canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
  51738. }
  51739. return canonical;
  51740. }, "getCanonicalHeaders");
  51741. var import_is_array_buffer = require_dist_cjs8();
  51742. var import_util_utf822 = require_dist_cjs10();
  51743. var getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => {
  51744. for (const headerName of Object.keys(headers)) {
  51745. if (headerName.toLowerCase() === SHA256_HEADER) {
  51746. return headers[headerName];
  51747. }
  51748. }
  51749. if (body == void 0) {
  51750. return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
  51751. } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, import_is_array_buffer.isArrayBuffer)(body)) {
  51752. const hashCtor = new hashConstructor();
  51753. hashCtor.update((0, import_util_utf822.toUint8Array)(body));
  51754. return (0, import_util_hex_encoding.toHex)(await hashCtor.digest());
  51755. }
  51756. return UNSIGNED_PAYLOAD;
  51757. }, "getPayloadHash");
  51758. var import_util_utf832 = require_dist_cjs10();
  51759. var _a2;
  51760. var HeaderFormatter = (_a2 = class {
  51761. format(headers) {
  51762. const chunks = [];
  51763. for (const headerName of Object.keys(headers)) {
  51764. const bytes = (0, import_util_utf832.fromUtf8)(headerName);
  51765. chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
  51766. }
  51767. const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
  51768. let position = 0;
  51769. for (const chunk of chunks) {
  51770. out.set(chunk, position);
  51771. position += chunk.byteLength;
  51772. }
  51773. return out;
  51774. }
  51775. formatHeaderValue(header) {
  51776. switch (header.type) {
  51777. case "boolean":
  51778. return Uint8Array.from([
  51779. header.value ? 0 : 1
  51780. /* boolFalse */
  51781. ]);
  51782. case "byte":
  51783. return Uint8Array.from([2, header.value]);
  51784. case "short":
  51785. const shortView = new DataView(new ArrayBuffer(3));
  51786. shortView.setUint8(
  51787. 0,
  51788. 3
  51789. /* short */
  51790. );
  51791. shortView.setInt16(1, header.value, false);
  51792. return new Uint8Array(shortView.buffer);
  51793. case "integer":
  51794. const intView = new DataView(new ArrayBuffer(5));
  51795. intView.setUint8(
  51796. 0,
  51797. 4
  51798. /* integer */
  51799. );
  51800. intView.setInt32(1, header.value, false);
  51801. return new Uint8Array(intView.buffer);
  51802. case "long":
  51803. const longBytes = new Uint8Array(9);
  51804. longBytes[0] = 5;
  51805. longBytes.set(header.value.bytes, 1);
  51806. return longBytes;
  51807. case "binary":
  51808. const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
  51809. binView.setUint8(
  51810. 0,
  51811. 6
  51812. /* byteArray */
  51813. );
  51814. binView.setUint16(1, header.value.byteLength, false);
  51815. const binBytes = new Uint8Array(binView.buffer);
  51816. binBytes.set(header.value, 3);
  51817. return binBytes;
  51818. case "string":
  51819. const utf8Bytes = (0, import_util_utf832.fromUtf8)(header.value);
  51820. const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
  51821. strView.setUint8(
  51822. 0,
  51823. 7
  51824. /* string */
  51825. );
  51826. strView.setUint16(1, utf8Bytes.byteLength, false);
  51827. const strBytes = new Uint8Array(strView.buffer);
  51828. strBytes.set(utf8Bytes, 3);
  51829. return strBytes;
  51830. case "timestamp":
  51831. const tsBytes = new Uint8Array(9);
  51832. tsBytes[0] = 8;
  51833. tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);
  51834. return tsBytes;
  51835. case "uuid":
  51836. if (!UUID_PATTERN.test(header.value)) {
  51837. throw new Error(`Invalid UUID received: ${header.value}`);
  51838. }
  51839. const uuidBytes = new Uint8Array(17);
  51840. uuidBytes[0] = 9;
  51841. uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1);
  51842. return uuidBytes;
  51843. }
  51844. }
  51845. }, __name(_a2, "HeaderFormatter"), _a2);
  51846. var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
  51847. var _a3;
  51848. var Int64 = (_a3 = class {
  51849. constructor(bytes) {
  51850. this.bytes = bytes;
  51851. if (bytes.byteLength !== 8) {
  51852. throw new Error("Int64 buffers must be exactly 8 bytes");
  51853. }
  51854. }
  51855. static fromNumber(number2) {
  51856. if (number2 > 9223372036854776e3 || number2 < -9223372036854776e3) {
  51857. throw new Error(`${number2} is too large (or, if negative, too small) to represent as an Int64`);
  51858. }
  51859. const bytes = new Uint8Array(8);
  51860. for (let i4 = 7, remaining = Math.abs(Math.round(number2)); i4 > -1 && remaining > 0; i4--, remaining /= 256) {
  51861. bytes[i4] = remaining;
  51862. }
  51863. if (number2 < 0) {
  51864. negate(bytes);
  51865. }
  51866. return new _a3(bytes);
  51867. }
  51868. /**
  51869. * Called implicitly by infix arithmetic operators.
  51870. */
  51871. valueOf() {
  51872. const bytes = this.bytes.slice(0);
  51873. const negative = bytes[0] & 128;
  51874. if (negative) {
  51875. negate(bytes);
  51876. }
  51877. return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1);
  51878. }
  51879. toString() {
  51880. return String(this.valueOf());
  51881. }
  51882. }, __name(_a3, "Int64"), _a3);
  51883. function negate(bytes) {
  51884. for (let i4 = 0; i4 < 8; i4++) {
  51885. bytes[i4] ^= 255;
  51886. }
  51887. for (let i4 = 7; i4 > -1; i4--) {
  51888. bytes[i4]++;
  51889. if (bytes[i4] !== 0)
  51890. break;
  51891. }
  51892. }
  51893. __name(negate, "negate");
  51894. var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => {
  51895. soughtHeader = soughtHeader.toLowerCase();
  51896. for (const headerName of Object.keys(headers)) {
  51897. if (soughtHeader === headerName.toLowerCase()) {
  51898. return true;
  51899. }
  51900. }
  51901. return false;
  51902. }, "hasHeader");
  51903. var import_protocol_http15 = require_dist_cjs2();
  51904. var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => {
  51905. var _a6, _b;
  51906. const { headers, query = {} } = import_protocol_http15.HttpRequest.clone(request);
  51907. for (const name of Object.keys(headers)) {
  51908. const lname = name.toLowerCase();
  51909. if (lname.slice(0, 6) === "x-amz-" && !((_a6 = options.unhoistableHeaders) == null ? void 0 : _a6.has(lname)) || ((_b = options.hoistableHeaders) == null ? void 0 : _b.has(lname))) {
  51910. query[name] = headers[name];
  51911. delete headers[name];
  51912. }
  51913. }
  51914. return {
  51915. ...request,
  51916. headers,
  51917. query
  51918. };
  51919. }, "moveHeadersToQuery");
  51920. var prepareRequest = /* @__PURE__ */ __name((request) => {
  51921. request = import_protocol_http15.HttpRequest.clone(request);
  51922. for (const headerName of Object.keys(request.headers)) {
  51923. if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
  51924. delete request.headers[headerName];
  51925. }
  51926. }
  51927. return request;
  51928. }, "prepareRequest");
  51929. var import_util_middleware7 = require_dist_cjs6();
  51930. var import_util_utf842 = require_dist_cjs10();
  51931. var import_util_uri_escape = require_dist_cjs12();
  51932. var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => {
  51933. const keys = [];
  51934. const serialized = {};
  51935. for (const key of Object.keys(query)) {
  51936. if (key.toLowerCase() === SIGNATURE_HEADER) {
  51937. continue;
  51938. }
  51939. const encodedKey = (0, import_util_uri_escape.escapeUri)(key);
  51940. keys.push(encodedKey);
  51941. const value = query[key];
  51942. if (typeof value === "string") {
  51943. serialized[encodedKey] = `${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value)}`;
  51944. } else if (Array.isArray(value)) {
  51945. serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${(0, import_util_uri_escape.escapeUri)(value2)}`]), []).sort().join("&");
  51946. }
  51947. }
  51948. return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&");
  51949. }, "getCanonicalQuery");
  51950. var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601");
  51951. var toDate = /* @__PURE__ */ __name((time) => {
  51952. if (typeof time === "number") {
  51953. return new Date(time * 1e3);
  51954. }
  51955. if (typeof time === "string") {
  51956. if (Number(time)) {
  51957. return new Date(Number(time) * 1e3);
  51958. }
  51959. return new Date(time);
  51960. }
  51961. return time;
  51962. }, "toDate");
  51963. var _a4;
  51964. var SignatureV4Base = (_a4 = class {
  51965. constructor({
  51966. applyChecksum,
  51967. credentials: credentials2,
  51968. region,
  51969. service,
  51970. sha256: sha2562,
  51971. uriEscapePath = true
  51972. }) {
  51973. this.service = service;
  51974. this.sha256 = sha2562;
  51975. this.uriEscapePath = uriEscapePath;
  51976. this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
  51977. this.regionProvider = (0, import_util_middleware7.normalizeProvider)(region);
  51978. this.credentialProvider = (0, import_util_middleware7.normalizeProvider)(credentials2);
  51979. }
  51980. createCanonicalRequest(request, canonicalHeaders, payloadHash) {
  51981. const sortedHeaders = Object.keys(canonicalHeaders).sort();
  51982. return `${request.method}
  51983. ${this.getCanonicalPath(request)}
  51984. ${getCanonicalQuery(request)}
  51985. ${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")}
  51986. ${sortedHeaders.join(";")}
  51987. ${payloadHash}`;
  51988. }
  51989. async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) {
  51990. const hash = new this.sha256();
  51991. hash.update((0, import_util_utf842.toUint8Array)(canonicalRequest));
  51992. const hashedRequest = await hash.digest();
  51993. return `${algorithmIdentifier}
  51994. ${longDate}
  51995. ${credentialScope}
  51996. ${(0, import_util_hex_encoding.toHex)(hashedRequest)}`;
  51997. }
  51998. getCanonicalPath({ path: path4 }) {
  51999. if (this.uriEscapePath) {
  52000. const normalizedPathSegments = [];
  52001. for (const pathSegment of path4.split("/")) {
  52002. if ((pathSegment == null ? void 0 : pathSegment.length) === 0)
  52003. continue;
  52004. if (pathSegment === ".")
  52005. continue;
  52006. if (pathSegment === "..") {
  52007. normalizedPathSegments.pop();
  52008. } else {
  52009. normalizedPathSegments.push(pathSegment);
  52010. }
  52011. }
  52012. const normalizedPath = `${(path4 == null ? void 0 : path4.startsWith("/")) ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && (path4 == null ? void 0 : path4.endsWith("/")) ? "/" : ""}`;
  52013. const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath);
  52014. return doubleEncoded.replace(/%2F/g, "/");
  52015. }
  52016. return path4;
  52017. }
  52018. validateResolvedCredentials(credentials2) {
  52019. if (typeof credentials2 !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339)
  52020. typeof credentials2.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339)
  52021. typeof credentials2.secretAccessKey !== "string") {
  52022. throw new Error("Resolved credential object is not valid");
  52023. }
  52024. }
  52025. formatDate(now) {
  52026. const longDate = iso8601(now).replace(/[\-:]/g, "");
  52027. return {
  52028. longDate,
  52029. shortDate: longDate.slice(0, 8)
  52030. };
  52031. }
  52032. getCanonicalHeaderList(headers) {
  52033. return Object.keys(headers).sort().join(";");
  52034. }
  52035. }, __name(_a4, "SignatureV4Base"), _a4);
  52036. var _a5;
  52037. var SignatureV42 = (_a5 = class extends SignatureV4Base {
  52038. constructor({
  52039. applyChecksum,
  52040. credentials: credentials2,
  52041. region,
  52042. service,
  52043. sha256: sha2562,
  52044. uriEscapePath = true
  52045. }) {
  52046. super({
  52047. applyChecksum,
  52048. credentials: credentials2,
  52049. region,
  52050. service,
  52051. sha256: sha2562,
  52052. uriEscapePath
  52053. });
  52054. this.headerFormatter = new HeaderFormatter();
  52055. }
  52056. async presign(originalRequest, options = {}) {
  52057. const {
  52058. signingDate = /* @__PURE__ */ new Date(),
  52059. expiresIn = 3600,
  52060. unsignableHeaders,
  52061. unhoistableHeaders,
  52062. signableHeaders,
  52063. hoistableHeaders,
  52064. signingRegion,
  52065. signingService
  52066. } = options;
  52067. const credentials2 = await this.credentialProvider();
  52068. this.validateResolvedCredentials(credentials2);
  52069. const region = signingRegion ?? await this.regionProvider();
  52070. const { longDate, shortDate } = this.formatDate(signingDate);
  52071. if (expiresIn > MAX_PRESIGNED_TTL) {
  52072. return Promise.reject(
  52073. "Signature version 4 presigned URLs must have an expiration date less than one week in the future"
  52074. );
  52075. }
  52076. const scope = createScope(shortDate, region, signingService ?? this.service);
  52077. const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders });
  52078. if (credentials2.sessionToken) {
  52079. request.query[TOKEN_QUERY_PARAM] = credentials2.sessionToken;
  52080. }
  52081. request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
  52082. request.query[CREDENTIAL_QUERY_PARAM] = `${credentials2.accessKeyId}/${scope}`;
  52083. request.query[AMZ_DATE_QUERY_PARAM] = longDate;
  52084. request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
  52085. const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);
  52086. request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders);
  52087. request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(
  52088. longDate,
  52089. scope,
  52090. this.getSigningKey(credentials2, region, shortDate, signingService),
  52091. this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))
  52092. );
  52093. return request;
  52094. }
  52095. async sign(toSign, options) {
  52096. if (typeof toSign === "string") {
  52097. return this.signString(toSign, options);
  52098. } else if (toSign.headers && toSign.payload) {
  52099. return this.signEvent(toSign, options);
  52100. } else if (toSign.message) {
  52101. return this.signMessage(toSign, options);
  52102. } else {
  52103. return this.signRequest(toSign, options);
  52104. }
  52105. }
  52106. async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) {
  52107. const region = signingRegion ?? await this.regionProvider();
  52108. const { shortDate, longDate } = this.formatDate(signingDate);
  52109. const scope = createScope(shortDate, region, signingService ?? this.service);
  52110. const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);
  52111. const hash = new this.sha256();
  52112. hash.update(headers);
  52113. const hashedHeaders = (0, import_util_hex_encoding.toHex)(await hash.digest());
  52114. const stringToSign = [
  52115. EVENT_ALGORITHM_IDENTIFIER,
  52116. longDate,
  52117. scope,
  52118. priorSignature,
  52119. hashedHeaders,
  52120. hashedPayload
  52121. ].join("\n");
  52122. return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
  52123. }
  52124. async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) {
  52125. const promise = this.signEvent(
  52126. {
  52127. headers: this.headerFormatter.format(signableMessage.message.headers),
  52128. payload: signableMessage.message.body
  52129. },
  52130. {
  52131. signingDate,
  52132. signingRegion,
  52133. signingService,
  52134. priorSignature: signableMessage.priorSignature
  52135. }
  52136. );
  52137. return promise.then((signature) => {
  52138. return { message: signableMessage.message, signature };
  52139. });
  52140. }
  52141. async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) {
  52142. const credentials2 = await this.credentialProvider();
  52143. this.validateResolvedCredentials(credentials2);
  52144. const region = signingRegion ?? await this.regionProvider();
  52145. const { shortDate } = this.formatDate(signingDate);
  52146. const hash = new this.sha256(await this.getSigningKey(credentials2, region, shortDate, signingService));
  52147. hash.update((0, import_util_utf85.toUint8Array)(stringToSign));
  52148. return (0, import_util_hex_encoding.toHex)(await hash.digest());
  52149. }
  52150. async signRequest(requestToSign, {
  52151. signingDate = /* @__PURE__ */ new Date(),
  52152. signableHeaders,
  52153. unsignableHeaders,
  52154. signingRegion,
  52155. signingService
  52156. } = {}) {
  52157. const credentials2 = await this.credentialProvider();
  52158. this.validateResolvedCredentials(credentials2);
  52159. const region = signingRegion ?? await this.regionProvider();
  52160. const request = prepareRequest(requestToSign);
  52161. const { longDate, shortDate } = this.formatDate(signingDate);
  52162. const scope = createScope(shortDate, region, signingService ?? this.service);
  52163. request.headers[AMZ_DATE_HEADER] = longDate;
  52164. if (credentials2.sessionToken) {
  52165. request.headers[TOKEN_HEADER] = credentials2.sessionToken;
  52166. }
  52167. const payloadHash = await getPayloadHash(request, this.sha256);
  52168. if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) {
  52169. request.headers[SHA256_HEADER] = payloadHash;
  52170. }
  52171. const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders);
  52172. const signature = await this.getSignature(
  52173. longDate,
  52174. scope,
  52175. this.getSigningKey(credentials2, region, shortDate, signingService),
  52176. this.createCanonicalRequest(request, canonicalHeaders, payloadHash)
  52177. );
  52178. request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials2.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`;
  52179. return request;
  52180. }
  52181. async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
  52182. const stringToSign = await this.createStringToSign(
  52183. longDate,
  52184. credentialScope,
  52185. canonicalRequest,
  52186. ALGORITHM_IDENTIFIER
  52187. );
  52188. const hash = new this.sha256(await keyPromise);
  52189. hash.update((0, import_util_utf85.toUint8Array)(stringToSign));
  52190. return (0, import_util_hex_encoding.toHex)(await hash.digest());
  52191. }
  52192. getSigningKey(credentials2, region, shortDate, service) {
  52193. return getSigningKey(this.sha256, credentials2, shortDate, region, service || this.service);
  52194. }
  52195. }, __name(_a5, "SignatureV4"), _a5);
  52196. var signatureV4aContainer = {
  52197. SignatureV4a: null
  52198. };
  52199. }
  52200. });
  52201. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js
  52202. function normalizeCredentialProvider(config, { credentials: credentials2, credentialDefaultProvider }) {
  52203. let credentialsProvider;
  52204. if (credentials2) {
  52205. if (!(credentials2 == null ? void 0 : credentials2.memoized)) {
  52206. credentialsProvider = memoizeIdentityProvider(credentials2, isIdentityExpired, doesIdentityRequireRefresh);
  52207. } else {
  52208. credentialsProvider = credentials2;
  52209. }
  52210. } else {
  52211. if (credentialDefaultProvider) {
  52212. credentialsProvider = normalizeProvider(credentialDefaultProvider(Object.assign({}, config, {
  52213. parentClientConfig: config
  52214. })));
  52215. } else {
  52216. credentialsProvider = async () => {
  52217. throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.");
  52218. };
  52219. }
  52220. }
  52221. credentialsProvider.memoized = true;
  52222. return credentialsProvider;
  52223. }
  52224. function bindCallerConfig(config, credentialsProvider) {
  52225. if (credentialsProvider.configBound) {
  52226. return credentialsProvider;
  52227. }
  52228. const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config });
  52229. fn.memoized = credentialsProvider.memoized;
  52230. fn.configBound = true;
  52231. return fn;
  52232. }
  52233. var import_signature_v4, resolveAwsSdkSigV4Config, resolveAWSSDKSigV4Config;
  52234. var init_resolveAwsSdkSigV4Config = __esm({
  52235. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js"() {
  52236. init_client();
  52237. init_dist_es();
  52238. import_signature_v4 = __toESM(require_dist_cjs21());
  52239. resolveAwsSdkSigV4Config = (config) => {
  52240. let inputCredentials = config.credentials;
  52241. let isUserSupplied = !!config.credentials;
  52242. let resolvedCredentials = void 0;
  52243. Object.defineProperty(config, "credentials", {
  52244. set(credentials2) {
  52245. if (credentials2 && credentials2 !== inputCredentials && credentials2 !== resolvedCredentials) {
  52246. isUserSupplied = true;
  52247. }
  52248. inputCredentials = credentials2;
  52249. const memoizedProvider = normalizeCredentialProvider(config, {
  52250. credentials: inputCredentials,
  52251. credentialDefaultProvider: config.credentialDefaultProvider
  52252. });
  52253. const boundProvider = bindCallerConfig(config, memoizedProvider);
  52254. if (isUserSupplied && !boundProvider.attributed) {
  52255. resolvedCredentials = async (options) => boundProvider(options).then((creds) => setCredentialFeature(creds, "CREDENTIALS_CODE", "e"));
  52256. resolvedCredentials.memoized = boundProvider.memoized;
  52257. resolvedCredentials.configBound = boundProvider.configBound;
  52258. resolvedCredentials.attributed = true;
  52259. } else {
  52260. resolvedCredentials = boundProvider;
  52261. }
  52262. },
  52263. get() {
  52264. return resolvedCredentials;
  52265. },
  52266. enumerable: true,
  52267. configurable: true
  52268. });
  52269. config.credentials = inputCredentials;
  52270. const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256: sha2562 } = config;
  52271. let signer;
  52272. if (config.signer) {
  52273. signer = normalizeProvider(config.signer);
  52274. } else if (config.regionInfoProvider) {
  52275. signer = () => normalizeProvider(config.region)().then(async (region) => [
  52276. await config.regionInfoProvider(region, {
  52277. useFipsEndpoint: await config.useFipsEndpoint(),
  52278. useDualstackEndpoint: await config.useDualstackEndpoint()
  52279. }) || {},
  52280. region
  52281. ]).then(([regionInfo, region]) => {
  52282. const { signingRegion, signingService } = regionInfo;
  52283. config.signingRegion = config.signingRegion || signingRegion || region;
  52284. config.signingName = config.signingName || signingService || config.serviceId;
  52285. const params = {
  52286. ...config,
  52287. credentials: config.credentials,
  52288. region: config.signingRegion,
  52289. service: config.signingName,
  52290. sha256: sha2562,
  52291. uriEscapePath: signingEscapePath
  52292. };
  52293. const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4;
  52294. return new SignerCtor(params);
  52295. });
  52296. } else {
  52297. signer = async (authScheme) => {
  52298. authScheme = Object.assign({}, {
  52299. name: "sigv4",
  52300. signingName: config.signingName || config.defaultSigningName,
  52301. signingRegion: await normalizeProvider(config.region)(),
  52302. properties: {}
  52303. }, authScheme);
  52304. const signingRegion = authScheme.signingRegion;
  52305. const signingService = authScheme.signingName;
  52306. config.signingRegion = config.signingRegion || signingRegion;
  52307. config.signingName = config.signingName || signingService || config.serviceId;
  52308. const params = {
  52309. ...config,
  52310. credentials: config.credentials,
  52311. region: config.signingRegion,
  52312. service: config.signingName,
  52313. sha256: sha2562,
  52314. uriEscapePath: signingEscapePath
  52315. };
  52316. const SignerCtor = config.signerConstructor || import_signature_v4.SignatureV4;
  52317. return new SignerCtor(params);
  52318. };
  52319. }
  52320. const resolvedConfig = Object.assign(config, {
  52321. systemClockOffset,
  52322. signingEscapePath,
  52323. signer
  52324. });
  52325. return resolvedConfig;
  52326. };
  52327. resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config;
  52328. }
  52329. });
  52330. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js
  52331. var init_aws_sdk = __esm({
  52332. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js"() {
  52333. init_AwsSdkSigV4Signer();
  52334. init_AwsSdkSigV4ASigner();
  52335. init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS();
  52336. init_resolveAwsSdkSigV4AConfig();
  52337. init_resolveAwsSdkSigV4Config();
  52338. }
  52339. });
  52340. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js
  52341. var init_httpAuthSchemes2 = __esm({
  52342. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js"() {
  52343. init_aws_sdk();
  52344. init_getBearerTokenEnvKey();
  52345. }
  52346. });
  52347. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js
  52348. var _toStr, _toBool, _toNum;
  52349. var init_coercing_serializers = __esm({
  52350. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js"() {
  52351. _toStr = (val2) => {
  52352. if (val2 == null) {
  52353. return val2;
  52354. }
  52355. if (typeof val2 === "number" || typeof val2 === "bigint") {
  52356. const warning3 = new Error(`Received number ${val2} where a string was expected.`);
  52357. warning3.name = "Warning";
  52358. console.warn(warning3);
  52359. return String(val2);
  52360. }
  52361. if (typeof val2 === "boolean") {
  52362. const warning3 = new Error(`Received boolean ${val2} where a string was expected.`);
  52363. warning3.name = "Warning";
  52364. console.warn(warning3);
  52365. return String(val2);
  52366. }
  52367. return val2;
  52368. };
  52369. _toBool = (val2) => {
  52370. if (val2 == null) {
  52371. return val2;
  52372. }
  52373. if (typeof val2 === "number") {
  52374. }
  52375. if (typeof val2 === "string") {
  52376. const lowercase = val2.toLowerCase();
  52377. if (val2 !== "" && lowercase !== "false" && lowercase !== "true") {
  52378. const warning3 = new Error(`Received string "${val2}" where a boolean was expected.`);
  52379. warning3.name = "Warning";
  52380. console.warn(warning3);
  52381. }
  52382. return val2 !== "" && lowercase !== "false";
  52383. }
  52384. return val2;
  52385. };
  52386. _toNum = (val2) => {
  52387. if (val2 == null) {
  52388. return val2;
  52389. }
  52390. if (typeof val2 === "boolean") {
  52391. }
  52392. if (typeof val2 === "string") {
  52393. const num = Number(val2);
  52394. if (num.toString() !== val2) {
  52395. const warning3 = new Error(`Received string "${val2}" where a number was expected.`);
  52396. warning3.name = "Warning";
  52397. console.warn(warning3);
  52398. return val2;
  52399. }
  52400. return num;
  52401. }
  52402. return val2;
  52403. };
  52404. }
  52405. });
  52406. // ../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-cjs/index.js
  52407. var require_dist_cjs22 = __commonJS({
  52408. "../node_modules/.pnpm/@smithy+middleware-stack@4.0.4/node_modules/@smithy/middleware-stack/dist-cjs/index.js"(exports2, module2) {
  52409. var __defProp3 = Object.defineProperty;
  52410. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  52411. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  52412. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  52413. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  52414. var __export2 = (target, all) => {
  52415. for (var name in all)
  52416. __defProp3(target, name, { get: all[name], enumerable: true });
  52417. };
  52418. var __copyProps3 = (to, from, except, desc) => {
  52419. if (from && typeof from === "object" || typeof from === "function") {
  52420. for (let key of __getOwnPropNames3(from))
  52421. if (!__hasOwnProp3.call(to, key) && key !== except)
  52422. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  52423. }
  52424. return to;
  52425. };
  52426. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  52427. var src_exports = {};
  52428. __export2(src_exports, {
  52429. constructStack: () => constructStack
  52430. });
  52431. module2.exports = __toCommonJS2(src_exports);
  52432. var getAllAliases = /* @__PURE__ */ __name((name, aliases) => {
  52433. const _aliases = [];
  52434. if (name) {
  52435. _aliases.push(name);
  52436. }
  52437. if (aliases) {
  52438. for (const alias of aliases) {
  52439. _aliases.push(alias);
  52440. }
  52441. }
  52442. return _aliases;
  52443. }, "getAllAliases");
  52444. var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => {
  52445. return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`;
  52446. }, "getMiddlewareNameWithAliases");
  52447. var constructStack = /* @__PURE__ */ __name(() => {
  52448. let absoluteEntries = [];
  52449. let relativeEntries = [];
  52450. let identifyOnResolve = false;
  52451. const entriesNameSet = /* @__PURE__ */ new Set();
  52452. const sort = /* @__PURE__ */ __name((entries) => entries.sort(
  52453. (a3, b3) => stepWeights[b3.step] - stepWeights[a3.step] || priorityWeights[b3.priority || "normal"] - priorityWeights[a3.priority || "normal"]
  52454. ), "sort");
  52455. const removeByName = /* @__PURE__ */ __name((toRemove) => {
  52456. let isRemoved = false;
  52457. const filterCb = /* @__PURE__ */ __name((entry) => {
  52458. const aliases = getAllAliases(entry.name, entry.aliases);
  52459. if (aliases.includes(toRemove)) {
  52460. isRemoved = true;
  52461. for (const alias of aliases) {
  52462. entriesNameSet.delete(alias);
  52463. }
  52464. return false;
  52465. }
  52466. return true;
  52467. }, "filterCb");
  52468. absoluteEntries = absoluteEntries.filter(filterCb);
  52469. relativeEntries = relativeEntries.filter(filterCb);
  52470. return isRemoved;
  52471. }, "removeByName");
  52472. const removeByReference = /* @__PURE__ */ __name((toRemove) => {
  52473. let isRemoved = false;
  52474. const filterCb = /* @__PURE__ */ __name((entry) => {
  52475. if (entry.middleware === toRemove) {
  52476. isRemoved = true;
  52477. for (const alias of getAllAliases(entry.name, entry.aliases)) {
  52478. entriesNameSet.delete(alias);
  52479. }
  52480. return false;
  52481. }
  52482. return true;
  52483. }, "filterCb");
  52484. absoluteEntries = absoluteEntries.filter(filterCb);
  52485. relativeEntries = relativeEntries.filter(filterCb);
  52486. return isRemoved;
  52487. }, "removeByReference");
  52488. const cloneTo = /* @__PURE__ */ __name((toStack) => {
  52489. var _a2;
  52490. absoluteEntries.forEach((entry) => {
  52491. toStack.add(entry.middleware, { ...entry });
  52492. });
  52493. relativeEntries.forEach((entry) => {
  52494. toStack.addRelativeTo(entry.middleware, { ...entry });
  52495. });
  52496. (_a2 = toStack.identifyOnResolve) == null ? void 0 : _a2.call(toStack, stack.identifyOnResolve());
  52497. return toStack;
  52498. }, "cloneTo");
  52499. const expandRelativeMiddlewareList = /* @__PURE__ */ __name((from) => {
  52500. const expandedMiddlewareList = [];
  52501. from.before.forEach((entry) => {
  52502. if (entry.before.length === 0 && entry.after.length === 0) {
  52503. expandedMiddlewareList.push(entry);
  52504. } else {
  52505. expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
  52506. }
  52507. });
  52508. expandedMiddlewareList.push(from);
  52509. from.after.reverse().forEach((entry) => {
  52510. if (entry.before.length === 0 && entry.after.length === 0) {
  52511. expandedMiddlewareList.push(entry);
  52512. } else {
  52513. expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry));
  52514. }
  52515. });
  52516. return expandedMiddlewareList;
  52517. }, "expandRelativeMiddlewareList");
  52518. const getMiddlewareList = /* @__PURE__ */ __name((debug = false) => {
  52519. const normalizedAbsoluteEntries = [];
  52520. const normalizedRelativeEntries = [];
  52521. const normalizedEntriesNameMap = {};
  52522. absoluteEntries.forEach((entry) => {
  52523. const normalizedEntry = {
  52524. ...entry,
  52525. before: [],
  52526. after: []
  52527. };
  52528. for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
  52529. normalizedEntriesNameMap[alias] = normalizedEntry;
  52530. }
  52531. normalizedAbsoluteEntries.push(normalizedEntry);
  52532. });
  52533. relativeEntries.forEach((entry) => {
  52534. const normalizedEntry = {
  52535. ...entry,
  52536. before: [],
  52537. after: []
  52538. };
  52539. for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
  52540. normalizedEntriesNameMap[alias] = normalizedEntry;
  52541. }
  52542. normalizedRelativeEntries.push(normalizedEntry);
  52543. });
  52544. normalizedRelativeEntries.forEach((entry) => {
  52545. if (entry.toMiddleware) {
  52546. const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware];
  52547. if (toMiddleware === void 0) {
  52548. if (debug) {
  52549. return;
  52550. }
  52551. throw new Error(
  52552. `${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`
  52553. );
  52554. }
  52555. if (entry.relation === "after") {
  52556. toMiddleware.after.push(entry);
  52557. }
  52558. if (entry.relation === "before") {
  52559. toMiddleware.before.push(entry);
  52560. }
  52561. }
  52562. });
  52563. const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce(
  52564. (wholeList, expandedMiddlewareList) => {
  52565. wholeList.push(...expandedMiddlewareList);
  52566. return wholeList;
  52567. },
  52568. []
  52569. );
  52570. return mainChain;
  52571. }, "getMiddlewareList");
  52572. const stack = {
  52573. add: (middleware, options = {}) => {
  52574. const { name, override, aliases: _aliases } = options;
  52575. const entry = {
  52576. step: "initialize",
  52577. priority: "normal",
  52578. middleware,
  52579. ...options
  52580. };
  52581. const aliases = getAllAliases(name, _aliases);
  52582. if (aliases.length > 0) {
  52583. if (aliases.some((alias) => entriesNameSet.has(alias))) {
  52584. if (!override)
  52585. throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
  52586. for (const alias of aliases) {
  52587. const toOverrideIndex = absoluteEntries.findIndex(
  52588. (entry2) => {
  52589. var _a2;
  52590. return entry2.name === alias || ((_a2 = entry2.aliases) == null ? void 0 : _a2.some((a3) => a3 === alias));
  52591. }
  52592. );
  52593. if (toOverrideIndex === -1) {
  52594. continue;
  52595. }
  52596. const toOverride = absoluteEntries[toOverrideIndex];
  52597. if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) {
  52598. throw new Error(
  52599. `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`
  52600. );
  52601. }
  52602. absoluteEntries.splice(toOverrideIndex, 1);
  52603. }
  52604. }
  52605. for (const alias of aliases) {
  52606. entriesNameSet.add(alias);
  52607. }
  52608. }
  52609. absoluteEntries.push(entry);
  52610. },
  52611. addRelativeTo: (middleware, options) => {
  52612. const { name, override, aliases: _aliases } = options;
  52613. const entry = {
  52614. middleware,
  52615. ...options
  52616. };
  52617. const aliases = getAllAliases(name, _aliases);
  52618. if (aliases.length > 0) {
  52619. if (aliases.some((alias) => entriesNameSet.has(alias))) {
  52620. if (!override)
  52621. throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`);
  52622. for (const alias of aliases) {
  52623. const toOverrideIndex = relativeEntries.findIndex(
  52624. (entry2) => {
  52625. var _a2;
  52626. return entry2.name === alias || ((_a2 = entry2.aliases) == null ? void 0 : _a2.some((a3) => a3 === alias));
  52627. }
  52628. );
  52629. if (toOverrideIndex === -1) {
  52630. continue;
  52631. }
  52632. const toOverride = relativeEntries[toOverrideIndex];
  52633. if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) {
  52634. throw new Error(
  52635. `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`
  52636. );
  52637. }
  52638. relativeEntries.splice(toOverrideIndex, 1);
  52639. }
  52640. }
  52641. for (const alias of aliases) {
  52642. entriesNameSet.add(alias);
  52643. }
  52644. }
  52645. relativeEntries.push(entry);
  52646. },
  52647. clone: () => cloneTo(constructStack()),
  52648. use: (plugin) => {
  52649. plugin.applyToStack(stack);
  52650. },
  52651. remove: (toRemove) => {
  52652. if (typeof toRemove === "string")
  52653. return removeByName(toRemove);
  52654. else
  52655. return removeByReference(toRemove);
  52656. },
  52657. removeByTag: (toRemove) => {
  52658. let isRemoved = false;
  52659. const filterCb = /* @__PURE__ */ __name((entry) => {
  52660. const { tags, name, aliases: _aliases } = entry;
  52661. if (tags && tags.includes(toRemove)) {
  52662. const aliases = getAllAliases(name, _aliases);
  52663. for (const alias of aliases) {
  52664. entriesNameSet.delete(alias);
  52665. }
  52666. isRemoved = true;
  52667. return false;
  52668. }
  52669. return true;
  52670. }, "filterCb");
  52671. absoluteEntries = absoluteEntries.filter(filterCb);
  52672. relativeEntries = relativeEntries.filter(filterCb);
  52673. return isRemoved;
  52674. },
  52675. concat: (from) => {
  52676. var _a2;
  52677. const cloned = cloneTo(constructStack());
  52678. cloned.use(from);
  52679. cloned.identifyOnResolve(
  52680. identifyOnResolve || cloned.identifyOnResolve() || (((_a2 = from.identifyOnResolve) == null ? void 0 : _a2.call(from)) ?? false)
  52681. );
  52682. return cloned;
  52683. },
  52684. applyToStack: cloneTo,
  52685. identify: () => {
  52686. return getMiddlewareList(true).map((mw) => {
  52687. const step = mw.step ?? mw.relation + " " + mw.toMiddleware;
  52688. return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step;
  52689. });
  52690. },
  52691. identifyOnResolve(toggle) {
  52692. if (typeof toggle === "boolean")
  52693. identifyOnResolve = toggle;
  52694. return identifyOnResolve;
  52695. },
  52696. resolve: (handler, context) => {
  52697. for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) {
  52698. handler = middleware(handler, context);
  52699. }
  52700. if (identifyOnResolve) {
  52701. console.log(stack.identify());
  52702. }
  52703. return handler;
  52704. }
  52705. };
  52706. return stack;
  52707. }, "constructStack");
  52708. var stepWeights = {
  52709. initialize: 5,
  52710. serialize: 4,
  52711. build: 3,
  52712. finalizeRequest: 2,
  52713. deserialize: 1
  52714. };
  52715. var priorityWeights = {
  52716. high: 3,
  52717. normal: 2,
  52718. low: 1
  52719. };
  52720. }
  52721. });
  52722. // ../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-cjs/index.js
  52723. var require_dist_cjs23 = __commonJS({
  52724. "../node_modules/.pnpm/@smithy+smithy-client@4.4.1/node_modules/@smithy/smithy-client/dist-cjs/index.js"(exports2, module2) {
  52725. var __defProp3 = Object.defineProperty;
  52726. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  52727. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  52728. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  52729. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  52730. var __export2 = (target, all) => {
  52731. for (var name in all)
  52732. __defProp3(target, name, { get: all[name], enumerable: true });
  52733. };
  52734. var __copyProps3 = (to, from, except, desc) => {
  52735. if (from && typeof from === "object" || typeof from === "function") {
  52736. for (let key of __getOwnPropNames3(from))
  52737. if (!__hasOwnProp3.call(to, key) && key !== except)
  52738. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  52739. }
  52740. return to;
  52741. };
  52742. var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
  52743. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  52744. var src_exports = {};
  52745. __export2(src_exports, {
  52746. Client: () => Client,
  52747. Command: () => Command,
  52748. NoOpLogger: () => NoOpLogger3,
  52749. SENSITIVE_STRING: () => SENSITIVE_STRING3,
  52750. ServiceException: () => ServiceException,
  52751. _json: () => _json2,
  52752. collectBody: () => import_protocols2.collectBody,
  52753. convertMap: () => convertMap,
  52754. createAggregatedClient: () => createAggregatedClient3,
  52755. decorateServiceException: () => decorateServiceException,
  52756. emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion4,
  52757. extendedEncodeURIComponent: () => import_protocols2.extendedEncodeURIComponent,
  52758. getArrayIfSingleItem: () => getArrayIfSingleItem,
  52759. getDefaultClientConfiguration: () => getDefaultClientConfiguration,
  52760. getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration3,
  52761. getValueFromTextNode: () => getValueFromTextNode2,
  52762. isSerializableHeaderValue: () => isSerializableHeaderValue,
  52763. loadConfigsForDefaultMode: () => loadConfigsForDefaultMode3,
  52764. map: () => map2,
  52765. resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig3,
  52766. resolvedPath: () => import_protocols2.resolvedPath,
  52767. serializeDateTime: () => serializeDateTime,
  52768. serializeFloat: () => serializeFloat,
  52769. take: () => take2,
  52770. throwDefaultError: () => throwDefaultError3,
  52771. withBaseException: () => withBaseException3
  52772. });
  52773. module2.exports = __toCommonJS2(src_exports);
  52774. var import_middleware_stack = require_dist_cjs22();
  52775. var _a2;
  52776. var Client = (_a2 = class {
  52777. constructor(config) {
  52778. this.config = config;
  52779. this.middlewareStack = (0, import_middleware_stack.constructStack)();
  52780. }
  52781. send(command, optionsOrCb, cb) {
  52782. const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0;
  52783. const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
  52784. const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true;
  52785. let handler;
  52786. if (useHandlerCache) {
  52787. if (!this.handlers) {
  52788. this.handlers = /* @__PURE__ */ new WeakMap();
  52789. }
  52790. const handlers = this.handlers;
  52791. if (handlers.has(command.constructor)) {
  52792. handler = handlers.get(command.constructor);
  52793. } else {
  52794. handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
  52795. handlers.set(command.constructor, handler);
  52796. }
  52797. } else {
  52798. delete this.handlers;
  52799. handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
  52800. }
  52801. if (callback) {
  52802. handler(command).then(
  52803. (result) => callback(null, result.output),
  52804. (err2) => callback(err2)
  52805. ).catch(
  52806. // prevent any errors thrown in the callback from triggering an
  52807. // unhandled promise rejection
  52808. () => {
  52809. }
  52810. );
  52811. } else {
  52812. return handler(command).then((result) => result.output);
  52813. }
  52814. }
  52815. destroy() {
  52816. var _a7, _b, _c;
  52817. (_c = (_b = (_a7 = this.config) == null ? void 0 : _a7.requestHandler) == null ? void 0 : _b.destroy) == null ? void 0 : _c.call(_b);
  52818. delete this.handlers;
  52819. }
  52820. }, __name(_a2, "Client"), _a2);
  52821. var import_protocols2 = (init_protocols(), __toCommonJS(protocols_exports));
  52822. var import_types5 = require_dist_cjs();
  52823. var _a3;
  52824. var Command = (_a3 = class {
  52825. constructor() {
  52826. this.middlewareStack = (0, import_middleware_stack.constructStack)();
  52827. }
  52828. /**
  52829. * Factory for Command ClassBuilder.
  52830. * @internal
  52831. */
  52832. static classBuilder() {
  52833. return new ClassBuilder();
  52834. }
  52835. /**
  52836. * @internal
  52837. */
  52838. resolveMiddlewareWithContext(clientStack, configuration, options, {
  52839. middlewareFn,
  52840. clientName,
  52841. commandName,
  52842. inputFilterSensitiveLog,
  52843. outputFilterSensitiveLog,
  52844. smithyContext,
  52845. additionalContext,
  52846. CommandCtor
  52847. }) {
  52848. for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) {
  52849. this.middlewareStack.use(mw);
  52850. }
  52851. const stack = clientStack.concat(this.middlewareStack);
  52852. const { logger: logger3 } = configuration;
  52853. const handlerExecutionContext = {
  52854. logger: logger3,
  52855. clientName,
  52856. commandName,
  52857. inputFilterSensitiveLog,
  52858. outputFilterSensitiveLog,
  52859. [import_types5.SMITHY_CONTEXT_KEY]: {
  52860. commandInstance: this,
  52861. ...smithyContext
  52862. },
  52863. ...additionalContext
  52864. };
  52865. const { requestHandler } = configuration;
  52866. return stack.resolve(
  52867. (request) => requestHandler.handle(request.request, options || {}),
  52868. handlerExecutionContext
  52869. );
  52870. }
  52871. }, __name(_a3, "Command"), _a3);
  52872. var _a4;
  52873. var ClassBuilder = (_a4 = class {
  52874. constructor() {
  52875. this._init = () => {
  52876. };
  52877. this._ep = {};
  52878. this._middlewareFn = () => [];
  52879. this._commandName = "";
  52880. this._clientName = "";
  52881. this._additionalContext = {};
  52882. this._smithyContext = {};
  52883. this._inputFilterSensitiveLog = (_3) => _3;
  52884. this._outputFilterSensitiveLog = (_3) => _3;
  52885. this._serializer = null;
  52886. this._deserializer = null;
  52887. }
  52888. /**
  52889. * Optional init callback.
  52890. */
  52891. init(cb) {
  52892. this._init = cb;
  52893. }
  52894. /**
  52895. * Set the endpoint parameter instructions.
  52896. */
  52897. ep(endpointParameterInstructions) {
  52898. this._ep = endpointParameterInstructions;
  52899. return this;
  52900. }
  52901. /**
  52902. * Add any number of middleware.
  52903. */
  52904. m(middlewareSupplier) {
  52905. this._middlewareFn = middlewareSupplier;
  52906. return this;
  52907. }
  52908. /**
  52909. * Set the initial handler execution context Smithy field.
  52910. */
  52911. s(service, operation, smithyContext = {}) {
  52912. this._smithyContext = {
  52913. service,
  52914. operation,
  52915. ...smithyContext
  52916. };
  52917. return this;
  52918. }
  52919. /**
  52920. * Set the initial handler execution context.
  52921. */
  52922. c(additionalContext = {}) {
  52923. this._additionalContext = additionalContext;
  52924. return this;
  52925. }
  52926. /**
  52927. * Set constant string identifiers for the operation.
  52928. */
  52929. n(clientName, commandName) {
  52930. this._clientName = clientName;
  52931. this._commandName = commandName;
  52932. return this;
  52933. }
  52934. /**
  52935. * Set the input and output sensistive log filters.
  52936. */
  52937. f(inputFilter = (_3) => _3, outputFilter = (_3) => _3) {
  52938. this._inputFilterSensitiveLog = inputFilter;
  52939. this._outputFilterSensitiveLog = outputFilter;
  52940. return this;
  52941. }
  52942. /**
  52943. * Sets the serializer.
  52944. */
  52945. ser(serializer) {
  52946. this._serializer = serializer;
  52947. return this;
  52948. }
  52949. /**
  52950. * Sets the deserializer.
  52951. */
  52952. de(deserializer) {
  52953. this._deserializer = deserializer;
  52954. return this;
  52955. }
  52956. /**
  52957. * Sets input/output schema for the operation.
  52958. */
  52959. sc(operation) {
  52960. this._operationSchema = operation;
  52961. this._smithyContext.operationSchema = operation;
  52962. return this;
  52963. }
  52964. /**
  52965. * @returns a Command class with the classBuilder properties.
  52966. */
  52967. build() {
  52968. var _a7;
  52969. const closure = this;
  52970. let CommandRef;
  52971. return CommandRef = (_a7 = class extends Command {
  52972. /**
  52973. * @public
  52974. */
  52975. constructor(...[input]) {
  52976. super();
  52977. this.serialize = closure._serializer;
  52978. this.deserialize = closure._deserializer;
  52979. this.input = input ?? {};
  52980. closure._init(this);
  52981. this.schema = closure._operationSchema;
  52982. }
  52983. /**
  52984. * @public
  52985. */
  52986. static getEndpointParameterInstructions() {
  52987. return closure._ep;
  52988. }
  52989. /**
  52990. * @internal
  52991. */
  52992. resolveMiddleware(stack, configuration, options) {
  52993. return this.resolveMiddlewareWithContext(stack, configuration, options, {
  52994. CommandCtor: CommandRef,
  52995. middlewareFn: closure._middlewareFn,
  52996. clientName: closure._clientName,
  52997. commandName: closure._commandName,
  52998. inputFilterSensitiveLog: closure._inputFilterSensitiveLog,
  52999. outputFilterSensitiveLog: closure._outputFilterSensitiveLog,
  53000. smithyContext: closure._smithyContext,
  53001. additionalContext: closure._additionalContext
  53002. });
  53003. }
  53004. }, __name(_a7, "CommandRef"), _a7);
  53005. }
  53006. }, __name(_a4, "ClassBuilder"), _a4);
  53007. var SENSITIVE_STRING3 = "***SensitiveInformation***";
  53008. var createAggregatedClient3 = /* @__PURE__ */ __name((commands3, Client2) => {
  53009. for (const command of Object.keys(commands3)) {
  53010. const CommandCtor = commands3[command];
  53011. const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb) {
  53012. const command22 = new CommandCtor(args);
  53013. if (typeof optionsOrCb === "function") {
  53014. this.send(command22, optionsOrCb);
  53015. } else if (typeof cb === "function") {
  53016. if (typeof optionsOrCb !== "object")
  53017. throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
  53018. this.send(command22, optionsOrCb || {}, cb);
  53019. } else {
  53020. return this.send(command22, optionsOrCb);
  53021. }
  53022. }, "methodImpl");
  53023. const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, "");
  53024. Client2.prototype[methodName] = methodImpl;
  53025. }
  53026. }, "createAggregatedClient");
  53027. var _a5;
  53028. var ServiceException = (_a5 = class extends Error {
  53029. constructor(options) {
  53030. super(options.message);
  53031. Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
  53032. this.name = options.name;
  53033. this.$fault = options.$fault;
  53034. this.$metadata = options.$metadata;
  53035. }
  53036. /**
  53037. * Checks if a value is an instance of ServiceException (duck typed)
  53038. */
  53039. static isInstance(value) {
  53040. if (!value)
  53041. return false;
  53042. const candidate = value;
  53043. return _a5.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
  53044. }
  53045. /**
  53046. * Custom instanceof check to support the operator for ServiceException base class
  53047. */
  53048. static [Symbol.hasInstance](instance) {
  53049. if (!instance)
  53050. return false;
  53051. const candidate = instance;
  53052. if (this === _a5) {
  53053. return _a5.isInstance(instance);
  53054. }
  53055. if (_a5.isInstance(instance)) {
  53056. if (candidate.name && this.name) {
  53057. return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
  53058. }
  53059. return this.prototype.isPrototypeOf(instance);
  53060. }
  53061. return false;
  53062. }
  53063. }, __name(_a5, "ServiceException"), _a5);
  53064. var decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => {
  53065. Object.entries(additions).filter(([, v6]) => v6 !== void 0).forEach(([k3, v6]) => {
  53066. if (exception[k3] == void 0 || exception[k3] === "") {
  53067. exception[k3] = v6;
  53068. }
  53069. });
  53070. const message = exception.message || exception.Message || "UnknownError";
  53071. exception.message = message;
  53072. delete exception.Message;
  53073. return exception;
  53074. }, "decorateServiceException");
  53075. var throwDefaultError3 = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => {
  53076. const $metadata = deserializeMetadata3(output);
  53077. const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0;
  53078. const response = new exceptionCtor({
  53079. name: (parsedBody == null ? void 0 : parsedBody.code) || (parsedBody == null ? void 0 : parsedBody.Code) || errorCode || statusCode || "UnknownError",
  53080. $fault: "client",
  53081. $metadata
  53082. });
  53083. throw decorateServiceException(response, parsedBody);
  53084. }, "throwDefaultError");
  53085. var withBaseException3 = /* @__PURE__ */ __name((ExceptionCtor) => {
  53086. return ({ output, parsedBody, errorCode }) => {
  53087. throwDefaultError3({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
  53088. };
  53089. }, "withBaseException");
  53090. var deserializeMetadata3 = /* @__PURE__ */ __name((output) => ({
  53091. httpStatusCode: output.statusCode,
  53092. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  53093. extendedRequestId: output.headers["x-amz-id-2"],
  53094. cfId: output.headers["x-amz-cf-id"]
  53095. }), "deserializeMetadata");
  53096. var loadConfigsForDefaultMode3 = /* @__PURE__ */ __name((mode) => {
  53097. switch (mode) {
  53098. case "standard":
  53099. return {
  53100. retryMode: "standard",
  53101. connectionTimeout: 3100
  53102. };
  53103. case "in-region":
  53104. return {
  53105. retryMode: "standard",
  53106. connectionTimeout: 1100
  53107. };
  53108. case "cross-region":
  53109. return {
  53110. retryMode: "standard",
  53111. connectionTimeout: 3100
  53112. };
  53113. case "mobile":
  53114. return {
  53115. retryMode: "standard",
  53116. connectionTimeout: 3e4
  53117. };
  53118. default:
  53119. return {};
  53120. }
  53121. }, "loadConfigsForDefaultMode");
  53122. var warningEmitted = false;
  53123. var emitWarningIfUnsupportedVersion4 = /* @__PURE__ */ __name((version3) => {
  53124. if (version3 && !warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 16) {
  53125. warningEmitted = true;
  53126. }
  53127. }, "emitWarningIfUnsupportedVersion");
  53128. var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
  53129. const checksumAlgorithms = [];
  53130. for (const id in import_types5.AlgorithmId) {
  53131. const algorithmId = import_types5.AlgorithmId[id];
  53132. if (runtimeConfig[algorithmId] === void 0) {
  53133. continue;
  53134. }
  53135. checksumAlgorithms.push({
  53136. algorithmId: () => algorithmId,
  53137. checksumConstructor: () => runtimeConfig[algorithmId]
  53138. });
  53139. }
  53140. return {
  53141. addChecksumAlgorithm(algo) {
  53142. checksumAlgorithms.push(algo);
  53143. },
  53144. checksumAlgorithms() {
  53145. return checksumAlgorithms;
  53146. }
  53147. };
  53148. }, "getChecksumConfiguration");
  53149. var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => {
  53150. const runtimeConfig = {};
  53151. clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
  53152. runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
  53153. });
  53154. return runtimeConfig;
  53155. }, "resolveChecksumRuntimeConfig");
  53156. var getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => {
  53157. return {
  53158. setRetryStrategy(retryStrategy) {
  53159. runtimeConfig.retryStrategy = retryStrategy;
  53160. },
  53161. retryStrategy() {
  53162. return runtimeConfig.retryStrategy;
  53163. }
  53164. };
  53165. }, "getRetryConfiguration");
  53166. var resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => {
  53167. const runtimeConfig = {};
  53168. runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
  53169. return runtimeConfig;
  53170. }, "resolveRetryRuntimeConfig");
  53171. var getDefaultExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
  53172. return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig));
  53173. }, "getDefaultExtensionConfiguration");
  53174. var getDefaultClientConfiguration = getDefaultExtensionConfiguration3;
  53175. var resolveDefaultRuntimeConfig3 = /* @__PURE__ */ __name((config) => {
  53176. return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config));
  53177. }, "resolveDefaultRuntimeConfig");
  53178. var getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem");
  53179. var getValueFromTextNode2 = /* @__PURE__ */ __name((obj) => {
  53180. const textNodeName = "#text";
  53181. for (const key in obj) {
  53182. if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) {
  53183. obj[key] = obj[key][textNodeName];
  53184. } else if (typeof obj[key] === "object" && obj[key] !== null) {
  53185. obj[key] = getValueFromTextNode2(obj[key]);
  53186. }
  53187. }
  53188. return obj;
  53189. }, "getValueFromTextNode");
  53190. var isSerializableHeaderValue = /* @__PURE__ */ __name((value) => {
  53191. return value != null;
  53192. }, "isSerializableHeaderValue");
  53193. var _a6;
  53194. var NoOpLogger3 = (_a6 = class {
  53195. trace() {
  53196. }
  53197. debug() {
  53198. }
  53199. info() {
  53200. }
  53201. warn() {
  53202. }
  53203. error() {
  53204. }
  53205. }, __name(_a6, "NoOpLogger"), _a6);
  53206. function map2(arg0, arg1, arg2) {
  53207. let target;
  53208. let filter2;
  53209. let instructions;
  53210. if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
  53211. target = {};
  53212. instructions = arg0;
  53213. } else {
  53214. target = arg0;
  53215. if (typeof arg1 === "function") {
  53216. filter2 = arg1;
  53217. instructions = arg2;
  53218. return mapWithFilter(target, filter2, instructions);
  53219. } else {
  53220. instructions = arg1;
  53221. }
  53222. }
  53223. for (const key of Object.keys(instructions)) {
  53224. if (!Array.isArray(instructions[key])) {
  53225. target[key] = instructions[key];
  53226. continue;
  53227. }
  53228. applyInstruction(target, null, instructions, key);
  53229. }
  53230. return target;
  53231. }
  53232. __name(map2, "map");
  53233. var convertMap = /* @__PURE__ */ __name((target) => {
  53234. const output = {};
  53235. for (const [k3, v6] of Object.entries(target || {})) {
  53236. output[k3] = [, v6];
  53237. }
  53238. return output;
  53239. }, "convertMap");
  53240. var take2 = /* @__PURE__ */ __name((source, instructions) => {
  53241. const out = {};
  53242. for (const key in instructions) {
  53243. applyInstruction(out, source, instructions, key);
  53244. }
  53245. return out;
  53246. }, "take");
  53247. var mapWithFilter = /* @__PURE__ */ __name((target, filter2, instructions) => {
  53248. return map2(
  53249. target,
  53250. Object.entries(instructions).reduce(
  53251. (_instructions, [key, value]) => {
  53252. if (Array.isArray(value)) {
  53253. _instructions[key] = value;
  53254. } else {
  53255. if (typeof value === "function") {
  53256. _instructions[key] = [filter2, value()];
  53257. } else {
  53258. _instructions[key] = [filter2, value];
  53259. }
  53260. }
  53261. return _instructions;
  53262. },
  53263. {}
  53264. )
  53265. );
  53266. }, "mapWithFilter");
  53267. var applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => {
  53268. if (source !== null) {
  53269. let instruction = instructions[targetKey];
  53270. if (typeof instruction === "function") {
  53271. instruction = [, instruction];
  53272. }
  53273. const [filter22 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
  53274. if (typeof filter22 === "function" && filter22(source[sourceKey]) || typeof filter22 !== "function" && !!filter22) {
  53275. target[targetKey] = valueFn(source[sourceKey]);
  53276. }
  53277. return;
  53278. }
  53279. let [filter2, value] = instructions[targetKey];
  53280. if (typeof value === "function") {
  53281. let _value;
  53282. const defaultFilterPassed = filter2 === void 0 && (_value = value()) != null;
  53283. const customFilterPassed = typeof filter2 === "function" && !!filter2(void 0) || typeof filter2 !== "function" && !!filter2;
  53284. if (defaultFilterPassed) {
  53285. target[targetKey] = _value;
  53286. } else if (customFilterPassed) {
  53287. target[targetKey] = value();
  53288. }
  53289. } else {
  53290. const defaultFilterPassed = filter2 === void 0 && value != null;
  53291. const customFilterPassed = typeof filter2 === "function" && !!filter2(value) || typeof filter2 !== "function" && !!filter2;
  53292. if (defaultFilterPassed || customFilterPassed) {
  53293. target[targetKey] = value;
  53294. }
  53295. }
  53296. }, "applyInstruction");
  53297. var nonNullish = /* @__PURE__ */ __name((_3) => _3 != null, "nonNullish");
  53298. var pass = /* @__PURE__ */ __name((_3) => _3, "pass");
  53299. var serializeFloat = /* @__PURE__ */ __name((value) => {
  53300. if (value !== value) {
  53301. return "NaN";
  53302. }
  53303. switch (value) {
  53304. case Infinity:
  53305. return "Infinity";
  53306. case -Infinity:
  53307. return "-Infinity";
  53308. default:
  53309. return value;
  53310. }
  53311. }, "serializeFloat");
  53312. var serializeDateTime = /* @__PURE__ */ __name((date) => date.toISOString().replace(".000Z", "Z"), "serializeDateTime");
  53313. var _json2 = /* @__PURE__ */ __name((obj) => {
  53314. if (obj == null) {
  53315. return {};
  53316. }
  53317. if (Array.isArray(obj)) {
  53318. return obj.filter((_3) => _3 != null).map(_json2);
  53319. }
  53320. if (typeof obj === "object") {
  53321. const target = {};
  53322. for (const key of Object.keys(obj)) {
  53323. if (obj[key] == null) {
  53324. continue;
  53325. }
  53326. target[key] = _json2(obj[key]);
  53327. }
  53328. return target;
  53329. }
  53330. return obj;
  53331. }, "_json");
  53332. __reExport(src_exports, (init_serde(), __toCommonJS(serde_exports)), module2.exports);
  53333. }
  53334. });
  53335. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js
  53336. var import_smithy_client, awsExpectUnion;
  53337. var init_awsExpectUnion = __esm({
  53338. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js"() {
  53339. import_smithy_client = __toESM(require_dist_cjs23());
  53340. awsExpectUnion = (value) => {
  53341. if (value == null) {
  53342. return void 0;
  53343. }
  53344. if (typeof value === "object" && "__type" in value) {
  53345. delete value.__type;
  53346. }
  53347. return (0, import_smithy_client.expectUnion)(value);
  53348. };
  53349. }
  53350. });
  53351. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js
  53352. var import_smithy_client2, collectBodyString;
  53353. var init_common2 = __esm({
  53354. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js"() {
  53355. import_smithy_client2 = __toESM(require_dist_cjs23());
  53356. collectBodyString = (streamBody, context) => (0, import_smithy_client2.collectBody)(streamBody, context).then((body) => context.utf8Encoder(body));
  53357. }
  53358. });
  53359. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js
  53360. var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode;
  53361. var init_parseJsonBody = __esm({
  53362. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js"() {
  53363. init_common2();
  53364. parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
  53365. if (encoded.length) {
  53366. try {
  53367. return JSON.parse(encoded);
  53368. } catch (e4) {
  53369. if ((e4 == null ? void 0 : e4.name) === "SyntaxError") {
  53370. Object.defineProperty(e4, "$responseBodyText", {
  53371. value: encoded
  53372. });
  53373. }
  53374. throw e4;
  53375. }
  53376. }
  53377. return {};
  53378. });
  53379. parseJsonErrorBody = async (errorBody, context) => {
  53380. const value = await parseJsonBody(errorBody, context);
  53381. value.message = value.message ?? value.Message;
  53382. return value;
  53383. };
  53384. loadRestJsonErrorCode = (output, data) => {
  53385. const findKey = (object, key) => Object.keys(object).find((k3) => k3.toLowerCase() === key.toLowerCase());
  53386. const sanitizeErrorCode = (rawValue) => {
  53387. let cleanValue = rawValue;
  53388. if (typeof cleanValue === "number") {
  53389. cleanValue = cleanValue.toString();
  53390. }
  53391. if (cleanValue.indexOf(",") >= 0) {
  53392. cleanValue = cleanValue.split(",")[0];
  53393. }
  53394. if (cleanValue.indexOf(":") >= 0) {
  53395. cleanValue = cleanValue.split(":")[0];
  53396. }
  53397. if (cleanValue.indexOf("#") >= 0) {
  53398. cleanValue = cleanValue.split("#")[1];
  53399. }
  53400. return cleanValue;
  53401. };
  53402. const headerKey = findKey(output.headers, "x-amzn-errortype");
  53403. if (headerKey !== void 0) {
  53404. return sanitizeErrorCode(output.headers[headerKey]);
  53405. }
  53406. if (data && typeof data === "object") {
  53407. const codeKey = findKey(data, "code");
  53408. if (codeKey && data[codeKey] !== void 0) {
  53409. return sanitizeErrorCode(data[codeKey]);
  53410. }
  53411. if (data["__type"] !== void 0) {
  53412. return sanitizeErrorCode(data["__type"]);
  53413. }
  53414. }
  53415. };
  53416. }
  53417. });
  53418. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js
  53419. var require_util2 = __commonJS({
  53420. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/util.js"(exports2) {
  53421. "use strict";
  53422. var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
  53423. var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
  53424. var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*";
  53425. var regexName = new RegExp("^" + nameRegexp + "$");
  53426. var getAllMatches = function(string2, regex) {
  53427. const matches = [];
  53428. let match2 = regex.exec(string2);
  53429. while (match2) {
  53430. const allmatches = [];
  53431. allmatches.startIndex = regex.lastIndex - match2[0].length;
  53432. const len = match2.length;
  53433. for (let index6 = 0; index6 < len; index6++) {
  53434. allmatches.push(match2[index6]);
  53435. }
  53436. matches.push(allmatches);
  53437. match2 = regex.exec(string2);
  53438. }
  53439. return matches;
  53440. };
  53441. var isName = function(string2) {
  53442. const match2 = regexName.exec(string2);
  53443. return !(match2 === null || typeof match2 === "undefined");
  53444. };
  53445. exports2.isExist = function(v6) {
  53446. return typeof v6 !== "undefined";
  53447. };
  53448. exports2.isEmptyObject = function(obj) {
  53449. return Object.keys(obj).length === 0;
  53450. };
  53451. exports2.merge = function(target, a3, arrayMode) {
  53452. if (a3) {
  53453. const keys = Object.keys(a3);
  53454. const len = keys.length;
  53455. for (let i4 = 0; i4 < len; i4++) {
  53456. if (arrayMode === "strict") {
  53457. target[keys[i4]] = [a3[keys[i4]]];
  53458. } else {
  53459. target[keys[i4]] = a3[keys[i4]];
  53460. }
  53461. }
  53462. }
  53463. };
  53464. exports2.getValue = function(v6) {
  53465. if (exports2.isExist(v6)) {
  53466. return v6;
  53467. } else {
  53468. return "";
  53469. }
  53470. };
  53471. exports2.isName = isName;
  53472. exports2.getAllMatches = getAllMatches;
  53473. exports2.nameRegexp = nameRegexp;
  53474. }
  53475. });
  53476. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js
  53477. var require_validator = __commonJS({
  53478. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/validator.js"(exports2) {
  53479. "use strict";
  53480. var util2 = require_util2();
  53481. var defaultOptions = {
  53482. allowBooleanAttributes: false,
  53483. //A tag can have attributes without any value
  53484. unpairedTags: []
  53485. };
  53486. exports2.validate = function(xmlData, options) {
  53487. options = Object.assign({}, defaultOptions, options);
  53488. const tags = [];
  53489. let tagFound = false;
  53490. let reachedRoot = false;
  53491. if (xmlData[0] === "\uFEFF") {
  53492. xmlData = xmlData.substr(1);
  53493. }
  53494. for (let i4 = 0; i4 < xmlData.length; i4++) {
  53495. if (xmlData[i4] === "<" && xmlData[i4 + 1] === "?") {
  53496. i4 += 2;
  53497. i4 = readPI(xmlData, i4);
  53498. if (i4.err) return i4;
  53499. } else if (xmlData[i4] === "<") {
  53500. let tagStartPos = i4;
  53501. i4++;
  53502. if (xmlData[i4] === "!") {
  53503. i4 = readCommentAndCDATA(xmlData, i4);
  53504. continue;
  53505. } else {
  53506. let closingTag = false;
  53507. if (xmlData[i4] === "/") {
  53508. closingTag = true;
  53509. i4++;
  53510. }
  53511. let tagName = "";
  53512. for (; i4 < xmlData.length && xmlData[i4] !== ">" && xmlData[i4] !== " " && xmlData[i4] !== " " && xmlData[i4] !== "\n" && xmlData[i4] !== "\r"; i4++) {
  53513. tagName += xmlData[i4];
  53514. }
  53515. tagName = tagName.trim();
  53516. if (tagName[tagName.length - 1] === "/") {
  53517. tagName = tagName.substring(0, tagName.length - 1);
  53518. i4--;
  53519. }
  53520. if (!validateTagName(tagName)) {
  53521. let msg;
  53522. if (tagName.trim().length === 0) {
  53523. msg = "Invalid space after '<'.";
  53524. } else {
  53525. msg = "Tag '" + tagName + "' is an invalid name.";
  53526. }
  53527. return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i4));
  53528. }
  53529. const result = readAttributeStr(xmlData, i4);
  53530. if (result === false) {
  53531. return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i4));
  53532. }
  53533. let attrStr = result.value;
  53534. i4 = result.index;
  53535. if (attrStr[attrStr.length - 1] === "/") {
  53536. const attrStrStart = i4 - attrStr.length;
  53537. attrStr = attrStr.substring(0, attrStr.length - 1);
  53538. const isValid2 = validateAttributeString(attrStr, options);
  53539. if (isValid2 === true) {
  53540. tagFound = true;
  53541. } else {
  53542. return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid2.err.line));
  53543. }
  53544. } else if (closingTag) {
  53545. if (!result.tagClosed) {
  53546. return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i4));
  53547. } else if (attrStr.trim().length > 0) {
  53548. return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
  53549. } else if (tags.length === 0) {
  53550. return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
  53551. } else {
  53552. const otg = tags.pop();
  53553. if (tagName !== otg.tagName) {
  53554. let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
  53555. return getErrorObject(
  53556. "InvalidTag",
  53557. "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.",
  53558. getLineNumberForPosition(xmlData, tagStartPos)
  53559. );
  53560. }
  53561. if (tags.length == 0) {
  53562. reachedRoot = true;
  53563. }
  53564. }
  53565. } else {
  53566. const isValid2 = validateAttributeString(attrStr, options);
  53567. if (isValid2 !== true) {
  53568. return getErrorObject(isValid2.err.code, isValid2.err.msg, getLineNumberForPosition(xmlData, i4 - attrStr.length + isValid2.err.line));
  53569. }
  53570. if (reachedRoot === true) {
  53571. return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i4));
  53572. } else if (options.unpairedTags.indexOf(tagName) !== -1) {
  53573. } else {
  53574. tags.push({ tagName, tagStartPos });
  53575. }
  53576. tagFound = true;
  53577. }
  53578. for (i4++; i4 < xmlData.length; i4++) {
  53579. if (xmlData[i4] === "<") {
  53580. if (xmlData[i4 + 1] === "!") {
  53581. i4++;
  53582. i4 = readCommentAndCDATA(xmlData, i4);
  53583. continue;
  53584. } else if (xmlData[i4 + 1] === "?") {
  53585. i4 = readPI(xmlData, ++i4);
  53586. if (i4.err) return i4;
  53587. } else {
  53588. break;
  53589. }
  53590. } else if (xmlData[i4] === "&") {
  53591. const afterAmp = validateAmpersand(xmlData, i4);
  53592. if (afterAmp == -1)
  53593. return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i4));
  53594. i4 = afterAmp;
  53595. } else {
  53596. if (reachedRoot === true && !isWhiteSpace(xmlData[i4])) {
  53597. return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i4));
  53598. }
  53599. }
  53600. }
  53601. if (xmlData[i4] === "<") {
  53602. i4--;
  53603. }
  53604. }
  53605. } else {
  53606. if (isWhiteSpace(xmlData[i4])) {
  53607. continue;
  53608. }
  53609. return getErrorObject("InvalidChar", "char '" + xmlData[i4] + "' is not expected.", getLineNumberForPosition(xmlData, i4));
  53610. }
  53611. }
  53612. if (!tagFound) {
  53613. return getErrorObject("InvalidXml", "Start tag expected.", 1);
  53614. } else if (tags.length == 1) {
  53615. return getErrorObject("InvalidTag", "Unclosed tag '" + tags[0].tagName + "'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
  53616. } else if (tags.length > 0) {
  53617. return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags.map((t4) => t4.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 });
  53618. }
  53619. return true;
  53620. };
  53621. function isWhiteSpace(char) {
  53622. return char === " " || char === " " || char === "\n" || char === "\r";
  53623. }
  53624. function readPI(xmlData, i4) {
  53625. const start = i4;
  53626. for (; i4 < xmlData.length; i4++) {
  53627. if (xmlData[i4] == "?" || xmlData[i4] == " ") {
  53628. const tagname = xmlData.substr(start, i4 - start);
  53629. if (i4 > 5 && tagname === "xml") {
  53630. return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i4));
  53631. } else if (xmlData[i4] == "?" && xmlData[i4 + 1] == ">") {
  53632. i4++;
  53633. break;
  53634. } else {
  53635. continue;
  53636. }
  53637. }
  53638. }
  53639. return i4;
  53640. }
  53641. function readCommentAndCDATA(xmlData, i4) {
  53642. if (xmlData.length > i4 + 5 && xmlData[i4 + 1] === "-" && xmlData[i4 + 2] === "-") {
  53643. for (i4 += 3; i4 < xmlData.length; i4++) {
  53644. if (xmlData[i4] === "-" && xmlData[i4 + 1] === "-" && xmlData[i4 + 2] === ">") {
  53645. i4 += 2;
  53646. break;
  53647. }
  53648. }
  53649. } else if (xmlData.length > i4 + 8 && xmlData[i4 + 1] === "D" && xmlData[i4 + 2] === "O" && xmlData[i4 + 3] === "C" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "Y" && xmlData[i4 + 6] === "P" && xmlData[i4 + 7] === "E") {
  53650. let angleBracketsCount = 1;
  53651. for (i4 += 8; i4 < xmlData.length; i4++) {
  53652. if (xmlData[i4] === "<") {
  53653. angleBracketsCount++;
  53654. } else if (xmlData[i4] === ">") {
  53655. angleBracketsCount--;
  53656. if (angleBracketsCount === 0) {
  53657. break;
  53658. }
  53659. }
  53660. }
  53661. } else if (xmlData.length > i4 + 9 && xmlData[i4 + 1] === "[" && xmlData[i4 + 2] === "C" && xmlData[i4 + 3] === "D" && xmlData[i4 + 4] === "A" && xmlData[i4 + 5] === "T" && xmlData[i4 + 6] === "A" && xmlData[i4 + 7] === "[") {
  53662. for (i4 += 8; i4 < xmlData.length; i4++) {
  53663. if (xmlData[i4] === "]" && xmlData[i4 + 1] === "]" && xmlData[i4 + 2] === ">") {
  53664. i4 += 2;
  53665. break;
  53666. }
  53667. }
  53668. }
  53669. return i4;
  53670. }
  53671. var doubleQuote = '"';
  53672. var singleQuote = "'";
  53673. function readAttributeStr(xmlData, i4) {
  53674. let attrStr = "";
  53675. let startChar = "";
  53676. let tagClosed = false;
  53677. for (; i4 < xmlData.length; i4++) {
  53678. if (xmlData[i4] === doubleQuote || xmlData[i4] === singleQuote) {
  53679. if (startChar === "") {
  53680. startChar = xmlData[i4];
  53681. } else if (startChar !== xmlData[i4]) {
  53682. } else {
  53683. startChar = "";
  53684. }
  53685. } else if (xmlData[i4] === ">") {
  53686. if (startChar === "") {
  53687. tagClosed = true;
  53688. break;
  53689. }
  53690. }
  53691. attrStr += xmlData[i4];
  53692. }
  53693. if (startChar !== "") {
  53694. return false;
  53695. }
  53696. return {
  53697. value: attrStr,
  53698. index: i4,
  53699. tagClosed
  53700. };
  53701. }
  53702. var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g");
  53703. function validateAttributeString(attrStr, options) {
  53704. const matches = util2.getAllMatches(attrStr, validAttrStrRegxp);
  53705. const attrNames = {};
  53706. for (let i4 = 0; i4 < matches.length; i4++) {
  53707. if (matches[i4][1].length === 0) {
  53708. return getErrorObject("InvalidAttr", "Attribute '" + matches[i4][2] + "' has no space in starting.", getPositionFromMatch(matches[i4]));
  53709. } else if (matches[i4][3] !== void 0 && matches[i4][4] === void 0) {
  53710. return getErrorObject("InvalidAttr", "Attribute '" + matches[i4][2] + "' is without value.", getPositionFromMatch(matches[i4]));
  53711. } else if (matches[i4][3] === void 0 && !options.allowBooleanAttributes) {
  53712. return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i4][2] + "' is not allowed.", getPositionFromMatch(matches[i4]));
  53713. }
  53714. const attrName = matches[i4][2];
  53715. if (!validateAttrName(attrName)) {
  53716. return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i4]));
  53717. }
  53718. if (!attrNames.hasOwnProperty(attrName)) {
  53719. attrNames[attrName] = 1;
  53720. } else {
  53721. return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i4]));
  53722. }
  53723. }
  53724. return true;
  53725. }
  53726. function validateNumberAmpersand(xmlData, i4) {
  53727. let re = /\d/;
  53728. if (xmlData[i4] === "x") {
  53729. i4++;
  53730. re = /[\da-fA-F]/;
  53731. }
  53732. for (; i4 < xmlData.length; i4++) {
  53733. if (xmlData[i4] === ";")
  53734. return i4;
  53735. if (!xmlData[i4].match(re))
  53736. break;
  53737. }
  53738. return -1;
  53739. }
  53740. function validateAmpersand(xmlData, i4) {
  53741. i4++;
  53742. if (xmlData[i4] === ";")
  53743. return -1;
  53744. if (xmlData[i4] === "#") {
  53745. i4++;
  53746. return validateNumberAmpersand(xmlData, i4);
  53747. }
  53748. let count = 0;
  53749. for (; i4 < xmlData.length; i4++, count++) {
  53750. if (xmlData[i4].match(/\w/) && count < 20)
  53751. continue;
  53752. if (xmlData[i4] === ";")
  53753. break;
  53754. return -1;
  53755. }
  53756. return i4;
  53757. }
  53758. function getErrorObject(code, message, lineNumber) {
  53759. return {
  53760. err: {
  53761. code,
  53762. msg: message,
  53763. line: lineNumber.line || lineNumber,
  53764. col: lineNumber.col
  53765. }
  53766. };
  53767. }
  53768. function validateAttrName(attrName) {
  53769. return util2.isName(attrName);
  53770. }
  53771. function validateTagName(tagname) {
  53772. return util2.isName(tagname);
  53773. }
  53774. function getLineNumberForPosition(xmlData, index6) {
  53775. const lines = xmlData.substring(0, index6).split(/\r?\n/);
  53776. return {
  53777. line: lines.length,
  53778. // column number is last line's length + 1, because column numbering starts at 1:
  53779. col: lines[lines.length - 1].length + 1
  53780. };
  53781. }
  53782. function getPositionFromMatch(match2) {
  53783. return match2.startIndex + match2[1].length;
  53784. }
  53785. }
  53786. });
  53787. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js
  53788. var require_OptionsBuilder = __commonJS({
  53789. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports2) {
  53790. var defaultOptions = {
  53791. preserveOrder: false,
  53792. attributeNamePrefix: "@_",
  53793. attributesGroupName: false,
  53794. textNodeName: "#text",
  53795. ignoreAttributes: true,
  53796. removeNSPrefix: false,
  53797. // remove NS from tag name or attribute name if true
  53798. allowBooleanAttributes: false,
  53799. //a tag can have attributes without any value
  53800. //ignoreRootElement : false,
  53801. parseTagValue: true,
  53802. parseAttributeValue: false,
  53803. trimValues: true,
  53804. //Trim string values of tag and attributes
  53805. cdataPropName: false,
  53806. numberParseOptions: {
  53807. hex: true,
  53808. leadingZeros: true,
  53809. eNotation: true
  53810. },
  53811. tagValueProcessor: function(tagName, val2) {
  53812. return val2;
  53813. },
  53814. attributeValueProcessor: function(attrName, val2) {
  53815. return val2;
  53816. },
  53817. stopNodes: [],
  53818. //nested tags will not be parsed even for errors
  53819. alwaysCreateTextNode: false,
  53820. isArray: () => false,
  53821. commentPropName: false,
  53822. unpairedTags: [],
  53823. processEntities: true,
  53824. htmlEntities: false,
  53825. ignoreDeclaration: false,
  53826. ignorePiTags: false,
  53827. transformTagName: false,
  53828. transformAttributeName: false,
  53829. updateTag: function(tagName, jPath, attrs) {
  53830. return tagName;
  53831. }
  53832. // skipEmptyListItem: false
  53833. };
  53834. var buildOptions = function(options) {
  53835. return Object.assign({}, defaultOptions, options);
  53836. };
  53837. exports2.buildOptions = buildOptions;
  53838. exports2.defaultOptions = defaultOptions;
  53839. }
  53840. });
  53841. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js
  53842. var require_xmlNode = __commonJS({
  53843. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports2, module2) {
  53844. "use strict";
  53845. var XmlNode = class {
  53846. constructor(tagname) {
  53847. this.tagname = tagname;
  53848. this.child = [];
  53849. this[":@"] = {};
  53850. }
  53851. add(key, val2) {
  53852. if (key === "__proto__") key = "#__proto__";
  53853. this.child.push({ [key]: val2 });
  53854. }
  53855. addChild(node) {
  53856. if (node.tagname === "__proto__") node.tagname = "#__proto__";
  53857. if (node[":@"] && Object.keys(node[":@"]).length > 0) {
  53858. this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] });
  53859. } else {
  53860. this.child.push({ [node.tagname]: node.child });
  53861. }
  53862. }
  53863. };
  53864. module2.exports = XmlNode;
  53865. }
  53866. });
  53867. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js
  53868. var require_DocTypeReader = __commonJS({
  53869. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports2, module2) {
  53870. var util2 = require_util2();
  53871. function readDocType(xmlData, i4) {
  53872. const entities = {};
  53873. if (xmlData[i4 + 3] === "O" && xmlData[i4 + 4] === "C" && xmlData[i4 + 5] === "T" && xmlData[i4 + 6] === "Y" && xmlData[i4 + 7] === "P" && xmlData[i4 + 8] === "E") {
  53874. i4 = i4 + 9;
  53875. let angleBracketsCount = 1;
  53876. let hasBody = false, comment = false;
  53877. let exp = "";
  53878. for (; i4 < xmlData.length; i4++) {
  53879. if (xmlData[i4] === "<" && !comment) {
  53880. if (hasBody && isEntity(xmlData, i4)) {
  53881. i4 += 7;
  53882. [entityName, val, i4] = readEntityExp(xmlData, i4 + 1);
  53883. if (val.indexOf("&") === -1)
  53884. entities[validateEntityName(entityName)] = {
  53885. regx: RegExp(`&${entityName};`, "g"),
  53886. val
  53887. };
  53888. } else if (hasBody && isElement(xmlData, i4)) i4 += 8;
  53889. else if (hasBody && isAttlist(xmlData, i4)) i4 += 8;
  53890. else if (hasBody && isNotation(xmlData, i4)) i4 += 9;
  53891. else if (isComment) comment = true;
  53892. else throw new Error("Invalid DOCTYPE");
  53893. angleBracketsCount++;
  53894. exp = "";
  53895. } else if (xmlData[i4] === ">") {
  53896. if (comment) {
  53897. if (xmlData[i4 - 1] === "-" && xmlData[i4 - 2] === "-") {
  53898. comment = false;
  53899. angleBracketsCount--;
  53900. }
  53901. } else {
  53902. angleBracketsCount--;
  53903. }
  53904. if (angleBracketsCount === 0) {
  53905. break;
  53906. }
  53907. } else if (xmlData[i4] === "[") {
  53908. hasBody = true;
  53909. } else {
  53910. exp += xmlData[i4];
  53911. }
  53912. }
  53913. if (angleBracketsCount !== 0) {
  53914. throw new Error(`Unclosed DOCTYPE`);
  53915. }
  53916. } else {
  53917. throw new Error(`Invalid Tag instead of DOCTYPE`);
  53918. }
  53919. return { entities, i: i4 };
  53920. }
  53921. function readEntityExp(xmlData, i4) {
  53922. let entityName2 = "";
  53923. for (; i4 < xmlData.length && (xmlData[i4] !== "'" && xmlData[i4] !== '"'); i4++) {
  53924. entityName2 += xmlData[i4];
  53925. }
  53926. entityName2 = entityName2.trim();
  53927. if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported");
  53928. const startChar = xmlData[i4++];
  53929. let val2 = "";
  53930. for (; i4 < xmlData.length && xmlData[i4] !== startChar; i4++) {
  53931. val2 += xmlData[i4];
  53932. }
  53933. return [entityName2, val2, i4];
  53934. }
  53935. function isComment(xmlData, i4) {
  53936. if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "-" && xmlData[i4 + 3] === "-") return true;
  53937. return false;
  53938. }
  53939. function isEntity(xmlData, i4) {
  53940. if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "E" && xmlData[i4 + 3] === "N" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "I" && xmlData[i4 + 6] === "T" && xmlData[i4 + 7] === "Y") return true;
  53941. return false;
  53942. }
  53943. function isElement(xmlData, i4) {
  53944. if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "E" && xmlData[i4 + 3] === "L" && xmlData[i4 + 4] === "E" && xmlData[i4 + 5] === "M" && xmlData[i4 + 6] === "E" && xmlData[i4 + 7] === "N" && xmlData[i4 + 8] === "T") return true;
  53945. return false;
  53946. }
  53947. function isAttlist(xmlData, i4) {
  53948. if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "A" && xmlData[i4 + 3] === "T" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "L" && xmlData[i4 + 6] === "I" && xmlData[i4 + 7] === "S" && xmlData[i4 + 8] === "T") return true;
  53949. return false;
  53950. }
  53951. function isNotation(xmlData, i4) {
  53952. if (xmlData[i4 + 1] === "!" && xmlData[i4 + 2] === "N" && xmlData[i4 + 3] === "O" && xmlData[i4 + 4] === "T" && xmlData[i4 + 5] === "A" && xmlData[i4 + 6] === "T" && xmlData[i4 + 7] === "I" && xmlData[i4 + 8] === "O" && xmlData[i4 + 9] === "N") return true;
  53953. return false;
  53954. }
  53955. function validateEntityName(name) {
  53956. if (util2.isName(name))
  53957. return name;
  53958. else
  53959. throw new Error(`Invalid entity name ${name}`);
  53960. }
  53961. module2.exports = readDocType;
  53962. }
  53963. });
  53964. // ../node_modules/.pnpm/strnum@1.1.2/node_modules/strnum/strnum.js
  53965. var require_strnum = __commonJS({
  53966. "../node_modules/.pnpm/strnum@1.1.2/node_modules/strnum/strnum.js"(exports2, module2) {
  53967. var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
  53968. var numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/;
  53969. var consider = {
  53970. hex: true,
  53971. // oct: false,
  53972. leadingZeros: true,
  53973. decimalPoint: ".",
  53974. eNotation: true
  53975. //skipLike: /regex/
  53976. };
  53977. function toNumber(str, options = {}) {
  53978. options = Object.assign({}, consider, options);
  53979. if (!str || typeof str !== "string") return str;
  53980. let trimmedStr = str.trim();
  53981. if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str;
  53982. else if (str === "0") return 0;
  53983. else if (options.hex && hexRegex.test(trimmedStr)) {
  53984. return parse_int(trimmedStr, 16);
  53985. } else if (trimmedStr.search(/[eE]/) !== -1) {
  53986. const notation = trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);
  53987. if (notation) {
  53988. if (options.leadingZeros) {
  53989. trimmedStr = (notation[1] || "") + notation[3];
  53990. } else {
  53991. if (notation[2] === "0" && notation[3][0] === ".") {
  53992. } else {
  53993. return str;
  53994. }
  53995. }
  53996. return options.eNotation ? Number(trimmedStr) : str;
  53997. } else {
  53998. return str;
  53999. }
  54000. } else {
  54001. const match2 = numRegex.exec(trimmedStr);
  54002. if (match2) {
  54003. const sign = match2[1];
  54004. const leadingZeros = match2[2];
  54005. let numTrimmedByZeros = trimZeros(match2[3]);
  54006. if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str;
  54007. else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str;
  54008. else if (options.leadingZeros && leadingZeros === str) return 0;
  54009. else {
  54010. const num = Number(trimmedStr);
  54011. const numStr = "" + num;
  54012. if (numStr.search(/[eE]/) !== -1) {
  54013. if (options.eNotation) return num;
  54014. else return str;
  54015. } else if (trimmedStr.indexOf(".") !== -1) {
  54016. if (numStr === "0" && numTrimmedByZeros === "") return num;
  54017. else if (numStr === numTrimmedByZeros) return num;
  54018. else if (sign && numStr === "-" + numTrimmedByZeros) return num;
  54019. else return str;
  54020. }
  54021. if (leadingZeros) {
  54022. return numTrimmedByZeros === numStr || sign + numTrimmedByZeros === numStr ? num : str;
  54023. } else {
  54024. return trimmedStr === numStr || trimmedStr === sign + numStr ? num : str;
  54025. }
  54026. }
  54027. } else {
  54028. return str;
  54029. }
  54030. }
  54031. }
  54032. function trimZeros(numStr) {
  54033. if (numStr && numStr.indexOf(".") !== -1) {
  54034. numStr = numStr.replace(/0+$/, "");
  54035. if (numStr === ".") numStr = "0";
  54036. else if (numStr[0] === ".") numStr = "0" + numStr;
  54037. else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1);
  54038. return numStr;
  54039. }
  54040. return numStr;
  54041. }
  54042. function parse_int(numStr, base) {
  54043. if (parseInt) return parseInt(numStr, base);
  54044. else if (Number.parseInt) return Number.parseInt(numStr, base);
  54045. else if (window && window.parseInt) return window.parseInt(numStr, base);
  54046. else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported");
  54047. }
  54048. module2.exports = toNumber;
  54049. }
  54050. });
  54051. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js
  54052. var require_OrderedObjParser = __commonJS({
  54053. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports2, module2) {
  54054. "use strict";
  54055. var util2 = require_util2();
  54056. var xmlNode = require_xmlNode();
  54057. var readDocType = require_DocTypeReader();
  54058. var toNumber = require_strnum();
  54059. var OrderedObjParser = class {
  54060. constructor(options) {
  54061. this.options = options;
  54062. this.currentNode = null;
  54063. this.tagsNodeStack = [];
  54064. this.docTypeEntities = {};
  54065. this.lastEntities = {
  54066. "apos": { regex: /&(apos|#39|#x27);/g, val: "'" },
  54067. "gt": { regex: /&(gt|#62|#x3E);/g, val: ">" },
  54068. "lt": { regex: /&(lt|#60|#x3C);/g, val: "<" },
  54069. "quot": { regex: /&(quot|#34|#x22);/g, val: '"' }
  54070. };
  54071. this.ampEntity = { regex: /&(amp|#38|#x26);/g, val: "&" };
  54072. this.htmlEntities = {
  54073. "space": { regex: /&(nbsp|#160);/g, val: " " },
  54074. // "lt" : { regex: /&(lt|#60);/g, val: "<" },
  54075. // "gt" : { regex: /&(gt|#62);/g, val: ">" },
  54076. // "amp" : { regex: /&(amp|#38);/g, val: "&" },
  54077. // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
  54078. // "apos" : { regex: /&(apos|#39);/g, val: "'" },
  54079. "cent": { regex: /&(cent|#162);/g, val: "\xA2" },
  54080. "pound": { regex: /&(pound|#163);/g, val: "\xA3" },
  54081. "yen": { regex: /&(yen|#165);/g, val: "\xA5" },
  54082. "euro": { regex: /&(euro|#8364);/g, val: "\u20AC" },
  54083. "copyright": { regex: /&(copy|#169);/g, val: "\xA9" },
  54084. "reg": { regex: /&(reg|#174);/g, val: "\xAE" },
  54085. "inr": { regex: /&(inr|#8377);/g, val: "\u20B9" },
  54086. "num_dec": { regex: /&#([0-9]{1,7});/g, val: (_3, str) => String.fromCharCode(Number.parseInt(str, 10)) },
  54087. "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val: (_3, str) => String.fromCharCode(Number.parseInt(str, 16)) }
  54088. };
  54089. this.addExternalEntities = addExternalEntities;
  54090. this.parseXml = parseXml;
  54091. this.parseTextData = parseTextData;
  54092. this.resolveNameSpace = resolveNameSpace;
  54093. this.buildAttributesMap = buildAttributesMap;
  54094. this.isItStopNode = isItStopNode;
  54095. this.replaceEntitiesValue = replaceEntitiesValue;
  54096. this.readStopNodeData = readStopNodeData;
  54097. this.saveTextToParentTag = saveTextToParentTag;
  54098. this.addChild = addChild;
  54099. }
  54100. };
  54101. function addExternalEntities(externalEntities) {
  54102. const entKeys = Object.keys(externalEntities);
  54103. for (let i4 = 0; i4 < entKeys.length; i4++) {
  54104. const ent = entKeys[i4];
  54105. this.lastEntities[ent] = {
  54106. regex: new RegExp("&" + ent + ";", "g"),
  54107. val: externalEntities[ent]
  54108. };
  54109. }
  54110. }
  54111. function parseTextData(val2, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
  54112. if (val2 !== void 0) {
  54113. if (this.options.trimValues && !dontTrim) {
  54114. val2 = val2.trim();
  54115. }
  54116. if (val2.length > 0) {
  54117. if (!escapeEntities) val2 = this.replaceEntitiesValue(val2);
  54118. const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode);
  54119. if (newval === null || newval === void 0) {
  54120. return val2;
  54121. } else if (typeof newval !== typeof val2 || newval !== val2) {
  54122. return newval;
  54123. } else if (this.options.trimValues) {
  54124. return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
  54125. } else {
  54126. const trimmedVal = val2.trim();
  54127. if (trimmedVal === val2) {
  54128. return parseValue(val2, this.options.parseTagValue, this.options.numberParseOptions);
  54129. } else {
  54130. return val2;
  54131. }
  54132. }
  54133. }
  54134. }
  54135. }
  54136. function resolveNameSpace(tagname) {
  54137. if (this.options.removeNSPrefix) {
  54138. const tags = tagname.split(":");
  54139. const prefix2 = tagname.charAt(0) === "/" ? "/" : "";
  54140. if (tags[0] === "xmlns") {
  54141. return "";
  54142. }
  54143. if (tags.length === 2) {
  54144. tagname = prefix2 + tags[1];
  54145. }
  54146. }
  54147. return tagname;
  54148. }
  54149. var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
  54150. function buildAttributesMap(attrStr, jPath, tagName) {
  54151. if (!this.options.ignoreAttributes && typeof attrStr === "string") {
  54152. const matches = util2.getAllMatches(attrStr, attrsRegx);
  54153. const len = matches.length;
  54154. const attrs = {};
  54155. for (let i4 = 0; i4 < len; i4++) {
  54156. const attrName = this.resolveNameSpace(matches[i4][1]);
  54157. let oldVal = matches[i4][4];
  54158. let aName = this.options.attributeNamePrefix + attrName;
  54159. if (attrName.length) {
  54160. if (this.options.transformAttributeName) {
  54161. aName = this.options.transformAttributeName(aName);
  54162. }
  54163. if (aName === "__proto__") aName = "#__proto__";
  54164. if (oldVal !== void 0) {
  54165. if (this.options.trimValues) {
  54166. oldVal = oldVal.trim();
  54167. }
  54168. oldVal = this.replaceEntitiesValue(oldVal);
  54169. const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
  54170. if (newVal === null || newVal === void 0) {
  54171. attrs[aName] = oldVal;
  54172. } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {
  54173. attrs[aName] = newVal;
  54174. } else {
  54175. attrs[aName] = parseValue(
  54176. oldVal,
  54177. this.options.parseAttributeValue,
  54178. this.options.numberParseOptions
  54179. );
  54180. }
  54181. } else if (this.options.allowBooleanAttributes) {
  54182. attrs[aName] = true;
  54183. }
  54184. }
  54185. }
  54186. if (!Object.keys(attrs).length) {
  54187. return;
  54188. }
  54189. if (this.options.attributesGroupName) {
  54190. const attrCollection = {};
  54191. attrCollection[this.options.attributesGroupName] = attrs;
  54192. return attrCollection;
  54193. }
  54194. return attrs;
  54195. }
  54196. }
  54197. var parseXml = function(xmlData) {
  54198. xmlData = xmlData.replace(/\r\n?/g, "\n");
  54199. const xmlObj = new xmlNode("!xml");
  54200. let currentNode = xmlObj;
  54201. let textData = "";
  54202. let jPath = "";
  54203. for (let i4 = 0; i4 < xmlData.length; i4++) {
  54204. const ch = xmlData[i4];
  54205. if (ch === "<") {
  54206. if (xmlData[i4 + 1] === "/") {
  54207. const closeIndex = findClosingIndex(xmlData, ">", i4, "Closing Tag is not closed.");
  54208. let tagName = xmlData.substring(i4 + 2, closeIndex).trim();
  54209. if (this.options.removeNSPrefix) {
  54210. const colonIndex = tagName.indexOf(":");
  54211. if (colonIndex !== -1) {
  54212. tagName = tagName.substr(colonIndex + 1);
  54213. }
  54214. }
  54215. if (this.options.transformTagName) {
  54216. tagName = this.options.transformTagName(tagName);
  54217. }
  54218. if (currentNode) {
  54219. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  54220. }
  54221. const lastTagName = jPath.substring(jPath.lastIndexOf(".") + 1);
  54222. if (tagName && this.options.unpairedTags.indexOf(tagName) !== -1) {
  54223. throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
  54224. }
  54225. let propIndex = 0;
  54226. if (lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1) {
  54227. propIndex = jPath.lastIndexOf(".", jPath.lastIndexOf(".") - 1);
  54228. this.tagsNodeStack.pop();
  54229. } else {
  54230. propIndex = jPath.lastIndexOf(".");
  54231. }
  54232. jPath = jPath.substring(0, propIndex);
  54233. currentNode = this.tagsNodeStack.pop();
  54234. textData = "";
  54235. i4 = closeIndex;
  54236. } else if (xmlData[i4 + 1] === "?") {
  54237. let tagData = readTagExp(xmlData, i4, false, "?>");
  54238. if (!tagData) throw new Error("Pi Tag is not closed.");
  54239. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  54240. if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) {
  54241. } else {
  54242. const childNode = new xmlNode(tagData.tagName);
  54243. childNode.add(this.options.textNodeName, "");
  54244. if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent) {
  54245. childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
  54246. }
  54247. this.addChild(currentNode, childNode, jPath);
  54248. }
  54249. i4 = tagData.closeIndex + 1;
  54250. } else if (xmlData.substr(i4 + 1, 3) === "!--") {
  54251. const endIndex = findClosingIndex(xmlData, "-->", i4 + 4, "Comment is not closed.");
  54252. if (this.options.commentPropName) {
  54253. const comment = xmlData.substring(i4 + 4, endIndex - 2);
  54254. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  54255. currentNode.add(this.options.commentPropName, [{ [this.options.textNodeName]: comment }]);
  54256. }
  54257. i4 = endIndex;
  54258. } else if (xmlData.substr(i4 + 1, 2) === "!D") {
  54259. const result = readDocType(xmlData, i4);
  54260. this.docTypeEntities = result.entities;
  54261. i4 = result.i;
  54262. } else if (xmlData.substr(i4 + 1, 2) === "![") {
  54263. const closeIndex = findClosingIndex(xmlData, "]]>", i4, "CDATA is not closed.") - 2;
  54264. const tagExp = xmlData.substring(i4 + 9, closeIndex);
  54265. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  54266. let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
  54267. if (val2 == void 0) val2 = "";
  54268. if (this.options.cdataPropName) {
  54269. currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]);
  54270. } else {
  54271. currentNode.add(this.options.textNodeName, val2);
  54272. }
  54273. i4 = closeIndex + 2;
  54274. } else {
  54275. let result = readTagExp(xmlData, i4, this.options.removeNSPrefix);
  54276. let tagName = result.tagName;
  54277. const rawTagName = result.rawTagName;
  54278. let tagExp = result.tagExp;
  54279. let attrExpPresent = result.attrExpPresent;
  54280. let closeIndex = result.closeIndex;
  54281. if (this.options.transformTagName) {
  54282. tagName = this.options.transformTagName(tagName);
  54283. }
  54284. if (currentNode && textData) {
  54285. if (currentNode.tagname !== "!xml") {
  54286. textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
  54287. }
  54288. }
  54289. const lastTag = currentNode;
  54290. if (lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1) {
  54291. currentNode = this.tagsNodeStack.pop();
  54292. jPath = jPath.substring(0, jPath.lastIndexOf("."));
  54293. }
  54294. if (tagName !== xmlObj.tagname) {
  54295. jPath += jPath ? "." + tagName : tagName;
  54296. }
  54297. if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
  54298. let tagContent = "";
  54299. if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
  54300. if (tagName[tagName.length - 1] === "/") {
  54301. tagName = tagName.substr(0, tagName.length - 1);
  54302. jPath = jPath.substr(0, jPath.length - 1);
  54303. tagExp = tagName;
  54304. } else {
  54305. tagExp = tagExp.substr(0, tagExp.length - 1);
  54306. }
  54307. i4 = result.closeIndex;
  54308. } else if (this.options.unpairedTags.indexOf(tagName) !== -1) {
  54309. i4 = result.closeIndex;
  54310. } else {
  54311. const result2 = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
  54312. if (!result2) throw new Error(`Unexpected end of ${rawTagName}`);
  54313. i4 = result2.i;
  54314. tagContent = result2.tagContent;
  54315. }
  54316. const childNode = new xmlNode(tagName);
  54317. if (tagName !== tagExp && attrExpPresent) {
  54318. childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
  54319. }
  54320. if (tagContent) {
  54321. tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
  54322. }
  54323. jPath = jPath.substr(0, jPath.lastIndexOf("."));
  54324. childNode.add(this.options.textNodeName, tagContent);
  54325. this.addChild(currentNode, childNode, jPath);
  54326. } else {
  54327. if (tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1) {
  54328. if (tagName[tagName.length - 1] === "/") {
  54329. tagName = tagName.substr(0, tagName.length - 1);
  54330. jPath = jPath.substr(0, jPath.length - 1);
  54331. tagExp = tagName;
  54332. } else {
  54333. tagExp = tagExp.substr(0, tagExp.length - 1);
  54334. }
  54335. if (this.options.transformTagName) {
  54336. tagName = this.options.transformTagName(tagName);
  54337. }
  54338. const childNode = new xmlNode(tagName);
  54339. if (tagName !== tagExp && attrExpPresent) {
  54340. childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
  54341. }
  54342. this.addChild(currentNode, childNode, jPath);
  54343. jPath = jPath.substr(0, jPath.lastIndexOf("."));
  54344. } else {
  54345. const childNode = new xmlNode(tagName);
  54346. this.tagsNodeStack.push(currentNode);
  54347. if (tagName !== tagExp && attrExpPresent) {
  54348. childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
  54349. }
  54350. this.addChild(currentNode, childNode, jPath);
  54351. currentNode = childNode;
  54352. }
  54353. textData = "";
  54354. i4 = closeIndex;
  54355. }
  54356. }
  54357. } else {
  54358. textData += xmlData[i4];
  54359. }
  54360. }
  54361. return xmlObj.child;
  54362. };
  54363. function addChild(currentNode, childNode, jPath) {
  54364. const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"]);
  54365. if (result === false) {
  54366. } else if (typeof result === "string") {
  54367. childNode.tagname = result;
  54368. currentNode.addChild(childNode);
  54369. } else {
  54370. currentNode.addChild(childNode);
  54371. }
  54372. }
  54373. var replaceEntitiesValue = function(val2) {
  54374. if (this.options.processEntities) {
  54375. for (let entityName2 in this.docTypeEntities) {
  54376. const entity = this.docTypeEntities[entityName2];
  54377. val2 = val2.replace(entity.regx, entity.val);
  54378. }
  54379. for (let entityName2 in this.lastEntities) {
  54380. const entity = this.lastEntities[entityName2];
  54381. val2 = val2.replace(entity.regex, entity.val);
  54382. }
  54383. if (this.options.htmlEntities) {
  54384. for (let entityName2 in this.htmlEntities) {
  54385. const entity = this.htmlEntities[entityName2];
  54386. val2 = val2.replace(entity.regex, entity.val);
  54387. }
  54388. }
  54389. val2 = val2.replace(this.ampEntity.regex, this.ampEntity.val);
  54390. }
  54391. return val2;
  54392. };
  54393. function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
  54394. if (textData) {
  54395. if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0;
  54396. textData = this.parseTextData(
  54397. textData,
  54398. currentNode.tagname,
  54399. jPath,
  54400. false,
  54401. currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
  54402. isLeafNode
  54403. );
  54404. if (textData !== void 0 && textData !== "")
  54405. currentNode.add(this.options.textNodeName, textData);
  54406. textData = "";
  54407. }
  54408. return textData;
  54409. }
  54410. function isItStopNode(stopNodes, jPath, currentTagName) {
  54411. const allNodesExp = "*." + currentTagName;
  54412. for (const stopNodePath in stopNodes) {
  54413. const stopNodeExp = stopNodes[stopNodePath];
  54414. if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true;
  54415. }
  54416. return false;
  54417. }
  54418. function tagExpWithClosingIndex(xmlData, i4, closingChar = ">") {
  54419. let attrBoundary;
  54420. let tagExp = "";
  54421. for (let index6 = i4; index6 < xmlData.length; index6++) {
  54422. let ch = xmlData[index6];
  54423. if (attrBoundary) {
  54424. if (ch === attrBoundary) attrBoundary = "";
  54425. } else if (ch === '"' || ch === "'") {
  54426. attrBoundary = ch;
  54427. } else if (ch === closingChar[0]) {
  54428. if (closingChar[1]) {
  54429. if (xmlData[index6 + 1] === closingChar[1]) {
  54430. return {
  54431. data: tagExp,
  54432. index: index6
  54433. };
  54434. }
  54435. } else {
  54436. return {
  54437. data: tagExp,
  54438. index: index6
  54439. };
  54440. }
  54441. } else if (ch === " ") {
  54442. ch = " ";
  54443. }
  54444. tagExp += ch;
  54445. }
  54446. }
  54447. function findClosingIndex(xmlData, str, i4, errMsg) {
  54448. const closingIndex = xmlData.indexOf(str, i4);
  54449. if (closingIndex === -1) {
  54450. throw new Error(errMsg);
  54451. } else {
  54452. return closingIndex + str.length - 1;
  54453. }
  54454. }
  54455. function readTagExp(xmlData, i4, removeNSPrefix, closingChar = ">") {
  54456. const result = tagExpWithClosingIndex(xmlData, i4 + 1, closingChar);
  54457. if (!result) return;
  54458. let tagExp = result.data;
  54459. const closeIndex = result.index;
  54460. const separatorIndex = tagExp.search(/\s/);
  54461. let tagName = tagExp;
  54462. let attrExpPresent = true;
  54463. if (separatorIndex !== -1) {
  54464. tagName = tagExp.substring(0, separatorIndex);
  54465. tagExp = tagExp.substring(separatorIndex + 1).trimStart();
  54466. }
  54467. const rawTagName = tagName;
  54468. if (removeNSPrefix) {
  54469. const colonIndex = tagName.indexOf(":");
  54470. if (colonIndex !== -1) {
  54471. tagName = tagName.substr(colonIndex + 1);
  54472. attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
  54473. }
  54474. }
  54475. return {
  54476. tagName,
  54477. tagExp,
  54478. closeIndex,
  54479. attrExpPresent,
  54480. rawTagName
  54481. };
  54482. }
  54483. function readStopNodeData(xmlData, tagName, i4) {
  54484. const startIndex = i4;
  54485. let openTagCount = 1;
  54486. for (; i4 < xmlData.length; i4++) {
  54487. if (xmlData[i4] === "<") {
  54488. if (xmlData[i4 + 1] === "/") {
  54489. const closeIndex = findClosingIndex(xmlData, ">", i4, `${tagName} is not closed`);
  54490. let closeTagName = xmlData.substring(i4 + 2, closeIndex).trim();
  54491. if (closeTagName === tagName) {
  54492. openTagCount--;
  54493. if (openTagCount === 0) {
  54494. return {
  54495. tagContent: xmlData.substring(startIndex, i4),
  54496. i: closeIndex
  54497. };
  54498. }
  54499. }
  54500. i4 = closeIndex;
  54501. } else if (xmlData[i4 + 1] === "?") {
  54502. const closeIndex = findClosingIndex(xmlData, "?>", i4 + 1, "StopNode is not closed.");
  54503. i4 = closeIndex;
  54504. } else if (xmlData.substr(i4 + 1, 3) === "!--") {
  54505. const closeIndex = findClosingIndex(xmlData, "-->", i4 + 3, "StopNode is not closed.");
  54506. i4 = closeIndex;
  54507. } else if (xmlData.substr(i4 + 1, 2) === "![") {
  54508. const closeIndex = findClosingIndex(xmlData, "]]>", i4, "StopNode is not closed.") - 2;
  54509. i4 = closeIndex;
  54510. } else {
  54511. const tagData = readTagExp(xmlData, i4, ">");
  54512. if (tagData) {
  54513. const openTagName = tagData && tagData.tagName;
  54514. if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== "/") {
  54515. openTagCount++;
  54516. }
  54517. i4 = tagData.closeIndex;
  54518. }
  54519. }
  54520. }
  54521. }
  54522. }
  54523. function parseValue(val2, shouldParse, options) {
  54524. if (shouldParse && typeof val2 === "string") {
  54525. const newval = val2.trim();
  54526. if (newval === "true") return true;
  54527. else if (newval === "false") return false;
  54528. else return toNumber(val2, options);
  54529. } else {
  54530. if (util2.isExist(val2)) {
  54531. return val2;
  54532. } else {
  54533. return "";
  54534. }
  54535. }
  54536. }
  54537. module2.exports = OrderedObjParser;
  54538. }
  54539. });
  54540. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js
  54541. var require_node2json = __commonJS({
  54542. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports2) {
  54543. "use strict";
  54544. function prettify(node, options) {
  54545. return compress2(node, options);
  54546. }
  54547. function compress2(arr, options, jPath) {
  54548. let text;
  54549. const compressedObj = {};
  54550. for (let i4 = 0; i4 < arr.length; i4++) {
  54551. const tagObj = arr[i4];
  54552. const property = propName(tagObj);
  54553. let newJpath = "";
  54554. if (jPath === void 0) newJpath = property;
  54555. else newJpath = jPath + "." + property;
  54556. if (property === options.textNodeName) {
  54557. if (text === void 0) text = tagObj[property];
  54558. else text += "" + tagObj[property];
  54559. } else if (property === void 0) {
  54560. continue;
  54561. } else if (tagObj[property]) {
  54562. let val2 = compress2(tagObj[property], options, newJpath);
  54563. const isLeaf = isLeafTag(val2, options);
  54564. if (tagObj[":@"]) {
  54565. assignAttributes(val2, tagObj[":@"], newJpath, options);
  54566. } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) {
  54567. val2 = val2[options.textNodeName];
  54568. } else if (Object.keys(val2).length === 0) {
  54569. if (options.alwaysCreateTextNode) val2[options.textNodeName] = "";
  54570. else val2 = "";
  54571. }
  54572. if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) {
  54573. if (!Array.isArray(compressedObj[property])) {
  54574. compressedObj[property] = [compressedObj[property]];
  54575. }
  54576. compressedObj[property].push(val2);
  54577. } else {
  54578. if (options.isArray(property, newJpath, isLeaf)) {
  54579. compressedObj[property] = [val2];
  54580. } else {
  54581. compressedObj[property] = val2;
  54582. }
  54583. }
  54584. }
  54585. }
  54586. if (typeof text === "string") {
  54587. if (text.length > 0) compressedObj[options.textNodeName] = text;
  54588. } else if (text !== void 0) compressedObj[options.textNodeName] = text;
  54589. return compressedObj;
  54590. }
  54591. function propName(obj) {
  54592. const keys = Object.keys(obj);
  54593. for (let i4 = 0; i4 < keys.length; i4++) {
  54594. const key = keys[i4];
  54595. if (key !== ":@") return key;
  54596. }
  54597. }
  54598. function assignAttributes(obj, attrMap, jpath, options) {
  54599. if (attrMap) {
  54600. const keys = Object.keys(attrMap);
  54601. const len = keys.length;
  54602. for (let i4 = 0; i4 < len; i4++) {
  54603. const atrrName = keys[i4];
  54604. if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
  54605. obj[atrrName] = [attrMap[atrrName]];
  54606. } else {
  54607. obj[atrrName] = attrMap[atrrName];
  54608. }
  54609. }
  54610. }
  54611. }
  54612. function isLeafTag(obj, options) {
  54613. const { textNodeName } = options;
  54614. const propCount = Object.keys(obj).length;
  54615. if (propCount === 0) {
  54616. return true;
  54617. }
  54618. if (propCount === 1 && (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)) {
  54619. return true;
  54620. }
  54621. return false;
  54622. }
  54623. exports2.prettify = prettify;
  54624. }
  54625. });
  54626. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js
  54627. var require_XMLParser = __commonJS({
  54628. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports2, module2) {
  54629. var { buildOptions } = require_OptionsBuilder();
  54630. var OrderedObjParser = require_OrderedObjParser();
  54631. var { prettify } = require_node2json();
  54632. var validator2 = require_validator();
  54633. var XMLParser2 = class {
  54634. constructor(options) {
  54635. this.externalEntities = {};
  54636. this.options = buildOptions(options);
  54637. }
  54638. /**
  54639. * Parse XML dats to JS object
  54640. * @param {string|Buffer} xmlData
  54641. * @param {boolean|Object} validationOption
  54642. */
  54643. parse(xmlData, validationOption) {
  54644. if (typeof xmlData === "string") {
  54645. } else if (xmlData.toString) {
  54646. xmlData = xmlData.toString();
  54647. } else {
  54648. throw new Error("XML data is accepted in String or Bytes[] form.");
  54649. }
  54650. if (validationOption) {
  54651. if (validationOption === true) validationOption = {};
  54652. const result = validator2.validate(xmlData, validationOption);
  54653. if (result !== true) {
  54654. throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`);
  54655. }
  54656. }
  54657. const orderedObjParser = new OrderedObjParser(this.options);
  54658. orderedObjParser.addExternalEntities(this.externalEntities);
  54659. const orderedResult = orderedObjParser.parseXml(xmlData);
  54660. if (this.options.preserveOrder || orderedResult === void 0) return orderedResult;
  54661. else return prettify(orderedResult, this.options);
  54662. }
  54663. /**
  54664. * Add Entity which is not by default supported by this library
  54665. * @param {string} key
  54666. * @param {string} value
  54667. */
  54668. addEntity(key, value) {
  54669. if (value.indexOf("&") !== -1) {
  54670. throw new Error("Entity value can't have '&'");
  54671. } else if (key.indexOf("&") !== -1 || key.indexOf(";") !== -1) {
  54672. throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");
  54673. } else if (value === "&") {
  54674. throw new Error("An entity with value '&' is not permitted");
  54675. } else {
  54676. this.externalEntities[key] = value;
  54677. }
  54678. }
  54679. };
  54680. module2.exports = XMLParser2;
  54681. }
  54682. });
  54683. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js
  54684. var require_orderedJs2Xml = __commonJS({
  54685. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports2, module2) {
  54686. var EOL = "\n";
  54687. function toXml(jArray, options) {
  54688. let indentation = "";
  54689. if (options.format && options.indentBy.length > 0) {
  54690. indentation = EOL;
  54691. }
  54692. return arrToStr(jArray, options, "", indentation);
  54693. }
  54694. function arrToStr(arr, options, jPath, indentation) {
  54695. let xmlStr = "";
  54696. let isPreviousElementTag = false;
  54697. for (let i4 = 0; i4 < arr.length; i4++) {
  54698. const tagObj = arr[i4];
  54699. const tagName = propName(tagObj);
  54700. if (tagName === void 0) continue;
  54701. let newJPath = "";
  54702. if (jPath.length === 0) newJPath = tagName;
  54703. else newJPath = `${jPath}.${tagName}`;
  54704. if (tagName === options.textNodeName) {
  54705. let tagText = tagObj[tagName];
  54706. if (!isStopNode(newJPath, options)) {
  54707. tagText = options.tagValueProcessor(tagName, tagText);
  54708. tagText = replaceEntitiesValue(tagText, options);
  54709. }
  54710. if (isPreviousElementTag) {
  54711. xmlStr += indentation;
  54712. }
  54713. xmlStr += tagText;
  54714. isPreviousElementTag = false;
  54715. continue;
  54716. } else if (tagName === options.cdataPropName) {
  54717. if (isPreviousElementTag) {
  54718. xmlStr += indentation;
  54719. }
  54720. xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`;
  54721. isPreviousElementTag = false;
  54722. continue;
  54723. } else if (tagName === options.commentPropName) {
  54724. xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`;
  54725. isPreviousElementTag = true;
  54726. continue;
  54727. } else if (tagName[0] === "?") {
  54728. const attStr2 = attr_to_str(tagObj[":@"], options);
  54729. const tempInd = tagName === "?xml" ? "" : indentation;
  54730. let piTextNodeName = tagObj[tagName][0][options.textNodeName];
  54731. piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : "";
  54732. xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr2}?>`;
  54733. isPreviousElementTag = true;
  54734. continue;
  54735. }
  54736. let newIdentation = indentation;
  54737. if (newIdentation !== "") {
  54738. newIdentation += options.indentBy;
  54739. }
  54740. const attStr = attr_to_str(tagObj[":@"], options);
  54741. const tagStart = indentation + `<${tagName}${attStr}`;
  54742. const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
  54743. if (options.unpairedTags.indexOf(tagName) !== -1) {
  54744. if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
  54745. else xmlStr += tagStart + "/>";
  54746. } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
  54747. xmlStr += tagStart + "/>";
  54748. } else if (tagValue && tagValue.endsWith(">")) {
  54749. xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>`;
  54750. } else {
  54751. xmlStr += tagStart + ">";
  54752. if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) {
  54753. xmlStr += indentation + options.indentBy + tagValue + indentation;
  54754. } else {
  54755. xmlStr += tagValue;
  54756. }
  54757. xmlStr += `</${tagName}>`;
  54758. }
  54759. isPreviousElementTag = true;
  54760. }
  54761. return xmlStr;
  54762. }
  54763. function propName(obj) {
  54764. const keys = Object.keys(obj);
  54765. for (let i4 = 0; i4 < keys.length; i4++) {
  54766. const key = keys[i4];
  54767. if (!obj.hasOwnProperty(key)) continue;
  54768. if (key !== ":@") return key;
  54769. }
  54770. }
  54771. function attr_to_str(attrMap, options) {
  54772. let attrStr = "";
  54773. if (attrMap && !options.ignoreAttributes) {
  54774. for (let attr in attrMap) {
  54775. if (!attrMap.hasOwnProperty(attr)) continue;
  54776. let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
  54777. attrVal = replaceEntitiesValue(attrVal, options);
  54778. if (attrVal === true && options.suppressBooleanAttributes) {
  54779. attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
  54780. } else {
  54781. attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
  54782. }
  54783. }
  54784. }
  54785. return attrStr;
  54786. }
  54787. function isStopNode(jPath, options) {
  54788. jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
  54789. let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
  54790. for (let index6 in options.stopNodes) {
  54791. if (options.stopNodes[index6] === jPath || options.stopNodes[index6] === "*." + tagName) return true;
  54792. }
  54793. return false;
  54794. }
  54795. function replaceEntitiesValue(textValue, options) {
  54796. if (textValue && textValue.length > 0 && options.processEntities) {
  54797. for (let i4 = 0; i4 < options.entities.length; i4++) {
  54798. const entity = options.entities[i4];
  54799. textValue = textValue.replace(entity.regex, entity.val);
  54800. }
  54801. }
  54802. return textValue;
  54803. }
  54804. module2.exports = toXml;
  54805. }
  54806. });
  54807. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js
  54808. var require_json2xml = __commonJS({
  54809. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports2, module2) {
  54810. "use strict";
  54811. var buildFromOrderedJs = require_orderedJs2Xml();
  54812. var defaultOptions = {
  54813. attributeNamePrefix: "@_",
  54814. attributesGroupName: false,
  54815. textNodeName: "#text",
  54816. ignoreAttributes: true,
  54817. cdataPropName: false,
  54818. format: false,
  54819. indentBy: " ",
  54820. suppressEmptyNode: false,
  54821. suppressUnpairedNode: true,
  54822. suppressBooleanAttributes: true,
  54823. tagValueProcessor: function(key, a3) {
  54824. return a3;
  54825. },
  54826. attributeValueProcessor: function(attrName, a3) {
  54827. return a3;
  54828. },
  54829. preserveOrder: false,
  54830. commentPropName: false,
  54831. unpairedTags: [],
  54832. entities: [
  54833. { regex: new RegExp("&", "g"), val: "&amp;" },
  54834. //it must be on top
  54835. { regex: new RegExp(">", "g"), val: "&gt;" },
  54836. { regex: new RegExp("<", "g"), val: "&lt;" },
  54837. { regex: new RegExp("'", "g"), val: "&apos;" },
  54838. { regex: new RegExp('"', "g"), val: "&quot;" }
  54839. ],
  54840. processEntities: true,
  54841. stopNodes: [],
  54842. // transformTagName: false,
  54843. // transformAttributeName: false,
  54844. oneListGroup: false
  54845. };
  54846. function Builder(options) {
  54847. this.options = Object.assign({}, defaultOptions, options);
  54848. if (this.options.ignoreAttributes || this.options.attributesGroupName) {
  54849. this.isAttribute = function() {
  54850. return false;
  54851. };
  54852. } else {
  54853. this.attrPrefixLen = this.options.attributeNamePrefix.length;
  54854. this.isAttribute = isAttribute;
  54855. }
  54856. this.processTextOrObjNode = processTextOrObjNode;
  54857. if (this.options.format) {
  54858. this.indentate = indentate;
  54859. this.tagEndChar = ">\n";
  54860. this.newLine = "\n";
  54861. } else {
  54862. this.indentate = function() {
  54863. return "";
  54864. };
  54865. this.tagEndChar = ">";
  54866. this.newLine = "";
  54867. }
  54868. }
  54869. Builder.prototype.build = function(jObj) {
  54870. if (this.options.preserveOrder) {
  54871. return buildFromOrderedJs(jObj, this.options);
  54872. } else {
  54873. if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {
  54874. jObj = {
  54875. [this.options.arrayNodeName]: jObj
  54876. };
  54877. }
  54878. return this.j2x(jObj, 0).val;
  54879. }
  54880. };
  54881. Builder.prototype.j2x = function(jObj, level) {
  54882. let attrStr = "";
  54883. let val2 = "";
  54884. for (let key in jObj) {
  54885. if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
  54886. if (typeof jObj[key] === "undefined") {
  54887. if (this.isAttribute(key)) {
  54888. val2 += "";
  54889. }
  54890. } else if (jObj[key] === null) {
  54891. if (this.isAttribute(key)) {
  54892. val2 += "";
  54893. } else if (key[0] === "?") {
  54894. val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
  54895. } else {
  54896. val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
  54897. }
  54898. } else if (jObj[key] instanceof Date) {
  54899. val2 += this.buildTextValNode(jObj[key], key, "", level);
  54900. } else if (typeof jObj[key] !== "object") {
  54901. const attr = this.isAttribute(key);
  54902. if (attr) {
  54903. attrStr += this.buildAttrPairStr(attr, "" + jObj[key]);
  54904. } else {
  54905. if (key === this.options.textNodeName) {
  54906. let newval = this.options.tagValueProcessor(key, "" + jObj[key]);
  54907. val2 += this.replaceEntitiesValue(newval);
  54908. } else {
  54909. val2 += this.buildTextValNode(jObj[key], key, "", level);
  54910. }
  54911. }
  54912. } else if (Array.isArray(jObj[key])) {
  54913. const arrLen = jObj[key].length;
  54914. let listTagVal = "";
  54915. let listTagAttr = "";
  54916. for (let j3 = 0; j3 < arrLen; j3++) {
  54917. const item = jObj[key][j3];
  54918. if (typeof item === "undefined") {
  54919. } else if (item === null) {
  54920. if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar;
  54921. else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar;
  54922. } else if (typeof item === "object") {
  54923. if (this.options.oneListGroup) {
  54924. const result = this.j2x(item, level + 1);
  54925. listTagVal += result.val;
  54926. if (this.options.attributesGroupName && item.hasOwnProperty(this.options.attributesGroupName)) {
  54927. listTagAttr += result.attrStr;
  54928. }
  54929. } else {
  54930. listTagVal += this.processTextOrObjNode(item, key, level);
  54931. }
  54932. } else {
  54933. if (this.options.oneListGroup) {
  54934. let textValue = this.options.tagValueProcessor(key, item);
  54935. textValue = this.replaceEntitiesValue(textValue);
  54936. listTagVal += textValue;
  54937. } else {
  54938. listTagVal += this.buildTextValNode(item, key, "", level);
  54939. }
  54940. }
  54941. }
  54942. if (this.options.oneListGroup) {
  54943. listTagVal = this.buildObjectNode(listTagVal, key, listTagAttr, level);
  54944. }
  54945. val2 += listTagVal;
  54946. } else {
  54947. if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
  54948. const Ks = Object.keys(jObj[key]);
  54949. const L = Ks.length;
  54950. for (let j3 = 0; j3 < L; j3++) {
  54951. attrStr += this.buildAttrPairStr(Ks[j3], "" + jObj[key][Ks[j3]]);
  54952. }
  54953. } else {
  54954. val2 += this.processTextOrObjNode(jObj[key], key, level);
  54955. }
  54956. }
  54957. }
  54958. return { attrStr, val: val2 };
  54959. };
  54960. Builder.prototype.buildAttrPairStr = function(attrName, val2) {
  54961. val2 = this.options.attributeValueProcessor(attrName, "" + val2);
  54962. val2 = this.replaceEntitiesValue(val2);
  54963. if (this.options.suppressBooleanAttributes && val2 === "true") {
  54964. return " " + attrName;
  54965. } else return " " + attrName + '="' + val2 + '"';
  54966. };
  54967. function processTextOrObjNode(object, key, level) {
  54968. const result = this.j2x(object, level + 1);
  54969. if (object[this.options.textNodeName] !== void 0 && Object.keys(object).length === 1) {
  54970. return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
  54971. } else {
  54972. return this.buildObjectNode(result.val, key, result.attrStr, level);
  54973. }
  54974. }
  54975. Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) {
  54976. if (val2 === "") {
  54977. if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
  54978. else {
  54979. return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
  54980. }
  54981. } else {
  54982. let tagEndExp = "</" + key + this.tagEndChar;
  54983. let piClosingChar = "";
  54984. if (key[0] === "?") {
  54985. piClosingChar = "?";
  54986. tagEndExp = "";
  54987. }
  54988. if ((attrStr || attrStr === "") && val2.indexOf("<") === -1) {
  54989. return this.indentate(level) + "<" + key + attrStr + piClosingChar + ">" + val2 + tagEndExp;
  54990. } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
  54991. return this.indentate(level) + `<!--${val2}-->` + this.newLine;
  54992. } else {
  54993. return this.indentate(level) + "<" + key + attrStr + piClosingChar + this.tagEndChar + val2 + this.indentate(level) + tagEndExp;
  54994. }
  54995. }
  54996. };
  54997. Builder.prototype.closeTag = function(key) {
  54998. let closeTag = "";
  54999. if (this.options.unpairedTags.indexOf(key) !== -1) {
  55000. if (!this.options.suppressUnpairedNode) closeTag = "/";
  55001. } else if (this.options.suppressEmptyNode) {
  55002. closeTag = "/";
  55003. } else {
  55004. closeTag = `></${key}`;
  55005. }
  55006. return closeTag;
  55007. };
  55008. Builder.prototype.buildTextValNode = function(val2, key, attrStr, level) {
  55009. if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
  55010. return this.indentate(level) + `<![CDATA[${val2}]]>` + this.newLine;
  55011. } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
  55012. return this.indentate(level) + `<!--${val2}-->` + this.newLine;
  55013. } else if (key[0] === "?") {
  55014. return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar;
  55015. } else {
  55016. let textValue = this.options.tagValueProcessor(key, val2);
  55017. textValue = this.replaceEntitiesValue(textValue);
  55018. if (textValue === "") {
  55019. return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar;
  55020. } else {
  55021. return this.indentate(level) + "<" + key + attrStr + ">" + textValue + "</" + key + this.tagEndChar;
  55022. }
  55023. }
  55024. };
  55025. Builder.prototype.replaceEntitiesValue = function(textValue) {
  55026. if (textValue && textValue.length > 0 && this.options.processEntities) {
  55027. for (let i4 = 0; i4 < this.options.entities.length; i4++) {
  55028. const entity = this.options.entities[i4];
  55029. textValue = textValue.replace(entity.regex, entity.val);
  55030. }
  55031. }
  55032. return textValue;
  55033. };
  55034. function indentate(level) {
  55035. return this.options.indentBy.repeat(level);
  55036. }
  55037. function isAttribute(name) {
  55038. if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
  55039. return name.substr(this.attrPrefixLen);
  55040. } else {
  55041. return false;
  55042. }
  55043. }
  55044. module2.exports = Builder;
  55045. }
  55046. });
  55047. // ../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js
  55048. var require_fxp = __commonJS({
  55049. "../node_modules/.pnpm/fast-xml-parser@4.4.1/node_modules/fast-xml-parser/src/fxp.js"(exports2, module2) {
  55050. "use strict";
  55051. var validator2 = require_validator();
  55052. var XMLParser2 = require_XMLParser();
  55053. var XMLBuilder = require_json2xml();
  55054. module2.exports = {
  55055. XMLParser: XMLParser2,
  55056. XMLValidator: validator2,
  55057. XMLBuilder
  55058. };
  55059. }
  55060. });
  55061. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js
  55062. var import_smithy_client3, import_fast_xml_parser, parseXmlBody, parseXmlErrorBody, loadRestXmlErrorCode;
  55063. var init_parseXmlBody = __esm({
  55064. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js"() {
  55065. import_smithy_client3 = __toESM(require_dist_cjs23());
  55066. import_fast_xml_parser = __toESM(require_fxp());
  55067. init_common2();
  55068. parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => {
  55069. if (encoded.length) {
  55070. const parser = new import_fast_xml_parser.XMLParser({
  55071. attributeNamePrefix: "",
  55072. htmlEntities: true,
  55073. ignoreAttributes: false,
  55074. ignoreDeclaration: true,
  55075. parseTagValue: false,
  55076. trimValues: false,
  55077. tagValueProcessor: (_3, val2) => val2.trim() === "" && val2.includes("\n") ? "" : void 0
  55078. });
  55079. parser.addEntity("#xD", "\r");
  55080. parser.addEntity("#10", "\n");
  55081. let parsedObj;
  55082. try {
  55083. parsedObj = parser.parse(encoded, true);
  55084. } catch (e4) {
  55085. if (e4 && typeof e4 === "object") {
  55086. Object.defineProperty(e4, "$responseBodyText", {
  55087. value: encoded
  55088. });
  55089. }
  55090. throw e4;
  55091. }
  55092. const textNodeName = "#text";
  55093. const key = Object.keys(parsedObj)[0];
  55094. const parsedObjToReturn = parsedObj[key];
  55095. if (parsedObjToReturn[textNodeName]) {
  55096. parsedObjToReturn[key] = parsedObjToReturn[textNodeName];
  55097. delete parsedObjToReturn[textNodeName];
  55098. }
  55099. return (0, import_smithy_client3.getValueFromTextNode)(parsedObjToReturn);
  55100. }
  55101. return {};
  55102. });
  55103. parseXmlErrorBody = async (errorBody, context) => {
  55104. const value = await parseXmlBody(errorBody, context);
  55105. if (value.Error) {
  55106. value.Error.message = value.Error.message ?? value.Error.Message;
  55107. }
  55108. return value;
  55109. };
  55110. loadRestXmlErrorCode = (output, data) => {
  55111. var _a2;
  55112. if (((_a2 = data == null ? void 0 : data.Error) == null ? void 0 : _a2.Code) !== void 0) {
  55113. return data.Error.Code;
  55114. }
  55115. if ((data == null ? void 0 : data.Code) !== void 0) {
  55116. return data.Code;
  55117. }
  55118. if (output.statusCode == 404) {
  55119. return "NotFound";
  55120. }
  55121. };
  55122. }
  55123. });
  55124. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js
  55125. var init_protocols2 = __esm({
  55126. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js"() {
  55127. init_coercing_serializers();
  55128. init_awsExpectUnion();
  55129. init_parseJsonBody();
  55130. init_parseXmlBody();
  55131. }
  55132. });
  55133. // ../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/index.js
  55134. var dist_es_exports2 = {};
  55135. __export(dist_es_exports2, {
  55136. AWSSDKSigV4Signer: () => AWSSDKSigV4Signer,
  55137. AwsSdkSigV4ASigner: () => AwsSdkSigV4ASigner,
  55138. AwsSdkSigV4Signer: () => AwsSdkSigV4Signer,
  55139. NODE_AUTH_SCHEME_PREFERENCE_OPTIONS: () => NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,
  55140. NODE_SIGV4A_CONFIG_OPTIONS: () => NODE_SIGV4A_CONFIG_OPTIONS,
  55141. _toBool: () => _toBool,
  55142. _toNum: () => _toNum,
  55143. _toStr: () => _toStr,
  55144. awsExpectUnion: () => awsExpectUnion,
  55145. emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion,
  55146. getBearerTokenEnvKey: () => getBearerTokenEnvKey,
  55147. loadRestJsonErrorCode: () => loadRestJsonErrorCode,
  55148. loadRestXmlErrorCode: () => loadRestXmlErrorCode,
  55149. parseJsonBody: () => parseJsonBody,
  55150. parseJsonErrorBody: () => parseJsonErrorBody,
  55151. parseXmlBody: () => parseXmlBody,
  55152. parseXmlErrorBody: () => parseXmlErrorBody,
  55153. resolveAWSSDKSigV4Config: () => resolveAWSSDKSigV4Config,
  55154. resolveAwsSdkSigV4AConfig: () => resolveAwsSdkSigV4AConfig,
  55155. resolveAwsSdkSigV4Config: () => resolveAwsSdkSigV4Config,
  55156. setCredentialFeature: () => setCredentialFeature,
  55157. setFeature: () => setFeature2,
  55158. state: () => state,
  55159. validateSigningProperties: () => validateSigningProperties
  55160. });
  55161. var init_dist_es2 = __esm({
  55162. "../node_modules/.pnpm/@aws-sdk+core@3.816.0/node_modules/@aws-sdk/core/dist-es/index.js"() {
  55163. init_client();
  55164. init_httpAuthSchemes2();
  55165. init_protocols2();
  55166. }
  55167. });
  55168. // ../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js
  55169. var require_dist_cjs24 = __commonJS({
  55170. "../node_modules/.pnpm/@aws-sdk+middleware-user-agent@3.816.0/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js"(exports2, module2) {
  55171. "use strict";
  55172. var __defProp3 = Object.defineProperty;
  55173. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  55174. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  55175. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  55176. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  55177. var __export2 = (target, all) => {
  55178. for (var name in all)
  55179. __defProp3(target, name, { get: all[name], enumerable: true });
  55180. };
  55181. var __copyProps3 = (to, from, except, desc) => {
  55182. if (from && typeof from === "object" || typeof from === "function") {
  55183. for (let key of __getOwnPropNames3(from))
  55184. if (!__hasOwnProp3.call(to, key) && key !== except)
  55185. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  55186. }
  55187. return to;
  55188. };
  55189. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  55190. var index_exports = {};
  55191. __export2(index_exports, {
  55192. DEFAULT_UA_APP_ID: () => DEFAULT_UA_APP_ID,
  55193. getUserAgentMiddlewareOptions: () => getUserAgentMiddlewareOptions,
  55194. getUserAgentPlugin: () => getUserAgentPlugin3,
  55195. resolveUserAgentConfig: () => resolveUserAgentConfig3,
  55196. userAgentMiddleware: () => userAgentMiddleware
  55197. });
  55198. module2.exports = __toCommonJS2(index_exports);
  55199. var import_core17 = (init_dist_es(), __toCommonJS(dist_es_exports));
  55200. var DEFAULT_UA_APP_ID = void 0;
  55201. function isValidUserAgentAppId(appId) {
  55202. if (appId === void 0) {
  55203. return true;
  55204. }
  55205. return typeof appId === "string" && appId.length <= 50;
  55206. }
  55207. __name(isValidUserAgentAppId, "isValidUserAgentAppId");
  55208. function resolveUserAgentConfig3(input) {
  55209. const normalizedAppIdProvider = (0, import_core17.normalizeProvider)(input.userAgentAppId ?? DEFAULT_UA_APP_ID);
  55210. const { customUserAgent } = input;
  55211. return Object.assign(input, {
  55212. customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent,
  55213. userAgentAppId: /* @__PURE__ */ __name(async () => {
  55214. var _a2, _b;
  55215. const appId = await normalizedAppIdProvider();
  55216. if (!isValidUserAgentAppId(appId)) {
  55217. const logger3 = ((_b = (_a2 = input.logger) == null ? void 0 : _a2.constructor) == null ? void 0 : _b.name) === "NoOpLogger" || !input.logger ? console : input.logger;
  55218. if (typeof appId !== "string") {
  55219. logger3 == null ? void 0 : logger3.warn("userAgentAppId must be a string or undefined.");
  55220. } else if (appId.length > 50) {
  55221. logger3 == null ? void 0 : logger3.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.");
  55222. }
  55223. }
  55224. return appId;
  55225. }, "userAgentAppId")
  55226. });
  55227. }
  55228. __name(resolveUserAgentConfig3, "resolveUserAgentConfig");
  55229. var import_util_endpoints5 = require_dist_cjs19();
  55230. var import_protocol_http15 = require_dist_cjs2();
  55231. var import_core22 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
  55232. var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/;
  55233. async function checkFeatures(context, config, args) {
  55234. var _a2, _b, _c, _d, _e, _f, _g;
  55235. const request = args.request;
  55236. if (((_a2 = request == null ? void 0 : request.headers) == null ? void 0 : _a2["smithy-protocol"]) === "rpc-v2-cbor") {
  55237. (0, import_core22.setFeature)(context, "PROTOCOL_RPC_V2_CBOR", "M");
  55238. }
  55239. if (typeof config.retryStrategy === "function") {
  55240. const retryStrategy = await config.retryStrategy();
  55241. if (typeof retryStrategy.acquireInitialRetryToken === "function") {
  55242. if ((_c = (_b = retryStrategy.constructor) == null ? void 0 : _b.name) == null ? void 0 : _c.includes("Adaptive")) {
  55243. (0, import_core22.setFeature)(context, "RETRY_MODE_ADAPTIVE", "F");
  55244. } else {
  55245. (0, import_core22.setFeature)(context, "RETRY_MODE_STANDARD", "E");
  55246. }
  55247. } else {
  55248. (0, import_core22.setFeature)(context, "RETRY_MODE_LEGACY", "D");
  55249. }
  55250. }
  55251. if (typeof config.accountIdEndpointMode === "function") {
  55252. const endpointV2 = context.endpointV2;
  55253. if (String((_d = endpointV2 == null ? void 0 : endpointV2.url) == null ? void 0 : _d.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) {
  55254. (0, import_core22.setFeature)(context, "ACCOUNT_ID_ENDPOINT", "O");
  55255. }
  55256. switch (await ((_e = config.accountIdEndpointMode) == null ? void 0 : _e.call(config))) {
  55257. case "disabled":
  55258. (0, import_core22.setFeature)(context, "ACCOUNT_ID_MODE_DISABLED", "Q");
  55259. break;
  55260. case "preferred":
  55261. (0, import_core22.setFeature)(context, "ACCOUNT_ID_MODE_PREFERRED", "P");
  55262. break;
  55263. case "required":
  55264. (0, import_core22.setFeature)(context, "ACCOUNT_ID_MODE_REQUIRED", "R");
  55265. break;
  55266. }
  55267. }
  55268. const identity = (_g = (_f = context.__smithy_context) == null ? void 0 : _f.selectedHttpAuthScheme) == null ? void 0 : _g.identity;
  55269. if (identity == null ? void 0 : identity.$source) {
  55270. const credentials2 = identity;
  55271. if (credentials2.accountId) {
  55272. (0, import_core22.setFeature)(context, "RESOLVED_ACCOUNT_ID", "T");
  55273. }
  55274. for (const [key, value] of Object.entries(credentials2.$source ?? {})) {
  55275. (0, import_core22.setFeature)(context, key, value);
  55276. }
  55277. }
  55278. }
  55279. __name(checkFeatures, "checkFeatures");
  55280. var USER_AGENT = "user-agent";
  55281. var X_AMZ_USER_AGENT = "x-amz-user-agent";
  55282. var SPACE2 = " ";
  55283. var UA_NAME_SEPARATOR = "/";
  55284. var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;
  55285. var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;
  55286. var UA_ESCAPE_CHAR = "-";
  55287. var BYTE_LIMIT = 1024;
  55288. function encodeFeatures(features) {
  55289. let buffer = "";
  55290. for (const key in features) {
  55291. const val2 = features[key];
  55292. if (buffer.length + val2.length + 1 <= BYTE_LIMIT) {
  55293. if (buffer.length) {
  55294. buffer += "," + val2;
  55295. } else {
  55296. buffer += val2;
  55297. }
  55298. continue;
  55299. }
  55300. break;
  55301. }
  55302. return buffer;
  55303. }
  55304. __name(encodeFeatures, "encodeFeatures");
  55305. var userAgentMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => {
  55306. var _a2, _b, _c, _d;
  55307. const { request } = args;
  55308. if (!import_protocol_http15.HttpRequest.isInstance(request)) {
  55309. return next(args);
  55310. }
  55311. const { headers } = request;
  55312. const userAgent = ((_a2 = context == null ? void 0 : context.userAgent) == null ? void 0 : _a2.map(escapeUserAgent)) || [];
  55313. const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent);
  55314. await checkFeatures(context, options, args);
  55315. const awsContext = context;
  55316. defaultUserAgent.push(
  55317. `m/${encodeFeatures(
  55318. Object.assign({}, (_b = context.__smithy_context) == null ? void 0 : _b.features, (_c = awsContext.__aws_sdk_context) == null ? void 0 : _c.features)
  55319. )}`
  55320. );
  55321. const customUserAgent = ((_d = options == null ? void 0 : options.customUserAgent) == null ? void 0 : _d.map(escapeUserAgent)) || [];
  55322. const appId = await options.userAgentAppId();
  55323. if (appId) {
  55324. defaultUserAgent.push(escapeUserAgent([`app/${appId}`]));
  55325. }
  55326. const prefix2 = (0, import_util_endpoints5.getUserAgentPrefix)();
  55327. const sdkUserAgentValue = (prefix2 ? [prefix2] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE2);
  55328. const normalUAValue = [
  55329. ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")),
  55330. ...customUserAgent
  55331. ].join(SPACE2);
  55332. if (options.runtime !== "browser") {
  55333. if (normalUAValue) {
  55334. headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue;
  55335. }
  55336. headers[USER_AGENT] = sdkUserAgentValue;
  55337. } else {
  55338. headers[X_AMZ_USER_AGENT] = sdkUserAgentValue;
  55339. }
  55340. return next({
  55341. ...args,
  55342. request
  55343. });
  55344. }, "userAgentMiddleware");
  55345. var escapeUserAgent = /* @__PURE__ */ __name((userAgentPair) => {
  55346. var _a2;
  55347. const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);
  55348. const version3 = (_a2 = userAgentPair[1]) == null ? void 0 : _a2.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR);
  55349. const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR);
  55350. const prefix2 = name.substring(0, prefixSeparatorIndex);
  55351. let uaName = name.substring(prefixSeparatorIndex + 1);
  55352. if (prefix2 === "api") {
  55353. uaName = uaName.toLowerCase();
  55354. }
  55355. return [prefix2, uaName, version3].filter((item) => item && item.length > 0).reduce((acc, item, index6) => {
  55356. switch (index6) {
  55357. case 0:
  55358. return item;
  55359. case 1:
  55360. return `${acc}/${item}`;
  55361. default:
  55362. return `${acc}#${item}`;
  55363. }
  55364. }, "");
  55365. }, "escapeUserAgent");
  55366. var getUserAgentMiddlewareOptions = {
  55367. name: "getUserAgentMiddleware",
  55368. step: "build",
  55369. priority: "low",
  55370. tags: ["SET_USER_AGENT", "USER_AGENT"],
  55371. override: true
  55372. };
  55373. var getUserAgentPlugin3 = /* @__PURE__ */ __name((config) => ({
  55374. applyToStack: /* @__PURE__ */ __name((clientStack) => {
  55375. clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);
  55376. }, "applyToStack")
  55377. }), "getUserAgentPlugin");
  55378. }
  55379. });
  55380. // ../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-cjs/index.js
  55381. var require_dist_cjs25 = __commonJS({
  55382. "../node_modules/.pnpm/@smithy+util-config-provider@4.0.0/node_modules/@smithy/util-config-provider/dist-cjs/index.js"(exports2, module2) {
  55383. var __defProp3 = Object.defineProperty;
  55384. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  55385. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  55386. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  55387. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  55388. var __export2 = (target, all) => {
  55389. for (var name in all)
  55390. __defProp3(target, name, { get: all[name], enumerable: true });
  55391. };
  55392. var __copyProps3 = (to, from, except, desc) => {
  55393. if (from && typeof from === "object" || typeof from === "function") {
  55394. for (let key of __getOwnPropNames3(from))
  55395. if (!__hasOwnProp3.call(to, key) && key !== except)
  55396. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  55397. }
  55398. return to;
  55399. };
  55400. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  55401. var src_exports = {};
  55402. __export2(src_exports, {
  55403. SelectorType: () => SelectorType,
  55404. booleanSelector: () => booleanSelector,
  55405. numberSelector: () => numberSelector
  55406. });
  55407. module2.exports = __toCommonJS2(src_exports);
  55408. var booleanSelector = /* @__PURE__ */ __name((obj, key, type) => {
  55409. if (!(key in obj))
  55410. return void 0;
  55411. if (obj[key] === "true")
  55412. return true;
  55413. if (obj[key] === "false")
  55414. return false;
  55415. throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`);
  55416. }, "booleanSelector");
  55417. var numberSelector = /* @__PURE__ */ __name((obj, key, type) => {
  55418. if (!(key in obj))
  55419. return void 0;
  55420. const numberValue = parseInt(obj[key], 10);
  55421. if (Number.isNaN(numberValue)) {
  55422. throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`);
  55423. }
  55424. return numberValue;
  55425. }, "numberSelector");
  55426. var SelectorType = /* @__PURE__ */ ((SelectorType2) => {
  55427. SelectorType2["ENV"] = "env";
  55428. SelectorType2["CONFIG"] = "shared config entry";
  55429. return SelectorType2;
  55430. })(SelectorType || {});
  55431. }
  55432. });
  55433. // ../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-cjs/index.js
  55434. var require_dist_cjs26 = __commonJS({
  55435. "../node_modules/.pnpm/@smithy+config-resolver@4.1.4/node_modules/@smithy/config-resolver/dist-cjs/index.js"(exports2, module2) {
  55436. var __defProp3 = Object.defineProperty;
  55437. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  55438. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  55439. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  55440. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  55441. var __export2 = (target, all) => {
  55442. for (var name in all)
  55443. __defProp3(target, name, { get: all[name], enumerable: true });
  55444. };
  55445. var __copyProps3 = (to, from, except, desc) => {
  55446. if (from && typeof from === "object" || typeof from === "function") {
  55447. for (let key of __getOwnPropNames3(from))
  55448. if (!__hasOwnProp3.call(to, key) && key !== except)
  55449. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  55450. }
  55451. return to;
  55452. };
  55453. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  55454. var src_exports = {};
  55455. __export2(src_exports, {
  55456. CONFIG_USE_DUALSTACK_ENDPOINT: () => CONFIG_USE_DUALSTACK_ENDPOINT,
  55457. CONFIG_USE_FIPS_ENDPOINT: () => CONFIG_USE_FIPS_ENDPOINT,
  55458. DEFAULT_USE_DUALSTACK_ENDPOINT: () => DEFAULT_USE_DUALSTACK_ENDPOINT,
  55459. DEFAULT_USE_FIPS_ENDPOINT: () => DEFAULT_USE_FIPS_ENDPOINT,
  55460. ENV_USE_DUALSTACK_ENDPOINT: () => ENV_USE_DUALSTACK_ENDPOINT,
  55461. ENV_USE_FIPS_ENDPOINT: () => ENV_USE_FIPS_ENDPOINT,
  55462. NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS3,
  55463. NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS3,
  55464. NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS3,
  55465. NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS: () => NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS3,
  55466. REGION_ENV_NAME: () => REGION_ENV_NAME,
  55467. REGION_INI_NAME: () => REGION_INI_NAME,
  55468. getRegionInfo: () => getRegionInfo,
  55469. resolveCustomEndpointsConfig: () => resolveCustomEndpointsConfig,
  55470. resolveEndpointsConfig: () => resolveEndpointsConfig,
  55471. resolveRegionConfig: () => resolveRegionConfig3
  55472. });
  55473. module2.exports = __toCommonJS2(src_exports);
  55474. var import_util_config_provider = require_dist_cjs25();
  55475. var ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT";
  55476. var CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
  55477. var DEFAULT_USE_DUALSTACK_ENDPOINT = false;
  55478. var NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS3 = {
  55479. environmentVariableSelector: (env3) => (0, import_util_config_provider.booleanSelector)(env3, ENV_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.ENV),
  55480. configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_DUALSTACK_ENDPOINT, import_util_config_provider.SelectorType.CONFIG),
  55481. default: false
  55482. };
  55483. var ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT";
  55484. var CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint";
  55485. var DEFAULT_USE_FIPS_ENDPOINT = false;
  55486. var NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS3 = {
  55487. environmentVariableSelector: (env3) => (0, import_util_config_provider.booleanSelector)(env3, ENV_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.ENV),
  55488. configFileSelector: (profile) => (0, import_util_config_provider.booleanSelector)(profile, CONFIG_USE_FIPS_ENDPOINT, import_util_config_provider.SelectorType.CONFIG),
  55489. default: false
  55490. };
  55491. var import_util_middleware7 = require_dist_cjs6();
  55492. var resolveCustomEndpointsConfig = /* @__PURE__ */ __name((input) => {
  55493. const { tls, endpoint, urlParser, useDualstackEndpoint } = input;
  55494. return Object.assign(input, {
  55495. tls: tls ?? true,
  55496. endpoint: (0, import_util_middleware7.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint),
  55497. isCustomEndpoint: true,
  55498. useDualstackEndpoint: (0, import_util_middleware7.normalizeProvider)(useDualstackEndpoint ?? false)
  55499. });
  55500. }, "resolveCustomEndpointsConfig");
  55501. var getEndpointFromRegion = /* @__PURE__ */ __name(async (input) => {
  55502. const { tls = true } = input;
  55503. const region = await input.region();
  55504. const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/);
  55505. if (!dnsHostRegex.test(region)) {
  55506. throw new Error("Invalid region in client config");
  55507. }
  55508. const useDualstackEndpoint = await input.useDualstackEndpoint();
  55509. const useFipsEndpoint = await input.useFipsEndpoint();
  55510. const { hostname } = await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint }) ?? {};
  55511. if (!hostname) {
  55512. throw new Error("Cannot resolve hostname from client config");
  55513. }
  55514. return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`);
  55515. }, "getEndpointFromRegion");
  55516. var resolveEndpointsConfig = /* @__PURE__ */ __name((input) => {
  55517. const useDualstackEndpoint = (0, import_util_middleware7.normalizeProvider)(input.useDualstackEndpoint ?? false);
  55518. const { endpoint, useFipsEndpoint, urlParser, tls } = input;
  55519. return Object.assign(input, {
  55520. tls: tls ?? true,
  55521. endpoint: endpoint ? (0, import_util_middleware7.normalizeProvider)(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }),
  55522. isCustomEndpoint: !!endpoint,
  55523. useDualstackEndpoint
  55524. });
  55525. }, "resolveEndpointsConfig");
  55526. var REGION_ENV_NAME = "AWS_REGION";
  55527. var REGION_INI_NAME = "region";
  55528. var NODE_REGION_CONFIG_OPTIONS3 = {
  55529. environmentVariableSelector: (env3) => env3[REGION_ENV_NAME],
  55530. configFileSelector: (profile) => profile[REGION_INI_NAME],
  55531. default: () => {
  55532. throw new Error("Region is missing");
  55533. }
  55534. };
  55535. var NODE_REGION_CONFIG_FILE_OPTIONS3 = {
  55536. preferredFile: "credentials"
  55537. };
  55538. var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion");
  55539. var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion");
  55540. var resolveRegionConfig3 = /* @__PURE__ */ __name((input) => {
  55541. const { region, useFipsEndpoint } = input;
  55542. if (!region) {
  55543. throw new Error("Region is missing");
  55544. }
  55545. return Object.assign(input, {
  55546. region: async () => {
  55547. if (typeof region === "string") {
  55548. return getRealRegion(region);
  55549. }
  55550. const providedRegion = await region();
  55551. return getRealRegion(providedRegion);
  55552. },
  55553. useFipsEndpoint: async () => {
  55554. const providedRegion = typeof region === "string" ? region : await region();
  55555. if (isFipsRegion(providedRegion)) {
  55556. return true;
  55557. }
  55558. return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
  55559. }
  55560. });
  55561. }, "resolveRegionConfig");
  55562. var getHostnameFromVariants = /* @__PURE__ */ __name((variants = [], { useFipsEndpoint, useDualstackEndpoint }) => {
  55563. var _a2;
  55564. return (_a2 = variants.find(
  55565. ({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack")
  55566. )) == null ? void 0 : _a2.hostname;
  55567. }, "getHostnameFromVariants");
  55568. var getResolvedHostname = /* @__PURE__ */ __name((resolvedRegion, { regionHostname, partitionHostname }) => regionHostname ? regionHostname : partitionHostname ? partitionHostname.replace("{region}", resolvedRegion) : void 0, "getResolvedHostname");
  55569. var getResolvedPartition = /* @__PURE__ */ __name((region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws", "getResolvedPartition");
  55570. var getResolvedSigningRegion = /* @__PURE__ */ __name((hostname, { signingRegion, regionRegex, useFipsEndpoint }) => {
  55571. if (signingRegion) {
  55572. return signingRegion;
  55573. } else if (useFipsEndpoint) {
  55574. const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\.");
  55575. const regionRegexmatchArray = hostname.match(regionRegexJs);
  55576. if (regionRegexmatchArray) {
  55577. return regionRegexmatchArray[0].slice(1, -1);
  55578. }
  55579. }
  55580. }, "getResolvedSigningRegion");
  55581. var getRegionInfo = /* @__PURE__ */ __name((region, {
  55582. useFipsEndpoint = false,
  55583. useDualstackEndpoint = false,
  55584. signingService,
  55585. regionHash,
  55586. partitionHash
  55587. }) => {
  55588. var _a2, _b, _c, _d, _e;
  55589. const partition = getResolvedPartition(region, { partitionHash });
  55590. const resolvedRegion = region in regionHash ? region : ((_a2 = partitionHash[partition]) == null ? void 0 : _a2.endpoint) ?? region;
  55591. const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint };
  55592. const regionHostname = getHostnameFromVariants((_b = regionHash[resolvedRegion]) == null ? void 0 : _b.variants, hostnameOptions);
  55593. const partitionHostname = getHostnameFromVariants((_c = partitionHash[partition]) == null ? void 0 : _c.variants, hostnameOptions);
  55594. const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname });
  55595. if (hostname === void 0) {
  55596. throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`);
  55597. }
  55598. const signingRegion = getResolvedSigningRegion(hostname, {
  55599. signingRegion: (_d = regionHash[resolvedRegion]) == null ? void 0 : _d.signingRegion,
  55600. regionRegex: partitionHash[partition].regionRegex,
  55601. useFipsEndpoint
  55602. });
  55603. return {
  55604. partition,
  55605. signingService,
  55606. hostname,
  55607. ...signingRegion && { signingRegion },
  55608. ...((_e = regionHash[resolvedRegion]) == null ? void 0 : _e.signingService) && {
  55609. signingService: regionHash[resolvedRegion].signingService
  55610. }
  55611. };
  55612. }, "getRegionInfo");
  55613. }
  55614. });
  55615. // ../node_modules/.pnpm/@smithy+middleware-content-length@4.0.4/node_modules/@smithy/middleware-content-length/dist-cjs/index.js
  55616. var require_dist_cjs27 = __commonJS({
  55617. "../node_modules/.pnpm/@smithy+middleware-content-length@4.0.4/node_modules/@smithy/middleware-content-length/dist-cjs/index.js"(exports2, module2) {
  55618. var __defProp3 = Object.defineProperty;
  55619. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  55620. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  55621. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  55622. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  55623. var __export2 = (target, all) => {
  55624. for (var name in all)
  55625. __defProp3(target, name, { get: all[name], enumerable: true });
  55626. };
  55627. var __copyProps3 = (to, from, except, desc) => {
  55628. if (from && typeof from === "object" || typeof from === "function") {
  55629. for (let key of __getOwnPropNames3(from))
  55630. if (!__hasOwnProp3.call(to, key) && key !== except)
  55631. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  55632. }
  55633. return to;
  55634. };
  55635. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  55636. var src_exports = {};
  55637. __export2(src_exports, {
  55638. contentLengthMiddleware: () => contentLengthMiddleware,
  55639. contentLengthMiddlewareOptions: () => contentLengthMiddlewareOptions,
  55640. getContentLengthPlugin: () => getContentLengthPlugin3
  55641. });
  55642. module2.exports = __toCommonJS2(src_exports);
  55643. var import_protocol_http15 = require_dist_cjs2();
  55644. var CONTENT_LENGTH_HEADER = "content-length";
  55645. function contentLengthMiddleware(bodyLengthChecker) {
  55646. return (next) => async (args) => {
  55647. const request = args.request;
  55648. if (import_protocol_http15.HttpRequest.isInstance(request)) {
  55649. const { body, headers } = request;
  55650. if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) {
  55651. try {
  55652. const length = bodyLengthChecker(body);
  55653. request.headers = {
  55654. ...request.headers,
  55655. [CONTENT_LENGTH_HEADER]: String(length)
  55656. };
  55657. } catch (error2) {
  55658. }
  55659. }
  55660. }
  55661. return next({
  55662. ...args,
  55663. request
  55664. });
  55665. };
  55666. }
  55667. __name(contentLengthMiddleware, "contentLengthMiddleware");
  55668. var contentLengthMiddlewareOptions = {
  55669. step: "build",
  55670. tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"],
  55671. name: "contentLengthMiddleware",
  55672. override: true
  55673. };
  55674. var getContentLengthPlugin3 = /* @__PURE__ */ __name((options) => ({
  55675. applyToStack: (clientStack) => {
  55676. clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions);
  55677. }
  55678. }), "getContentLengthPlugin");
  55679. }
  55680. });
  55681. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js
  55682. var require_getHomeDir = __commonJS({
  55683. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js"(exports2) {
  55684. "use strict";
  55685. Object.defineProperty(exports2, "__esModule", { value: true });
  55686. exports2.getHomeDir = void 0;
  55687. var os_1 = require("os");
  55688. var path_1 = require("path");
  55689. var homeDirCache = {};
  55690. var getHomeDirCacheKey = () => {
  55691. if (process && process.geteuid) {
  55692. return `${process.geteuid()}`;
  55693. }
  55694. return "DEFAULT";
  55695. };
  55696. var getHomeDir2 = () => {
  55697. const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env;
  55698. if (HOME)
  55699. return HOME;
  55700. if (USERPROFILE)
  55701. return USERPROFILE;
  55702. if (HOMEPATH)
  55703. return `${HOMEDRIVE}${HOMEPATH}`;
  55704. const homeDirCacheKey = getHomeDirCacheKey();
  55705. if (!homeDirCache[homeDirCacheKey])
  55706. homeDirCache[homeDirCacheKey] = (0, os_1.homedir)();
  55707. return homeDirCache[homeDirCacheKey];
  55708. };
  55709. exports2.getHomeDir = getHomeDir2;
  55710. }
  55711. });
  55712. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js
  55713. var require_getSSOTokenFilepath = __commonJS({
  55714. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js"(exports2) {
  55715. "use strict";
  55716. Object.defineProperty(exports2, "__esModule", { value: true });
  55717. exports2.getSSOTokenFilepath = void 0;
  55718. var crypto_1 = require("crypto");
  55719. var path_1 = require("path");
  55720. var getHomeDir_1 = require_getHomeDir();
  55721. var getSSOTokenFilepath2 = (id) => {
  55722. const hasher = (0, crypto_1.createHash)("sha1");
  55723. const cacheName = hasher.update(id).digest("hex");
  55724. return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`);
  55725. };
  55726. exports2.getSSOTokenFilepath = getSSOTokenFilepath2;
  55727. }
  55728. });
  55729. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js
  55730. var require_getSSOTokenFromFile = __commonJS({
  55731. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js"(exports2) {
  55732. "use strict";
  55733. Object.defineProperty(exports2, "__esModule", { value: true });
  55734. exports2.getSSOTokenFromFile = void 0;
  55735. var fs_1 = require("fs");
  55736. var getSSOTokenFilepath_1 = require_getSSOTokenFilepath();
  55737. var { readFile: readFile2 } = fs_1.promises;
  55738. var getSSOTokenFromFile2 = async (id) => {
  55739. const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id);
  55740. const ssoTokenText = await readFile2(ssoTokenFilepath, "utf8");
  55741. return JSON.parse(ssoTokenText);
  55742. };
  55743. exports2.getSSOTokenFromFile = getSSOTokenFromFile2;
  55744. }
  55745. });
  55746. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/slurpFile.js
  55747. var require_slurpFile = __commonJS({
  55748. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/slurpFile.js"(exports2) {
  55749. "use strict";
  55750. Object.defineProperty(exports2, "__esModule", { value: true });
  55751. exports2.slurpFile = void 0;
  55752. var fs_1 = require("fs");
  55753. var { readFile: readFile2 } = fs_1.promises;
  55754. var filePromisesHash = {};
  55755. var slurpFile = (path4, options) => {
  55756. if (!filePromisesHash[path4] || (options === null || options === void 0 ? void 0 : options.ignoreCache)) {
  55757. filePromisesHash[path4] = readFile2(path4, "utf8");
  55758. }
  55759. return filePromisesHash[path4];
  55760. };
  55761. exports2.slurpFile = slurpFile;
  55762. }
  55763. });
  55764. // ../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js
  55765. var require_dist_cjs28 = __commonJS({
  55766. "../node_modules/.pnpm/@smithy+shared-ini-file-loader@4.0.4/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js"(exports2, module2) {
  55767. var __defProp3 = Object.defineProperty;
  55768. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  55769. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  55770. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  55771. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  55772. var __export2 = (target, all) => {
  55773. for (var name in all)
  55774. __defProp3(target, name, { get: all[name], enumerable: true });
  55775. };
  55776. var __copyProps3 = (to, from, except, desc) => {
  55777. if (from && typeof from === "object" || typeof from === "function") {
  55778. for (let key of __getOwnPropNames3(from))
  55779. if (!__hasOwnProp3.call(to, key) && key !== except)
  55780. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  55781. }
  55782. return to;
  55783. };
  55784. var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
  55785. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  55786. var src_exports = {};
  55787. __export2(src_exports, {
  55788. CONFIG_PREFIX_SEPARATOR: () => CONFIG_PREFIX_SEPARATOR,
  55789. DEFAULT_PROFILE: () => DEFAULT_PROFILE,
  55790. ENV_PROFILE: () => ENV_PROFILE,
  55791. getProfileName: () => getProfileName,
  55792. loadSharedConfigFiles: () => loadSharedConfigFiles,
  55793. loadSsoSessionData: () => loadSsoSessionData,
  55794. parseKnownFiles: () => parseKnownFiles
  55795. });
  55796. module2.exports = __toCommonJS2(src_exports);
  55797. __reExport(src_exports, require_getHomeDir(), module2.exports);
  55798. var ENV_PROFILE = "AWS_PROFILE";
  55799. var DEFAULT_PROFILE = "default";
  55800. var getProfileName = /* @__PURE__ */ __name((init2) => init2.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE, "getProfileName");
  55801. __reExport(src_exports, require_getSSOTokenFilepath(), module2.exports);
  55802. __reExport(src_exports, require_getSSOTokenFromFile(), module2.exports);
  55803. var import_types5 = require_dist_cjs();
  55804. var getConfigData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => {
  55805. const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
  55806. if (indexOfSeparator === -1) {
  55807. return false;
  55808. }
  55809. return Object.values(import_types5.IniSectionType).includes(key.substring(0, indexOfSeparator));
  55810. }).reduce(
  55811. (acc, [key, value]) => {
  55812. const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR);
  55813. const updatedKey = key.substring(0, indexOfSeparator) === import_types5.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key;
  55814. acc[updatedKey] = value;
  55815. return acc;
  55816. },
  55817. {
  55818. // Populate default profile, if present.
  55819. ...data.default && { default: data.default }
  55820. }
  55821. ), "getConfigData");
  55822. var import_path8 = require("path");
  55823. var import_getHomeDir = require_getHomeDir();
  55824. var ENV_CONFIG_PATH = "AWS_CONFIG_FILE";
  55825. var getConfigFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CONFIG_PATH] || (0, import_path8.join)((0, import_getHomeDir.getHomeDir)(), ".aws", "config"), "getConfigFilepath");
  55826. var import_getHomeDir2 = require_getHomeDir();
  55827. var ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE";
  55828. var getCredentialsFilepath = /* @__PURE__ */ __name(() => process.env[ENV_CREDENTIALS_PATH] || (0, import_path8.join)((0, import_getHomeDir2.getHomeDir)(), ".aws", "credentials"), "getCredentialsFilepath");
  55829. var import_getHomeDir3 = require_getHomeDir();
  55830. var prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/;
  55831. var profileNameBlockList = ["__proto__", "profile __proto__"];
  55832. var parseIni = /* @__PURE__ */ __name((iniData) => {
  55833. const map2 = {};
  55834. let currentSection;
  55835. let currentSubSection;
  55836. for (const iniLine of iniData.split(/\r?\n/)) {
  55837. const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim();
  55838. const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]";
  55839. if (isSection) {
  55840. currentSection = void 0;
  55841. currentSubSection = void 0;
  55842. const sectionName = trimmedLine.substring(1, trimmedLine.length - 1);
  55843. const matches = prefixKeyRegex.exec(sectionName);
  55844. if (matches) {
  55845. const [, prefix2, , name] = matches;
  55846. if (Object.values(import_types5.IniSectionType).includes(prefix2)) {
  55847. currentSection = [prefix2, name].join(CONFIG_PREFIX_SEPARATOR);
  55848. }
  55849. } else {
  55850. currentSection = sectionName;
  55851. }
  55852. if (profileNameBlockList.includes(sectionName)) {
  55853. throw new Error(`Found invalid profile name "${sectionName}"`);
  55854. }
  55855. } else if (currentSection) {
  55856. const indexOfEqualsSign = trimmedLine.indexOf("=");
  55857. if (![0, -1].includes(indexOfEqualsSign)) {
  55858. const [name, value] = [
  55859. trimmedLine.substring(0, indexOfEqualsSign).trim(),
  55860. trimmedLine.substring(indexOfEqualsSign + 1).trim()
  55861. ];
  55862. if (value === "") {
  55863. currentSubSection = name;
  55864. } else {
  55865. if (currentSubSection && iniLine.trimStart() === iniLine) {
  55866. currentSubSection = void 0;
  55867. }
  55868. map2[currentSection] = map2[currentSection] || {};
  55869. const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name;
  55870. map2[currentSection][key] = value;
  55871. }
  55872. }
  55873. }
  55874. }
  55875. return map2;
  55876. }, "parseIni");
  55877. var import_slurpFile = require_slurpFile();
  55878. var swallowError = /* @__PURE__ */ __name(() => ({}), "swallowError");
  55879. var CONFIG_PREFIX_SEPARATOR = ".";
  55880. var loadSharedConfigFiles = /* @__PURE__ */ __name(async (init2 = {}) => {
  55881. const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init2;
  55882. const homeDir = (0, import_getHomeDir3.getHomeDir)();
  55883. const relativeHomeDirPrefix = "~/";
  55884. let resolvedFilepath = filepath;
  55885. if (filepath.startsWith(relativeHomeDirPrefix)) {
  55886. resolvedFilepath = (0, import_path8.join)(homeDir, filepath.slice(2));
  55887. }
  55888. let resolvedConfigFilepath = configFilepath;
  55889. if (configFilepath.startsWith(relativeHomeDirPrefix)) {
  55890. resolvedConfigFilepath = (0, import_path8.join)(homeDir, configFilepath.slice(2));
  55891. }
  55892. const parsedFiles = await Promise.all([
  55893. (0, import_slurpFile.slurpFile)(resolvedConfigFilepath, {
  55894. ignoreCache: init2.ignoreCache
  55895. }).then(parseIni).then(getConfigData).catch(swallowError),
  55896. (0, import_slurpFile.slurpFile)(resolvedFilepath, {
  55897. ignoreCache: init2.ignoreCache
  55898. }).then(parseIni).catch(swallowError)
  55899. ]);
  55900. return {
  55901. configFile: parsedFiles[0],
  55902. credentialsFile: parsedFiles[1]
  55903. };
  55904. }, "loadSharedConfigFiles");
  55905. var getSsoSessionData = /* @__PURE__ */ __name((data) => Object.entries(data).filter(([key]) => key.startsWith(import_types5.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)).reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}), "getSsoSessionData");
  55906. var import_slurpFile2 = require_slurpFile();
  55907. var swallowError2 = /* @__PURE__ */ __name(() => ({}), "swallowError");
  55908. var loadSsoSessionData = /* @__PURE__ */ __name(async (init2 = {}) => (0, import_slurpFile2.slurpFile)(init2.configFilepath ?? getConfigFilepath()).then(parseIni).then(getSsoSessionData).catch(swallowError2), "loadSsoSessionData");
  55909. var mergeConfigFiles = /* @__PURE__ */ __name((...files) => {
  55910. const merged = {};
  55911. for (const file of files) {
  55912. for (const [key, values] of Object.entries(file)) {
  55913. if (merged[key] !== void 0) {
  55914. Object.assign(merged[key], values);
  55915. } else {
  55916. merged[key] = values;
  55917. }
  55918. }
  55919. }
  55920. return merged;
  55921. }, "mergeConfigFiles");
  55922. var parseKnownFiles = /* @__PURE__ */ __name(async (init2) => {
  55923. const parsedFiles = await loadSharedConfigFiles(init2);
  55924. return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile);
  55925. }, "parseKnownFiles");
  55926. }
  55927. });
  55928. // ../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-cjs/index.js
  55929. var require_dist_cjs29 = __commonJS({
  55930. "../node_modules/.pnpm/@smithy+node-config-provider@4.1.3/node_modules/@smithy/node-config-provider/dist-cjs/index.js"(exports2, module2) {
  55931. var __defProp3 = Object.defineProperty;
  55932. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  55933. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  55934. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  55935. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  55936. var __export2 = (target, all) => {
  55937. for (var name in all)
  55938. __defProp3(target, name, { get: all[name], enumerable: true });
  55939. };
  55940. var __copyProps3 = (to, from, except, desc) => {
  55941. if (from && typeof from === "object" || typeof from === "function") {
  55942. for (let key of __getOwnPropNames3(from))
  55943. if (!__hasOwnProp3.call(to, key) && key !== except)
  55944. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  55945. }
  55946. return to;
  55947. };
  55948. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  55949. var src_exports = {};
  55950. __export2(src_exports, {
  55951. loadConfig: () => loadConfig
  55952. });
  55953. module2.exports = __toCommonJS2(src_exports);
  55954. var import_property_provider2 = require_dist_cjs20();
  55955. function getSelectorName(functionString) {
  55956. try {
  55957. const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? []));
  55958. constants.delete("CONFIG");
  55959. constants.delete("CONFIG_PREFIX_SEPARATOR");
  55960. constants.delete("ENV");
  55961. return [...constants].join(", ");
  55962. } catch (e4) {
  55963. return functionString;
  55964. }
  55965. }
  55966. __name(getSelectorName, "getSelectorName");
  55967. var fromEnv = /* @__PURE__ */ __name((envVarSelector, options) => async () => {
  55968. try {
  55969. const config = envVarSelector(process.env, options);
  55970. if (config === void 0) {
  55971. throw new Error();
  55972. }
  55973. return config;
  55974. } catch (e4) {
  55975. throw new import_property_provider2.CredentialsProviderError(
  55976. e4.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`,
  55977. { logger: options == null ? void 0 : options.logger }
  55978. );
  55979. }
  55980. }, "fromEnv");
  55981. var import_shared_ini_file_loader = require_dist_cjs28();
  55982. var fromSharedConfigFiles = /* @__PURE__ */ __name((configSelector, { preferredFile = "config", ...init2 } = {}) => async () => {
  55983. const profile = (0, import_shared_ini_file_loader.getProfileName)(init2);
  55984. const { configFile, credentialsFile } = await (0, import_shared_ini_file_loader.loadSharedConfigFiles)(init2);
  55985. const profileFromCredentials = credentialsFile[profile] || {};
  55986. const profileFromConfig = configFile[profile] || {};
  55987. const mergedProfile = preferredFile === "config" ? { ...profileFromCredentials, ...profileFromConfig } : { ...profileFromConfig, ...profileFromCredentials };
  55988. try {
  55989. const cfgFile = preferredFile === "config" ? configFile : credentialsFile;
  55990. const configValue = configSelector(mergedProfile, cfgFile);
  55991. if (configValue === void 0) {
  55992. throw new Error();
  55993. }
  55994. return configValue;
  55995. } catch (e4) {
  55996. throw new import_property_provider2.CredentialsProviderError(
  55997. e4.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`,
  55998. { logger: init2.logger }
  55999. );
  56000. }
  56001. }, "fromSharedConfigFiles");
  56002. var isFunction = /* @__PURE__ */ __name((func) => typeof func === "function", "isFunction");
  56003. var fromStatic = /* @__PURE__ */ __name((defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : (0, import_property_provider2.fromStatic)(defaultValue), "fromStatic");
  56004. var loadConfig = /* @__PURE__ */ __name(({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => {
  56005. const { signingName, logger: logger3 } = configuration;
  56006. const envOptions = { signingName, logger: logger3 };
  56007. return (0, import_property_provider2.memoize)(
  56008. (0, import_property_provider2.chain)(
  56009. fromEnv(environmentVariableSelector, envOptions),
  56010. fromSharedConfigFiles(configFileSelector, configuration),
  56011. fromStatic(defaultValue)
  56012. )
  56013. );
  56014. }, "loadConfig");
  56015. }
  56016. });
  56017. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js
  56018. var require_getEndpointUrlConfig = __commonJS({
  56019. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js"(exports2) {
  56020. "use strict";
  56021. Object.defineProperty(exports2, "__esModule", { value: true });
  56022. exports2.getEndpointUrlConfig = void 0;
  56023. var shared_ini_file_loader_1 = require_dist_cjs28();
  56024. var ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL";
  56025. var CONFIG_ENDPOINT_URL = "endpoint_url";
  56026. var getEndpointUrlConfig = (serviceId) => ({
  56027. environmentVariableSelector: (env3) => {
  56028. const serviceSuffixParts = serviceId.split(" ").map((w3) => w3.toUpperCase());
  56029. const serviceEndpointUrl = env3[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")];
  56030. if (serviceEndpointUrl)
  56031. return serviceEndpointUrl;
  56032. const endpointUrl = env3[ENV_ENDPOINT_URL];
  56033. if (endpointUrl)
  56034. return endpointUrl;
  56035. return void 0;
  56036. },
  56037. configFileSelector: (profile, config) => {
  56038. if (config && profile.services) {
  56039. const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)];
  56040. if (servicesSection) {
  56041. const servicePrefixParts = serviceId.split(" ").map((w3) => w3.toLowerCase());
  56042. const endpointUrl2 = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)];
  56043. if (endpointUrl2)
  56044. return endpointUrl2;
  56045. }
  56046. }
  56047. const endpointUrl = profile[CONFIG_ENDPOINT_URL];
  56048. if (endpointUrl)
  56049. return endpointUrl;
  56050. return void 0;
  56051. },
  56052. default: void 0
  56053. });
  56054. exports2.getEndpointUrlConfig = getEndpointUrlConfig;
  56055. }
  56056. });
  56057. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js
  56058. var require_getEndpointFromConfig = __commonJS({
  56059. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js"(exports2) {
  56060. "use strict";
  56061. Object.defineProperty(exports2, "__esModule", { value: true });
  56062. exports2.getEndpointFromConfig = void 0;
  56063. var node_config_provider_1 = require_dist_cjs29();
  56064. var getEndpointUrlConfig_1 = require_getEndpointUrlConfig();
  56065. var getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId !== null && serviceId !== void 0 ? serviceId : ""))();
  56066. exports2.getEndpointFromConfig = getEndpointFromConfig;
  56067. }
  56068. });
  56069. // ../node_modules/.pnpm/@smithy+querystring-parser@4.0.4/node_modules/@smithy/querystring-parser/dist-cjs/index.js
  56070. var require_dist_cjs30 = __commonJS({
  56071. "../node_modules/.pnpm/@smithy+querystring-parser@4.0.4/node_modules/@smithy/querystring-parser/dist-cjs/index.js"(exports2, module2) {
  56072. var __defProp3 = Object.defineProperty;
  56073. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  56074. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  56075. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  56076. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  56077. var __export2 = (target, all) => {
  56078. for (var name in all)
  56079. __defProp3(target, name, { get: all[name], enumerable: true });
  56080. };
  56081. var __copyProps3 = (to, from, except, desc) => {
  56082. if (from && typeof from === "object" || typeof from === "function") {
  56083. for (let key of __getOwnPropNames3(from))
  56084. if (!__hasOwnProp3.call(to, key) && key !== except)
  56085. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  56086. }
  56087. return to;
  56088. };
  56089. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  56090. var src_exports = {};
  56091. __export2(src_exports, {
  56092. parseQueryString: () => parseQueryString
  56093. });
  56094. module2.exports = __toCommonJS2(src_exports);
  56095. function parseQueryString(querystring) {
  56096. const query = {};
  56097. querystring = querystring.replace(/^\?/, "");
  56098. if (querystring) {
  56099. for (const pair of querystring.split("&")) {
  56100. let [key, value = null] = pair.split("=");
  56101. key = decodeURIComponent(key);
  56102. if (value) {
  56103. value = decodeURIComponent(value);
  56104. }
  56105. if (!(key in query)) {
  56106. query[key] = value;
  56107. } else if (Array.isArray(query[key])) {
  56108. query[key].push(value);
  56109. } else {
  56110. query[key] = [query[key], value];
  56111. }
  56112. }
  56113. }
  56114. return query;
  56115. }
  56116. __name(parseQueryString, "parseQueryString");
  56117. }
  56118. });
  56119. // ../node_modules/.pnpm/@smithy+url-parser@4.0.4/node_modules/@smithy/url-parser/dist-cjs/index.js
  56120. var require_dist_cjs31 = __commonJS({
  56121. "../node_modules/.pnpm/@smithy+url-parser@4.0.4/node_modules/@smithy/url-parser/dist-cjs/index.js"(exports2, module2) {
  56122. var __defProp3 = Object.defineProperty;
  56123. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  56124. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  56125. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  56126. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  56127. var __export2 = (target, all) => {
  56128. for (var name in all)
  56129. __defProp3(target, name, { get: all[name], enumerable: true });
  56130. };
  56131. var __copyProps3 = (to, from, except, desc) => {
  56132. if (from && typeof from === "object" || typeof from === "function") {
  56133. for (let key of __getOwnPropNames3(from))
  56134. if (!__hasOwnProp3.call(to, key) && key !== except)
  56135. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  56136. }
  56137. return to;
  56138. };
  56139. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  56140. var src_exports = {};
  56141. __export2(src_exports, {
  56142. parseUrl: () => parseUrl3
  56143. });
  56144. module2.exports = __toCommonJS2(src_exports);
  56145. var import_querystring_parser = require_dist_cjs30();
  56146. var parseUrl3 = /* @__PURE__ */ __name((url) => {
  56147. if (typeof url === "string") {
  56148. return parseUrl3(new URL(url));
  56149. }
  56150. const { hostname, pathname, port, protocol, search } = url;
  56151. let query;
  56152. if (search) {
  56153. query = (0, import_querystring_parser.parseQueryString)(search);
  56154. }
  56155. return {
  56156. hostname,
  56157. port: port ? parseInt(port) : void 0,
  56158. protocol,
  56159. path: pathname,
  56160. query
  56161. };
  56162. }, "parseUrl");
  56163. }
  56164. });
  56165. // ../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js
  56166. var require_dist_cjs32 = __commonJS({
  56167. "../node_modules/.pnpm/@smithy+middleware-endpoint@4.1.9/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js"(exports2, module2) {
  56168. var __defProp3 = Object.defineProperty;
  56169. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  56170. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  56171. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  56172. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  56173. var __export2 = (target, all) => {
  56174. for (var name in all)
  56175. __defProp3(target, name, { get: all[name], enumerable: true });
  56176. };
  56177. var __copyProps3 = (to, from, except, desc) => {
  56178. if (from && typeof from === "object" || typeof from === "function") {
  56179. for (let key of __getOwnPropNames3(from))
  56180. if (!__hasOwnProp3.call(to, key) && key !== except)
  56181. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  56182. }
  56183. return to;
  56184. };
  56185. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  56186. var src_exports = {};
  56187. __export2(src_exports, {
  56188. endpointMiddleware: () => endpointMiddleware,
  56189. endpointMiddlewareOptions: () => endpointMiddlewareOptions,
  56190. getEndpointFromInstructions: () => getEndpointFromInstructions,
  56191. getEndpointPlugin: () => getEndpointPlugin4,
  56192. resolveEndpointConfig: () => resolveEndpointConfig3,
  56193. resolveParams: () => resolveParams,
  56194. toEndpointV1: () => toEndpointV1
  56195. });
  56196. module2.exports = __toCommonJS2(src_exports);
  56197. var resolveParamsForS3 = /* @__PURE__ */ __name(async (endpointParams) => {
  56198. const bucket = (endpointParams == null ? void 0 : endpointParams.Bucket) || "";
  56199. if (typeof endpointParams.Bucket === "string") {
  56200. endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?"));
  56201. }
  56202. if (isArnBucketName(bucket)) {
  56203. if (endpointParams.ForcePathStyle === true) {
  56204. throw new Error("Path-style addressing cannot be used with ARN buckets");
  56205. }
  56206. } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) {
  56207. endpointParams.ForcePathStyle = true;
  56208. }
  56209. if (endpointParams.DisableMultiRegionAccessPoints) {
  56210. endpointParams.disableMultiRegionAccessPoints = true;
  56211. endpointParams.DisableMRAP = true;
  56212. }
  56213. return endpointParams;
  56214. }, "resolveParamsForS3");
  56215. var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;
  56216. var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/;
  56217. var DOTS_PATTERN = /\.\./;
  56218. var isDnsCompatibleBucketName = /* @__PURE__ */ __name((bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName), "isDnsCompatibleBucketName");
  56219. var isArnBucketName = /* @__PURE__ */ __name((bucketName) => {
  56220. const [arn, partition, service, , , bucket] = bucketName.split(":");
  56221. const isArn = arn === "arn" && bucketName.split(":").length >= 6;
  56222. const isValidArn = Boolean(isArn && partition && service && bucket);
  56223. if (isArn && !isValidArn) {
  56224. throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);
  56225. }
  56226. return isValidArn;
  56227. }, "isArnBucketName");
  56228. var createConfigValueProvider = /* @__PURE__ */ __name((configKey, canonicalEndpointParamKey, config) => {
  56229. const configProvider = /* @__PURE__ */ __name(async () => {
  56230. const configValue = config[configKey] ?? config[canonicalEndpointParamKey];
  56231. if (typeof configValue === "function") {
  56232. return configValue();
  56233. }
  56234. return configValue;
  56235. }, "configProvider");
  56236. if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") {
  56237. return async () => {
  56238. const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
  56239. const configValue = (credentials2 == null ? void 0 : credentials2.credentialScope) ?? (credentials2 == null ? void 0 : credentials2.CredentialScope);
  56240. return configValue;
  56241. };
  56242. }
  56243. if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") {
  56244. return async () => {
  56245. const credentials2 = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
  56246. const configValue = (credentials2 == null ? void 0 : credentials2.accountId) ?? (credentials2 == null ? void 0 : credentials2.AccountId);
  56247. return configValue;
  56248. };
  56249. }
  56250. if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") {
  56251. return async () => {
  56252. const endpoint = await configProvider();
  56253. if (endpoint && typeof endpoint === "object") {
  56254. if ("url" in endpoint) {
  56255. return endpoint.url.href;
  56256. }
  56257. if ("hostname" in endpoint) {
  56258. const { protocol, hostname, port, path: path4 } = endpoint;
  56259. return `${protocol}//${hostname}${port ? ":" + port : ""}${path4}`;
  56260. }
  56261. }
  56262. return endpoint;
  56263. };
  56264. }
  56265. return configProvider;
  56266. }, "createConfigValueProvider");
  56267. var import_getEndpointFromConfig = require_getEndpointFromConfig();
  56268. var import_url_parser3 = require_dist_cjs31();
  56269. var toEndpointV1 = /* @__PURE__ */ __name((endpoint) => {
  56270. if (typeof endpoint === "object") {
  56271. if ("url" in endpoint) {
  56272. return (0, import_url_parser3.parseUrl)(endpoint.url);
  56273. }
  56274. return endpoint;
  56275. }
  56276. return (0, import_url_parser3.parseUrl)(endpoint);
  56277. }, "toEndpointV1");
  56278. var getEndpointFromInstructions = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig, context) => {
  56279. if (!clientConfig.endpoint) {
  56280. let endpointFromConfig;
  56281. if (clientConfig.serviceConfiguredEndpoint) {
  56282. endpointFromConfig = await clientConfig.serviceConfiguredEndpoint();
  56283. } else {
  56284. endpointFromConfig = await (0, import_getEndpointFromConfig.getEndpointFromConfig)(clientConfig.serviceId);
  56285. }
  56286. if (endpointFromConfig) {
  56287. clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig));
  56288. }
  56289. }
  56290. const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig);
  56291. if (typeof clientConfig.endpointProvider !== "function") {
  56292. throw new Error("config.endpointProvider is not set.");
  56293. }
  56294. const endpoint = clientConfig.endpointProvider(endpointParams, context);
  56295. return endpoint;
  56296. }, "getEndpointFromInstructions");
  56297. var resolveParams = /* @__PURE__ */ __name(async (commandInput, instructionsSupplier, clientConfig) => {
  56298. var _a2;
  56299. const endpointParams = {};
  56300. const instructions = ((_a2 = instructionsSupplier == null ? void 0 : instructionsSupplier.getEndpointParameterInstructions) == null ? void 0 : _a2.call(instructionsSupplier)) || {};
  56301. for (const [name, instruction] of Object.entries(instructions)) {
  56302. switch (instruction.type) {
  56303. case "staticContextParams":
  56304. endpointParams[name] = instruction.value;
  56305. break;
  56306. case "contextParams":
  56307. endpointParams[name] = commandInput[instruction.name];
  56308. break;
  56309. case "clientContextParams":
  56310. case "builtInParams":
  56311. endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)();
  56312. break;
  56313. case "operationContextParams":
  56314. endpointParams[name] = instruction.get(commandInput);
  56315. break;
  56316. default:
  56317. throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction));
  56318. }
  56319. }
  56320. if (Object.keys(instructions).length === 0) {
  56321. Object.assign(endpointParams, clientConfig);
  56322. }
  56323. if (String(clientConfig.serviceId).toLowerCase() === "s3") {
  56324. await resolveParamsForS3(endpointParams);
  56325. }
  56326. return endpointParams;
  56327. }, "resolveParams");
  56328. var import_core17 = (init_dist_es(), __toCommonJS(dist_es_exports));
  56329. var import_util_middleware7 = require_dist_cjs6();
  56330. var endpointMiddleware = /* @__PURE__ */ __name(({
  56331. config,
  56332. instructions
  56333. }) => {
  56334. return (next, context) => async (args) => {
  56335. var _a2, _b, _c;
  56336. if (config.endpoint) {
  56337. (0, import_core17.setFeature)(context, "ENDPOINT_OVERRIDE", "N");
  56338. }
  56339. const endpoint = await getEndpointFromInstructions(
  56340. args.input,
  56341. {
  56342. getEndpointParameterInstructions() {
  56343. return instructions;
  56344. }
  56345. },
  56346. { ...config },
  56347. context
  56348. );
  56349. context.endpointV2 = endpoint;
  56350. context.authSchemes = (_a2 = endpoint.properties) == null ? void 0 : _a2.authSchemes;
  56351. const authScheme = (_b = context.authSchemes) == null ? void 0 : _b[0];
  56352. if (authScheme) {
  56353. context["signing_region"] = authScheme.signingRegion;
  56354. context["signing_service"] = authScheme.signingName;
  56355. const smithyContext = (0, import_util_middleware7.getSmithyContext)(context);
  56356. const httpAuthOption = (_c = smithyContext == null ? void 0 : smithyContext.selectedHttpAuthScheme) == null ? void 0 : _c.httpAuthOption;
  56357. if (httpAuthOption) {
  56358. httpAuthOption.signingProperties = Object.assign(
  56359. httpAuthOption.signingProperties || {},
  56360. {
  56361. signing_region: authScheme.signingRegion,
  56362. signingRegion: authScheme.signingRegion,
  56363. signing_service: authScheme.signingName,
  56364. signingName: authScheme.signingName,
  56365. signingRegionSet: authScheme.signingRegionSet
  56366. },
  56367. authScheme.properties
  56368. );
  56369. }
  56370. }
  56371. return next({
  56372. ...args
  56373. });
  56374. };
  56375. }, "endpointMiddleware");
  56376. var import_middleware_serde5 = require_dist_cjs7();
  56377. var endpointMiddlewareOptions = {
  56378. step: "serialize",
  56379. tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"],
  56380. name: "endpointV2Middleware",
  56381. override: true,
  56382. relation: "before",
  56383. toMiddleware: import_middleware_serde5.serializerMiddlewareOption.name
  56384. };
  56385. var getEndpointPlugin4 = /* @__PURE__ */ __name((config, instructions) => ({
  56386. applyToStack: (clientStack) => {
  56387. clientStack.addRelativeTo(
  56388. endpointMiddleware({
  56389. config,
  56390. instructions
  56391. }),
  56392. endpointMiddlewareOptions
  56393. );
  56394. }
  56395. }), "getEndpointPlugin");
  56396. var import_getEndpointFromConfig2 = require_getEndpointFromConfig();
  56397. var resolveEndpointConfig3 = /* @__PURE__ */ __name((input) => {
  56398. const tls = input.tls ?? true;
  56399. const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input;
  56400. const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await (0, import_util_middleware7.normalizeProvider)(endpoint)()) : void 0;
  56401. const isCustomEndpoint = !!endpoint;
  56402. const resolvedConfig = Object.assign(input, {
  56403. endpoint: customEndpointProvider,
  56404. tls,
  56405. isCustomEndpoint,
  56406. useDualstackEndpoint: (0, import_util_middleware7.normalizeProvider)(useDualstackEndpoint ?? false),
  56407. useFipsEndpoint: (0, import_util_middleware7.normalizeProvider)(useFipsEndpoint ?? false)
  56408. });
  56409. let configuredEndpointPromise = void 0;
  56410. resolvedConfig.serviceConfiguredEndpoint = async () => {
  56411. if (input.serviceId && !configuredEndpointPromise) {
  56412. configuredEndpointPromise = (0, import_getEndpointFromConfig2.getEndpointFromConfig)(input.serviceId);
  56413. }
  56414. return configuredEndpointPromise;
  56415. };
  56416. return resolvedConfig;
  56417. }, "resolveEndpointConfig");
  56418. }
  56419. });
  56420. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js
  56421. function rng() {
  56422. if (poolPtr > rnds8Pool.length - 16) {
  56423. import_crypto2.default.randomFillSync(rnds8Pool);
  56424. poolPtr = 0;
  56425. }
  56426. return rnds8Pool.slice(poolPtr, poolPtr += 16);
  56427. }
  56428. var import_crypto2, rnds8Pool, poolPtr;
  56429. var init_rng = __esm({
  56430. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/rng.js"() {
  56431. import_crypto2 = __toESM(require("crypto"));
  56432. rnds8Pool = new Uint8Array(256);
  56433. poolPtr = rnds8Pool.length;
  56434. }
  56435. });
  56436. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/regex.js
  56437. var regex_default;
  56438. var init_regex = __esm({
  56439. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/regex.js"() {
  56440. regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
  56441. }
  56442. });
  56443. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/validate.js
  56444. function validate(uuid) {
  56445. return typeof uuid === "string" && regex_default.test(uuid);
  56446. }
  56447. var validate_default;
  56448. var init_validate = __esm({
  56449. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/validate.js"() {
  56450. init_regex();
  56451. validate_default = validate;
  56452. }
  56453. });
  56454. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js
  56455. function unsafeStringify(arr, offset = 0) {
  56456. return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
  56457. }
  56458. function stringify(arr, offset = 0) {
  56459. const uuid = unsafeStringify(arr, offset);
  56460. if (!validate_default(uuid)) {
  56461. throw TypeError("Stringified UUID is invalid");
  56462. }
  56463. return uuid;
  56464. }
  56465. var byteToHex, stringify_default;
  56466. var init_stringify = __esm({
  56467. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/stringify.js"() {
  56468. init_validate();
  56469. byteToHex = [];
  56470. for (let i4 = 0; i4 < 256; ++i4) {
  56471. byteToHex.push((i4 + 256).toString(16).slice(1));
  56472. }
  56473. stringify_default = stringify;
  56474. }
  56475. });
  56476. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v1.js
  56477. function v1(options, buf, offset) {
  56478. let i4 = buf && offset || 0;
  56479. const b3 = buf || new Array(16);
  56480. options = options || {};
  56481. let node = options.node || _nodeId;
  56482. let clockseq = options.clockseq !== void 0 ? options.clockseq : _clockseq;
  56483. if (node == null || clockseq == null) {
  56484. const seedBytes = options.random || (options.rng || rng)();
  56485. if (node == null) {
  56486. node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
  56487. }
  56488. if (clockseq == null) {
  56489. clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;
  56490. }
  56491. }
  56492. let msecs = options.msecs !== void 0 ? options.msecs : Date.now();
  56493. let nsecs = options.nsecs !== void 0 ? options.nsecs : _lastNSecs + 1;
  56494. const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;
  56495. if (dt < 0 && options.clockseq === void 0) {
  56496. clockseq = clockseq + 1 & 16383;
  56497. }
  56498. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === void 0) {
  56499. nsecs = 0;
  56500. }
  56501. if (nsecs >= 1e4) {
  56502. throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
  56503. }
  56504. _lastMSecs = msecs;
  56505. _lastNSecs = nsecs;
  56506. _clockseq = clockseq;
  56507. msecs += 122192928e5;
  56508. const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
  56509. b3[i4++] = tl >>> 24 & 255;
  56510. b3[i4++] = tl >>> 16 & 255;
  56511. b3[i4++] = tl >>> 8 & 255;
  56512. b3[i4++] = tl & 255;
  56513. const tmh = msecs / 4294967296 * 1e4 & 268435455;
  56514. b3[i4++] = tmh >>> 8 & 255;
  56515. b3[i4++] = tmh & 255;
  56516. b3[i4++] = tmh >>> 24 & 15 | 16;
  56517. b3[i4++] = tmh >>> 16 & 255;
  56518. b3[i4++] = clockseq >>> 8 | 128;
  56519. b3[i4++] = clockseq & 255;
  56520. for (let n3 = 0; n3 < 6; ++n3) {
  56521. b3[i4 + n3] = node[n3];
  56522. }
  56523. return buf || unsafeStringify(b3);
  56524. }
  56525. var _nodeId, _clockseq, _lastMSecs, _lastNSecs, v1_default;
  56526. var init_v1 = __esm({
  56527. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v1.js"() {
  56528. init_rng();
  56529. init_stringify();
  56530. _lastMSecs = 0;
  56531. _lastNSecs = 0;
  56532. v1_default = v1;
  56533. }
  56534. });
  56535. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/parse.js
  56536. function parse2(uuid) {
  56537. if (!validate_default(uuid)) {
  56538. throw TypeError("Invalid UUID");
  56539. }
  56540. let v6;
  56541. const arr = new Uint8Array(16);
  56542. arr[0] = (v6 = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  56543. arr[1] = v6 >>> 16 & 255;
  56544. arr[2] = v6 >>> 8 & 255;
  56545. arr[3] = v6 & 255;
  56546. arr[4] = (v6 = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  56547. arr[5] = v6 & 255;
  56548. arr[6] = (v6 = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  56549. arr[7] = v6 & 255;
  56550. arr[8] = (v6 = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  56551. arr[9] = v6 & 255;
  56552. arr[10] = (v6 = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;
  56553. arr[11] = v6 / 4294967296 & 255;
  56554. arr[12] = v6 >>> 24 & 255;
  56555. arr[13] = v6 >>> 16 & 255;
  56556. arr[14] = v6 >>> 8 & 255;
  56557. arr[15] = v6 & 255;
  56558. return arr;
  56559. }
  56560. var parse_default;
  56561. var init_parse = __esm({
  56562. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/parse.js"() {
  56563. init_validate();
  56564. parse_default = parse2;
  56565. }
  56566. });
  56567. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v35.js
  56568. function stringToBytes(str) {
  56569. str = unescape(encodeURIComponent(str));
  56570. const bytes = [];
  56571. for (let i4 = 0; i4 < str.length; ++i4) {
  56572. bytes.push(str.charCodeAt(i4));
  56573. }
  56574. return bytes;
  56575. }
  56576. function v35(name, version3, hashfunc) {
  56577. function generateUUID(value, namespace, buf, offset) {
  56578. var _namespace;
  56579. if (typeof value === "string") {
  56580. value = stringToBytes(value);
  56581. }
  56582. if (typeof namespace === "string") {
  56583. namespace = parse_default(namespace);
  56584. }
  56585. if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
  56586. throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
  56587. }
  56588. let bytes = new Uint8Array(16 + value.length);
  56589. bytes.set(namespace);
  56590. bytes.set(value, namespace.length);
  56591. bytes = hashfunc(bytes);
  56592. bytes[6] = bytes[6] & 15 | version3;
  56593. bytes[8] = bytes[8] & 63 | 128;
  56594. if (buf) {
  56595. offset = offset || 0;
  56596. for (let i4 = 0; i4 < 16; ++i4) {
  56597. buf[offset + i4] = bytes[i4];
  56598. }
  56599. return buf;
  56600. }
  56601. return unsafeStringify(bytes);
  56602. }
  56603. try {
  56604. generateUUID.name = name;
  56605. } catch (err2) {
  56606. }
  56607. generateUUID.DNS = DNS;
  56608. generateUUID.URL = URL2;
  56609. return generateUUID;
  56610. }
  56611. var DNS, URL2;
  56612. var init_v35 = __esm({
  56613. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v35.js"() {
  56614. init_stringify();
  56615. init_parse();
  56616. DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
  56617. URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
  56618. }
  56619. });
  56620. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/md5.js
  56621. function md5(bytes) {
  56622. if (Array.isArray(bytes)) {
  56623. bytes = Buffer.from(bytes);
  56624. } else if (typeof bytes === "string") {
  56625. bytes = Buffer.from(bytes, "utf8");
  56626. }
  56627. return import_crypto3.default.createHash("md5").update(bytes).digest();
  56628. }
  56629. var import_crypto3, md5_default;
  56630. var init_md5 = __esm({
  56631. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/md5.js"() {
  56632. import_crypto3 = __toESM(require("crypto"));
  56633. md5_default = md5;
  56634. }
  56635. });
  56636. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v3.js
  56637. var v3, v3_default2;
  56638. var init_v32 = __esm({
  56639. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v3.js"() {
  56640. init_v35();
  56641. init_md5();
  56642. v3 = v35("v3", 48, md5_default);
  56643. v3_default2 = v3;
  56644. }
  56645. });
  56646. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js
  56647. var import_crypto4, native_default;
  56648. var init_native = __esm({
  56649. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/native.js"() {
  56650. import_crypto4 = __toESM(require("crypto"));
  56651. native_default = {
  56652. randomUUID: import_crypto4.default.randomUUID
  56653. };
  56654. }
  56655. });
  56656. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js
  56657. function v4(options, buf, offset) {
  56658. if (native_default.randomUUID && !buf && !options) {
  56659. return native_default.randomUUID();
  56660. }
  56661. options = options || {};
  56662. const rnds = options.random || (options.rng || rng)();
  56663. rnds[6] = rnds[6] & 15 | 64;
  56664. rnds[8] = rnds[8] & 63 | 128;
  56665. if (buf) {
  56666. offset = offset || 0;
  56667. for (let i4 = 0; i4 < 16; ++i4) {
  56668. buf[offset + i4] = rnds[i4];
  56669. }
  56670. return buf;
  56671. }
  56672. return unsafeStringify(rnds);
  56673. }
  56674. var v4_default;
  56675. var init_v4 = __esm({
  56676. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v4.js"() {
  56677. init_native();
  56678. init_rng();
  56679. init_stringify();
  56680. v4_default = v4;
  56681. }
  56682. });
  56683. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/sha1.js
  56684. function sha1(bytes) {
  56685. if (Array.isArray(bytes)) {
  56686. bytes = Buffer.from(bytes);
  56687. } else if (typeof bytes === "string") {
  56688. bytes = Buffer.from(bytes, "utf8");
  56689. }
  56690. return import_crypto5.default.createHash("sha1").update(bytes).digest();
  56691. }
  56692. var import_crypto5, sha1_default;
  56693. var init_sha1 = __esm({
  56694. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/sha1.js"() {
  56695. import_crypto5 = __toESM(require("crypto"));
  56696. sha1_default = sha1;
  56697. }
  56698. });
  56699. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v5.js
  56700. var v5, v5_default;
  56701. var init_v5 = __esm({
  56702. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/v5.js"() {
  56703. init_v35();
  56704. init_sha1();
  56705. v5 = v35("v5", 80, sha1_default);
  56706. v5_default = v5;
  56707. }
  56708. });
  56709. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/nil.js
  56710. var nil_default;
  56711. var init_nil = __esm({
  56712. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/nil.js"() {
  56713. nil_default = "00000000-0000-0000-0000-000000000000";
  56714. }
  56715. });
  56716. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/version.js
  56717. function version(uuid) {
  56718. if (!validate_default(uuid)) {
  56719. throw TypeError("Invalid UUID");
  56720. }
  56721. return parseInt(uuid.slice(14, 15), 16);
  56722. }
  56723. var version_default;
  56724. var init_version = __esm({
  56725. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/version.js"() {
  56726. init_validate();
  56727. version_default = version;
  56728. }
  56729. });
  56730. // ../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js
  56731. var esm_node_exports = {};
  56732. __export(esm_node_exports, {
  56733. NIL: () => nil_default,
  56734. parse: () => parse_default,
  56735. stringify: () => stringify_default,
  56736. v1: () => v1_default,
  56737. v3: () => v3_default2,
  56738. v4: () => v4_default,
  56739. v5: () => v5_default,
  56740. validate: () => validate_default,
  56741. version: () => version_default
  56742. });
  56743. var init_esm_node = __esm({
  56744. "../node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-node/index.js"() {
  56745. init_v1();
  56746. init_v32();
  56747. init_v4();
  56748. init_v5();
  56749. init_nil();
  56750. init_version();
  56751. init_validate();
  56752. init_stringify();
  56753. init_parse();
  56754. }
  56755. });
  56756. // ../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-cjs/index.js
  56757. var require_dist_cjs33 = __commonJS({
  56758. "../node_modules/.pnpm/@smithy+service-error-classification@4.0.5/node_modules/@smithy/service-error-classification/dist-cjs/index.js"(exports2, module2) {
  56759. var __defProp3 = Object.defineProperty;
  56760. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  56761. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  56762. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  56763. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  56764. var __export2 = (target, all) => {
  56765. for (var name in all)
  56766. __defProp3(target, name, { get: all[name], enumerable: true });
  56767. };
  56768. var __copyProps3 = (to, from, except, desc) => {
  56769. if (from && typeof from === "object" || typeof from === "function") {
  56770. for (let key of __getOwnPropNames3(from))
  56771. if (!__hasOwnProp3.call(to, key) && key !== except)
  56772. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  56773. }
  56774. return to;
  56775. };
  56776. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  56777. var src_exports = {};
  56778. __export2(src_exports, {
  56779. isBrowserNetworkError: () => isBrowserNetworkError,
  56780. isClockSkewCorrectedError: () => isClockSkewCorrectedError,
  56781. isClockSkewError: () => isClockSkewError,
  56782. isRetryableByTrait: () => isRetryableByTrait,
  56783. isServerError: () => isServerError,
  56784. isThrottlingError: () => isThrottlingError,
  56785. isTransientError: () => isTransientError
  56786. });
  56787. module2.exports = __toCommonJS2(src_exports);
  56788. var CLOCK_SKEW_ERROR_CODES = [
  56789. "AuthFailure",
  56790. "InvalidSignatureException",
  56791. "RequestExpired",
  56792. "RequestInTheFuture",
  56793. "RequestTimeTooSkewed",
  56794. "SignatureDoesNotMatch"
  56795. ];
  56796. var THROTTLING_ERROR_CODES = [
  56797. "BandwidthLimitExceeded",
  56798. "EC2ThrottledException",
  56799. "LimitExceededException",
  56800. "PriorRequestNotComplete",
  56801. "ProvisionedThroughputExceededException",
  56802. "RequestLimitExceeded",
  56803. "RequestThrottled",
  56804. "RequestThrottledException",
  56805. "SlowDown",
  56806. "ThrottledException",
  56807. "Throttling",
  56808. "ThrottlingException",
  56809. "TooManyRequestsException",
  56810. "TransactionInProgressException"
  56811. // DynamoDB
  56812. ];
  56813. var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"];
  56814. var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];
  56815. var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"];
  56816. var isRetryableByTrait = /* @__PURE__ */ __name((error2) => error2.$retryable !== void 0, "isRetryableByTrait");
  56817. var isClockSkewError = /* @__PURE__ */ __name((error2) => CLOCK_SKEW_ERROR_CODES.includes(error2.name), "isClockSkewError");
  56818. var isClockSkewCorrectedError = /* @__PURE__ */ __name((error2) => {
  56819. var _a2;
  56820. return (_a2 = error2.$metadata) == null ? void 0 : _a2.clockSkewCorrected;
  56821. }, "isClockSkewCorrectedError");
  56822. var isBrowserNetworkError = /* @__PURE__ */ __name((error2) => {
  56823. const errorMessages = /* @__PURE__ */ new Set([
  56824. "Failed to fetch",
  56825. // Chrome
  56826. "NetworkError when attempting to fetch resource",
  56827. // Firefox
  56828. "The Internet connection appears to be offline",
  56829. // Safari 16
  56830. "Load failed",
  56831. // Safari 17+
  56832. "Network request failed"
  56833. // `cross-fetch`
  56834. ]);
  56835. const isValid2 = error2 && error2 instanceof TypeError;
  56836. if (!isValid2) {
  56837. return false;
  56838. }
  56839. return errorMessages.has(error2.message);
  56840. }, "isBrowserNetworkError");
  56841. var isThrottlingError = /* @__PURE__ */ __name((error2) => {
  56842. var _a2, _b;
  56843. return ((_a2 = error2.$metadata) == null ? void 0 : _a2.httpStatusCode) === 429 || THROTTLING_ERROR_CODES.includes(error2.name) || ((_b = error2.$retryable) == null ? void 0 : _b.throttling) == true;
  56844. }, "isThrottlingError");
  56845. var isTransientError = /* @__PURE__ */ __name((error2, depth = 0) => {
  56846. var _a2;
  56847. return isClockSkewCorrectedError(error2) || TRANSIENT_ERROR_CODES.includes(error2.name) || NODEJS_TIMEOUT_ERROR_CODES.includes((error2 == null ? void 0 : error2.code) || "") || TRANSIENT_ERROR_STATUS_CODES.includes(((_a2 = error2.$metadata) == null ? void 0 : _a2.httpStatusCode) || 0) || isBrowserNetworkError(error2) || error2.cause !== void 0 && depth <= 10 && isTransientError(error2.cause, depth + 1);
  56848. }, "isTransientError");
  56849. var isServerError = /* @__PURE__ */ __name((error2) => {
  56850. var _a2;
  56851. if (((_a2 = error2.$metadata) == null ? void 0 : _a2.httpStatusCode) !== void 0) {
  56852. const statusCode = error2.$metadata.httpStatusCode;
  56853. if (500 <= statusCode && statusCode <= 599 && !isTransientError(error2)) {
  56854. return true;
  56855. }
  56856. return false;
  56857. }
  56858. return false;
  56859. }, "isServerError");
  56860. }
  56861. });
  56862. // ../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-cjs/index.js
  56863. var require_dist_cjs34 = __commonJS({
  56864. "../node_modules/.pnpm/@smithy+util-retry@4.0.5/node_modules/@smithy/util-retry/dist-cjs/index.js"(exports2, module2) {
  56865. var __defProp3 = Object.defineProperty;
  56866. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  56867. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  56868. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  56869. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  56870. var __export2 = (target, all) => {
  56871. for (var name in all)
  56872. __defProp3(target, name, { get: all[name], enumerable: true });
  56873. };
  56874. var __copyProps3 = (to, from, except, desc) => {
  56875. if (from && typeof from === "object" || typeof from === "function") {
  56876. for (let key of __getOwnPropNames3(from))
  56877. if (!__hasOwnProp3.call(to, key) && key !== except)
  56878. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  56879. }
  56880. return to;
  56881. };
  56882. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  56883. var src_exports = {};
  56884. __export2(src_exports, {
  56885. AdaptiveRetryStrategy: () => AdaptiveRetryStrategy,
  56886. ConfiguredRetryStrategy: () => ConfiguredRetryStrategy,
  56887. DEFAULT_MAX_ATTEMPTS: () => DEFAULT_MAX_ATTEMPTS,
  56888. DEFAULT_RETRY_DELAY_BASE: () => DEFAULT_RETRY_DELAY_BASE,
  56889. DEFAULT_RETRY_MODE: () => DEFAULT_RETRY_MODE3,
  56890. DefaultRateLimiter: () => DefaultRateLimiter,
  56891. INITIAL_RETRY_TOKENS: () => INITIAL_RETRY_TOKENS,
  56892. INVOCATION_ID_HEADER: () => INVOCATION_ID_HEADER,
  56893. MAXIMUM_RETRY_DELAY: () => MAXIMUM_RETRY_DELAY,
  56894. NO_RETRY_INCREMENT: () => NO_RETRY_INCREMENT,
  56895. REQUEST_HEADER: () => REQUEST_HEADER,
  56896. RETRY_COST: () => RETRY_COST,
  56897. RETRY_MODES: () => RETRY_MODES,
  56898. StandardRetryStrategy: () => StandardRetryStrategy,
  56899. THROTTLING_RETRY_DELAY_BASE: () => THROTTLING_RETRY_DELAY_BASE,
  56900. TIMEOUT_RETRY_COST: () => TIMEOUT_RETRY_COST
  56901. });
  56902. module2.exports = __toCommonJS2(src_exports);
  56903. var RETRY_MODES = /* @__PURE__ */ ((RETRY_MODES2) => {
  56904. RETRY_MODES2["STANDARD"] = "standard";
  56905. RETRY_MODES2["ADAPTIVE"] = "adaptive";
  56906. return RETRY_MODES2;
  56907. })(RETRY_MODES || {});
  56908. var DEFAULT_MAX_ATTEMPTS = 3;
  56909. var DEFAULT_RETRY_MODE3 = "standard";
  56910. var import_service_error_classification = require_dist_cjs33();
  56911. var _a2;
  56912. var DefaultRateLimiter = (_a2 = class {
  56913. constructor(options) {
  56914. this.currentCapacity = 0;
  56915. this.enabled = false;
  56916. this.lastMaxRate = 0;
  56917. this.measuredTxRate = 0;
  56918. this.requestCount = 0;
  56919. this.lastTimestamp = 0;
  56920. this.timeWindow = 0;
  56921. this.beta = (options == null ? void 0 : options.beta) ?? 0.7;
  56922. this.minCapacity = (options == null ? void 0 : options.minCapacity) ?? 1;
  56923. this.minFillRate = (options == null ? void 0 : options.minFillRate) ?? 0.5;
  56924. this.scaleConstant = (options == null ? void 0 : options.scaleConstant) ?? 0.4;
  56925. this.smooth = (options == null ? void 0 : options.smooth) ?? 0.8;
  56926. const currentTimeInSeconds = this.getCurrentTimeInSeconds();
  56927. this.lastThrottleTime = currentTimeInSeconds;
  56928. this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
  56929. this.fillRate = this.minFillRate;
  56930. this.maxCapacity = this.minCapacity;
  56931. }
  56932. getCurrentTimeInSeconds() {
  56933. return Date.now() / 1e3;
  56934. }
  56935. async getSendToken() {
  56936. return this.acquireTokenBucket(1);
  56937. }
  56938. async acquireTokenBucket(amount) {
  56939. if (!this.enabled) {
  56940. return;
  56941. }
  56942. this.refillTokenBucket();
  56943. if (amount > this.currentCapacity) {
  56944. const delay = (amount - this.currentCapacity) / this.fillRate * 1e3;
  56945. await new Promise((resolve2) => _a2.setTimeoutFn(resolve2, delay));
  56946. }
  56947. this.currentCapacity = this.currentCapacity - amount;
  56948. }
  56949. refillTokenBucket() {
  56950. const timestamp = this.getCurrentTimeInSeconds();
  56951. if (!this.lastTimestamp) {
  56952. this.lastTimestamp = timestamp;
  56953. return;
  56954. }
  56955. const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate;
  56956. this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount);
  56957. this.lastTimestamp = timestamp;
  56958. }
  56959. updateClientSendingRate(response) {
  56960. let calculatedRate;
  56961. this.updateMeasuredRate();
  56962. if ((0, import_service_error_classification.isThrottlingError)(response)) {
  56963. const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate);
  56964. this.lastMaxRate = rateToUse;
  56965. this.calculateTimeWindow();
  56966. this.lastThrottleTime = this.getCurrentTimeInSeconds();
  56967. calculatedRate = this.cubicThrottle(rateToUse);
  56968. this.enableTokenBucket();
  56969. } else {
  56970. this.calculateTimeWindow();
  56971. calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds());
  56972. }
  56973. const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate);
  56974. this.updateTokenBucketRate(newRate);
  56975. }
  56976. calculateTimeWindow() {
  56977. this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3));
  56978. }
  56979. cubicThrottle(rateToUse) {
  56980. return this.getPrecise(rateToUse * this.beta);
  56981. }
  56982. cubicSuccess(timestamp) {
  56983. return this.getPrecise(
  56984. this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate
  56985. );
  56986. }
  56987. enableTokenBucket() {
  56988. this.enabled = true;
  56989. }
  56990. updateTokenBucketRate(newRate) {
  56991. this.refillTokenBucket();
  56992. this.fillRate = Math.max(newRate, this.minFillRate);
  56993. this.maxCapacity = Math.max(newRate, this.minCapacity);
  56994. this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity);
  56995. }
  56996. updateMeasuredRate() {
  56997. const t4 = this.getCurrentTimeInSeconds();
  56998. const timeBucket = Math.floor(t4 * 2) / 2;
  56999. this.requestCount++;
  57000. if (timeBucket > this.lastTxRateBucket) {
  57001. const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket);
  57002. this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth));
  57003. this.requestCount = 0;
  57004. this.lastTxRateBucket = timeBucket;
  57005. }
  57006. }
  57007. getPrecise(num) {
  57008. return parseFloat(num.toFixed(8));
  57009. }
  57010. }, __name(_a2, "DefaultRateLimiter"), _a2.setTimeoutFn = setTimeout, _a2);
  57011. var DEFAULT_RETRY_DELAY_BASE = 100;
  57012. var MAXIMUM_RETRY_DELAY = 20 * 1e3;
  57013. var THROTTLING_RETRY_DELAY_BASE = 500;
  57014. var INITIAL_RETRY_TOKENS = 500;
  57015. var RETRY_COST = 5;
  57016. var TIMEOUT_RETRY_COST = 10;
  57017. var NO_RETRY_INCREMENT = 1;
  57018. var INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
  57019. var REQUEST_HEADER = "amz-sdk-request";
  57020. var getDefaultRetryBackoffStrategy = /* @__PURE__ */ __name(() => {
  57021. let delayBase = DEFAULT_RETRY_DELAY_BASE;
  57022. const computeNextBackoffDelay = /* @__PURE__ */ __name((attempts) => {
  57023. return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
  57024. }, "computeNextBackoffDelay");
  57025. const setDelayBase = /* @__PURE__ */ __name((delay) => {
  57026. delayBase = delay;
  57027. }, "setDelayBase");
  57028. return {
  57029. computeNextBackoffDelay,
  57030. setDelayBase
  57031. };
  57032. }, "getDefaultRetryBackoffStrategy");
  57033. var createDefaultRetryToken = /* @__PURE__ */ __name(({
  57034. retryDelay,
  57035. retryCount,
  57036. retryCost
  57037. }) => {
  57038. const getRetryCount = /* @__PURE__ */ __name(() => retryCount, "getRetryCount");
  57039. const getRetryDelay = /* @__PURE__ */ __name(() => Math.min(MAXIMUM_RETRY_DELAY, retryDelay), "getRetryDelay");
  57040. const getRetryCost = /* @__PURE__ */ __name(() => retryCost, "getRetryCost");
  57041. return {
  57042. getRetryCount,
  57043. getRetryDelay,
  57044. getRetryCost
  57045. };
  57046. }, "createDefaultRetryToken");
  57047. var _a3;
  57048. var StandardRetryStrategy = (_a3 = class {
  57049. constructor(maxAttempts) {
  57050. this.maxAttempts = maxAttempts;
  57051. this.mode = "standard";
  57052. this.capacity = INITIAL_RETRY_TOKENS;
  57053. this.retryBackoffStrategy = getDefaultRetryBackoffStrategy();
  57054. this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
  57055. }
  57056. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  57057. async acquireInitialRetryToken(retryTokenScope) {
  57058. return createDefaultRetryToken({
  57059. retryDelay: DEFAULT_RETRY_DELAY_BASE,
  57060. retryCount: 0
  57061. });
  57062. }
  57063. async refreshRetryTokenForRetry(token, errorInfo) {
  57064. const maxAttempts = await this.getMaxAttempts();
  57065. if (this.shouldRetry(token, errorInfo, maxAttempts)) {
  57066. const errorType = errorInfo.errorType;
  57067. this.retryBackoffStrategy.setDelayBase(
  57068. errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE
  57069. );
  57070. const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());
  57071. const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType;
  57072. const capacityCost = this.getCapacityCost(errorType);
  57073. this.capacity -= capacityCost;
  57074. return createDefaultRetryToken({
  57075. retryDelay,
  57076. retryCount: token.getRetryCount() + 1,
  57077. retryCost: capacityCost
  57078. });
  57079. }
  57080. throw new Error("No retry token available");
  57081. }
  57082. recordSuccess(token) {
  57083. this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT));
  57084. }
  57085. /**
  57086. * @returns the current available retry capacity.
  57087. *
  57088. * This number decreases when retries are executed and refills when requests or retries succeed.
  57089. */
  57090. getCapacity() {
  57091. return this.capacity;
  57092. }
  57093. async getMaxAttempts() {
  57094. try {
  57095. return await this.maxAttemptsProvider();
  57096. } catch (error2) {
  57097. console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);
  57098. return DEFAULT_MAX_ATTEMPTS;
  57099. }
  57100. }
  57101. shouldRetry(tokenToRenew, errorInfo, maxAttempts) {
  57102. const attempts = tokenToRenew.getRetryCount() + 1;
  57103. return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType);
  57104. }
  57105. getCapacityCost(errorType) {
  57106. return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST;
  57107. }
  57108. isRetryableError(errorType) {
  57109. return errorType === "THROTTLING" || errorType === "TRANSIENT";
  57110. }
  57111. }, __name(_a3, "StandardRetryStrategy"), _a3);
  57112. var _a4;
  57113. var AdaptiveRetryStrategy = (_a4 = class {
  57114. constructor(maxAttemptsProvider, options) {
  57115. this.maxAttemptsProvider = maxAttemptsProvider;
  57116. this.mode = "adaptive";
  57117. const { rateLimiter } = options ?? {};
  57118. this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();
  57119. this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);
  57120. }
  57121. async acquireInitialRetryToken(retryTokenScope) {
  57122. await this.rateLimiter.getSendToken();
  57123. return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);
  57124. }
  57125. async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
  57126. this.rateLimiter.updateClientSendingRate(errorInfo);
  57127. return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
  57128. }
  57129. recordSuccess(token) {
  57130. this.rateLimiter.updateClientSendingRate({});
  57131. this.standardRetryStrategy.recordSuccess(token);
  57132. }
  57133. }, __name(_a4, "AdaptiveRetryStrategy"), _a4);
  57134. var _a5;
  57135. var ConfiguredRetryStrategy = (_a5 = class extends StandardRetryStrategy {
  57136. /**
  57137. * @param maxAttempts - the maximum number of retry attempts allowed.
  57138. * e.g., if set to 3, then 4 total requests are possible.
  57139. * @param computeNextBackoffDelay - a millisecond delay for each retry or a function that takes the retry attempt
  57140. * and returns the delay.
  57141. *
  57142. * @example exponential backoff.
  57143. * ```js
  57144. * new Client({
  57145. * retryStrategy: new ConfiguredRetryStrategy(3, (attempt) => attempt ** 2)
  57146. * });
  57147. * ```
  57148. * @example constant delay.
  57149. * ```js
  57150. * new Client({
  57151. * retryStrategy: new ConfiguredRetryStrategy(3, 2000)
  57152. * });
  57153. * ```
  57154. */
  57155. constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) {
  57156. super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts);
  57157. if (typeof computeNextBackoffDelay === "number") {
  57158. this.computeNextBackoffDelay = () => computeNextBackoffDelay;
  57159. } else {
  57160. this.computeNextBackoffDelay = computeNextBackoffDelay;
  57161. }
  57162. }
  57163. async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
  57164. const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
  57165. token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount());
  57166. return token;
  57167. }
  57168. }, __name(_a5, "ConfiguredRetryStrategy"), _a5);
  57169. }
  57170. });
  57171. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js
  57172. var require_isStreamingPayload = __commonJS({
  57173. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js"(exports2) {
  57174. "use strict";
  57175. Object.defineProperty(exports2, "__esModule", { value: true });
  57176. exports2.isStreamingPayload = void 0;
  57177. var stream_1 = require("stream");
  57178. var isStreamingPayload = (request) => (request === null || request === void 0 ? void 0 : request.body) instanceof stream_1.Readable || typeof ReadableStream !== "undefined" && (request === null || request === void 0 ? void 0 : request.body) instanceof ReadableStream;
  57179. exports2.isStreamingPayload = isStreamingPayload;
  57180. }
  57181. });
  57182. // ../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-cjs/index.js
  57183. var require_dist_cjs35 = __commonJS({
  57184. "../node_modules/.pnpm/@smithy+middleware-retry@4.1.10/node_modules/@smithy/middleware-retry/dist-cjs/index.js"(exports2, module2) {
  57185. var __defProp3 = Object.defineProperty;
  57186. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  57187. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  57188. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  57189. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  57190. var __export2 = (target, all) => {
  57191. for (var name in all)
  57192. __defProp3(target, name, { get: all[name], enumerable: true });
  57193. };
  57194. var __copyProps3 = (to, from, except, desc) => {
  57195. if (from && typeof from === "object" || typeof from === "function") {
  57196. for (let key of __getOwnPropNames3(from))
  57197. if (!__hasOwnProp3.call(to, key) && key !== except)
  57198. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  57199. }
  57200. return to;
  57201. };
  57202. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  57203. var src_exports = {};
  57204. __export2(src_exports, {
  57205. AdaptiveRetryStrategy: () => AdaptiveRetryStrategy,
  57206. CONFIG_MAX_ATTEMPTS: () => CONFIG_MAX_ATTEMPTS,
  57207. CONFIG_RETRY_MODE: () => CONFIG_RETRY_MODE,
  57208. ENV_MAX_ATTEMPTS: () => ENV_MAX_ATTEMPTS,
  57209. ENV_RETRY_MODE: () => ENV_RETRY_MODE,
  57210. NODE_MAX_ATTEMPT_CONFIG_OPTIONS: () => NODE_MAX_ATTEMPT_CONFIG_OPTIONS3,
  57211. NODE_RETRY_MODE_CONFIG_OPTIONS: () => NODE_RETRY_MODE_CONFIG_OPTIONS3,
  57212. StandardRetryStrategy: () => StandardRetryStrategy,
  57213. defaultDelayDecider: () => defaultDelayDecider,
  57214. defaultRetryDecider: () => defaultRetryDecider,
  57215. getOmitRetryHeadersPlugin: () => getOmitRetryHeadersPlugin,
  57216. getRetryAfterHint: () => getRetryAfterHint,
  57217. getRetryPlugin: () => getRetryPlugin3,
  57218. omitRetryHeadersMiddleware: () => omitRetryHeadersMiddleware,
  57219. omitRetryHeadersMiddlewareOptions: () => omitRetryHeadersMiddlewareOptions,
  57220. resolveRetryConfig: () => resolveRetryConfig3,
  57221. retryMiddleware: () => retryMiddleware,
  57222. retryMiddlewareOptions: () => retryMiddlewareOptions
  57223. });
  57224. module2.exports = __toCommonJS2(src_exports);
  57225. var import_protocol_http15 = require_dist_cjs2();
  57226. var import_uuid = (init_esm_node(), __toCommonJS(esm_node_exports));
  57227. var import_util_retry3 = require_dist_cjs34();
  57228. var getDefaultRetryQuota = /* @__PURE__ */ __name((initialRetryTokens, options) => {
  57229. const MAX_CAPACITY = initialRetryTokens;
  57230. const noRetryIncrement = (options == null ? void 0 : options.noRetryIncrement) ?? import_util_retry3.NO_RETRY_INCREMENT;
  57231. const retryCost = (options == null ? void 0 : options.retryCost) ?? import_util_retry3.RETRY_COST;
  57232. const timeoutRetryCost = (options == null ? void 0 : options.timeoutRetryCost) ?? import_util_retry3.TIMEOUT_RETRY_COST;
  57233. let availableCapacity = initialRetryTokens;
  57234. const getCapacityAmount = /* @__PURE__ */ __name((error2) => error2.name === "TimeoutError" ? timeoutRetryCost : retryCost, "getCapacityAmount");
  57235. const hasRetryTokens = /* @__PURE__ */ __name((error2) => getCapacityAmount(error2) <= availableCapacity, "hasRetryTokens");
  57236. const retrieveRetryTokens = /* @__PURE__ */ __name((error2) => {
  57237. if (!hasRetryTokens(error2)) {
  57238. throw new Error("No retry token available");
  57239. }
  57240. const capacityAmount = getCapacityAmount(error2);
  57241. availableCapacity -= capacityAmount;
  57242. return capacityAmount;
  57243. }, "retrieveRetryTokens");
  57244. const releaseRetryTokens = /* @__PURE__ */ __name((capacityReleaseAmount) => {
  57245. availableCapacity += capacityReleaseAmount ?? noRetryIncrement;
  57246. availableCapacity = Math.min(availableCapacity, MAX_CAPACITY);
  57247. }, "releaseRetryTokens");
  57248. return Object.freeze({
  57249. hasRetryTokens,
  57250. retrieveRetryTokens,
  57251. releaseRetryTokens
  57252. });
  57253. }, "getDefaultRetryQuota");
  57254. var defaultDelayDecider = /* @__PURE__ */ __name((delayBase, attempts) => Math.floor(Math.min(import_util_retry3.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)), "defaultDelayDecider");
  57255. var import_service_error_classification = require_dist_cjs33();
  57256. var defaultRetryDecider = /* @__PURE__ */ __name((error2) => {
  57257. if (!error2) {
  57258. return false;
  57259. }
  57260. return (0, import_service_error_classification.isRetryableByTrait)(error2) || (0, import_service_error_classification.isClockSkewError)(error2) || (0, import_service_error_classification.isThrottlingError)(error2) || (0, import_service_error_classification.isTransientError)(error2);
  57261. }, "defaultRetryDecider");
  57262. var asSdkError = /* @__PURE__ */ __name((error2) => {
  57263. if (error2 instanceof Error)
  57264. return error2;
  57265. if (error2 instanceof Object)
  57266. return Object.assign(new Error(), error2);
  57267. if (typeof error2 === "string")
  57268. return new Error(error2);
  57269. return new Error(`AWS SDK error wrapper for ${error2}`);
  57270. }, "asSdkError");
  57271. var _a2;
  57272. var StandardRetryStrategy = (_a2 = class {
  57273. constructor(maxAttemptsProvider, options) {
  57274. this.maxAttemptsProvider = maxAttemptsProvider;
  57275. this.mode = import_util_retry3.RETRY_MODES.STANDARD;
  57276. this.retryDecider = (options == null ? void 0 : options.retryDecider) ?? defaultRetryDecider;
  57277. this.delayDecider = (options == null ? void 0 : options.delayDecider) ?? defaultDelayDecider;
  57278. this.retryQuota = (options == null ? void 0 : options.retryQuota) ?? getDefaultRetryQuota(import_util_retry3.INITIAL_RETRY_TOKENS);
  57279. }
  57280. shouldRetry(error2, attempts, maxAttempts) {
  57281. return attempts < maxAttempts && this.retryDecider(error2) && this.retryQuota.hasRetryTokens(error2);
  57282. }
  57283. async getMaxAttempts() {
  57284. let maxAttempts;
  57285. try {
  57286. maxAttempts = await this.maxAttemptsProvider();
  57287. } catch (error2) {
  57288. maxAttempts = import_util_retry3.DEFAULT_MAX_ATTEMPTS;
  57289. }
  57290. return maxAttempts;
  57291. }
  57292. async retry(next, args, options) {
  57293. let retryTokenAmount;
  57294. let attempts = 0;
  57295. let totalDelay = 0;
  57296. const maxAttempts = await this.getMaxAttempts();
  57297. const { request } = args;
  57298. if (import_protocol_http15.HttpRequest.isInstance(request)) {
  57299. request.headers[import_util_retry3.INVOCATION_ID_HEADER] = (0, import_uuid.v4)();
  57300. }
  57301. while (true) {
  57302. try {
  57303. if (import_protocol_http15.HttpRequest.isInstance(request)) {
  57304. request.headers[import_util_retry3.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
  57305. }
  57306. if (options == null ? void 0 : options.beforeRequest) {
  57307. await options.beforeRequest();
  57308. }
  57309. const { response, output } = await next(args);
  57310. if (options == null ? void 0 : options.afterRequest) {
  57311. options.afterRequest(response);
  57312. }
  57313. this.retryQuota.releaseRetryTokens(retryTokenAmount);
  57314. output.$metadata.attempts = attempts + 1;
  57315. output.$metadata.totalRetryDelay = totalDelay;
  57316. return { response, output };
  57317. } catch (e4) {
  57318. const err2 = asSdkError(e4);
  57319. attempts++;
  57320. if (this.shouldRetry(err2, attempts, maxAttempts)) {
  57321. retryTokenAmount = this.retryQuota.retrieveRetryTokens(err2);
  57322. const delayFromDecider = this.delayDecider(
  57323. (0, import_service_error_classification.isThrottlingError)(err2) ? import_util_retry3.THROTTLING_RETRY_DELAY_BASE : import_util_retry3.DEFAULT_RETRY_DELAY_BASE,
  57324. attempts
  57325. );
  57326. const delayFromResponse = getDelayFromRetryAfterHeader(err2.$response);
  57327. const delay = Math.max(delayFromResponse || 0, delayFromDecider);
  57328. totalDelay += delay;
  57329. await new Promise((resolve2) => setTimeout(resolve2, delay));
  57330. continue;
  57331. }
  57332. if (!err2.$metadata) {
  57333. err2.$metadata = {};
  57334. }
  57335. err2.$metadata.attempts = attempts;
  57336. err2.$metadata.totalRetryDelay = totalDelay;
  57337. throw err2;
  57338. }
  57339. }
  57340. }
  57341. }, __name(_a2, "StandardRetryStrategy"), _a2);
  57342. var getDelayFromRetryAfterHeader = /* @__PURE__ */ __name((response) => {
  57343. if (!import_protocol_http15.HttpResponse.isInstance(response))
  57344. return;
  57345. const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after");
  57346. if (!retryAfterHeaderName)
  57347. return;
  57348. const retryAfter = response.headers[retryAfterHeaderName];
  57349. const retryAfterSeconds = Number(retryAfter);
  57350. if (!Number.isNaN(retryAfterSeconds))
  57351. return retryAfterSeconds * 1e3;
  57352. const retryAfterDate = new Date(retryAfter);
  57353. return retryAfterDate.getTime() - Date.now();
  57354. }, "getDelayFromRetryAfterHeader");
  57355. var _a3;
  57356. var AdaptiveRetryStrategy = (_a3 = class extends StandardRetryStrategy {
  57357. constructor(maxAttemptsProvider, options) {
  57358. const { rateLimiter, ...superOptions } = options ?? {};
  57359. super(maxAttemptsProvider, superOptions);
  57360. this.rateLimiter = rateLimiter ?? new import_util_retry3.DefaultRateLimiter();
  57361. this.mode = import_util_retry3.RETRY_MODES.ADAPTIVE;
  57362. }
  57363. async retry(next, args) {
  57364. return super.retry(next, args, {
  57365. beforeRequest: async () => {
  57366. return this.rateLimiter.getSendToken();
  57367. },
  57368. afterRequest: (response) => {
  57369. this.rateLimiter.updateClientSendingRate(response);
  57370. }
  57371. });
  57372. }
  57373. }, __name(_a3, "AdaptiveRetryStrategy"), _a3);
  57374. var import_util_middleware7 = require_dist_cjs6();
  57375. var ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS";
  57376. var CONFIG_MAX_ATTEMPTS = "max_attempts";
  57377. var NODE_MAX_ATTEMPT_CONFIG_OPTIONS3 = {
  57378. environmentVariableSelector: (env3) => {
  57379. const value = env3[ENV_MAX_ATTEMPTS];
  57380. if (!value)
  57381. return void 0;
  57382. const maxAttempt = parseInt(value);
  57383. if (Number.isNaN(maxAttempt)) {
  57384. throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`);
  57385. }
  57386. return maxAttempt;
  57387. },
  57388. configFileSelector: (profile) => {
  57389. const value = profile[CONFIG_MAX_ATTEMPTS];
  57390. if (!value)
  57391. return void 0;
  57392. const maxAttempt = parseInt(value);
  57393. if (Number.isNaN(maxAttempt)) {
  57394. throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`);
  57395. }
  57396. return maxAttempt;
  57397. },
  57398. default: import_util_retry3.DEFAULT_MAX_ATTEMPTS
  57399. };
  57400. var resolveRetryConfig3 = /* @__PURE__ */ __name((input) => {
  57401. const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input;
  57402. const maxAttempts = (0, import_util_middleware7.normalizeProvider)(_maxAttempts ?? import_util_retry3.DEFAULT_MAX_ATTEMPTS);
  57403. return Object.assign(input, {
  57404. maxAttempts,
  57405. retryStrategy: async () => {
  57406. if (retryStrategy) {
  57407. return retryStrategy;
  57408. }
  57409. const retryMode = await (0, import_util_middleware7.normalizeProvider)(_retryMode)();
  57410. if (retryMode === import_util_retry3.RETRY_MODES.ADAPTIVE) {
  57411. return new import_util_retry3.AdaptiveRetryStrategy(maxAttempts);
  57412. }
  57413. return new import_util_retry3.StandardRetryStrategy(maxAttempts);
  57414. }
  57415. });
  57416. }, "resolveRetryConfig");
  57417. var ENV_RETRY_MODE = "AWS_RETRY_MODE";
  57418. var CONFIG_RETRY_MODE = "retry_mode";
  57419. var NODE_RETRY_MODE_CONFIG_OPTIONS3 = {
  57420. environmentVariableSelector: (env3) => env3[ENV_RETRY_MODE],
  57421. configFileSelector: (profile) => profile[CONFIG_RETRY_MODE],
  57422. default: import_util_retry3.DEFAULT_RETRY_MODE
  57423. };
  57424. var omitRetryHeadersMiddleware = /* @__PURE__ */ __name(() => (next) => async (args) => {
  57425. const { request } = args;
  57426. if (import_protocol_http15.HttpRequest.isInstance(request)) {
  57427. delete request.headers[import_util_retry3.INVOCATION_ID_HEADER];
  57428. delete request.headers[import_util_retry3.REQUEST_HEADER];
  57429. }
  57430. return next(args);
  57431. }, "omitRetryHeadersMiddleware");
  57432. var omitRetryHeadersMiddlewareOptions = {
  57433. name: "omitRetryHeadersMiddleware",
  57434. tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"],
  57435. relation: "before",
  57436. toMiddleware: "awsAuthMiddleware",
  57437. override: true
  57438. };
  57439. var getOmitRetryHeadersPlugin = /* @__PURE__ */ __name((options) => ({
  57440. applyToStack: (clientStack) => {
  57441. clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions);
  57442. }
  57443. }), "getOmitRetryHeadersPlugin");
  57444. var import_smithy_client25 = require_dist_cjs23();
  57445. var import_isStreamingPayload = require_isStreamingPayload();
  57446. var retryMiddleware = /* @__PURE__ */ __name((options) => (next, context) => async (args) => {
  57447. var _a4;
  57448. let retryStrategy = await options.retryStrategy();
  57449. const maxAttempts = await options.maxAttempts();
  57450. if (isRetryStrategyV2(retryStrategy)) {
  57451. retryStrategy = retryStrategy;
  57452. let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]);
  57453. let lastError = new Error();
  57454. let attempts = 0;
  57455. let totalRetryDelay = 0;
  57456. const { request } = args;
  57457. const isRequest2 = import_protocol_http15.HttpRequest.isInstance(request);
  57458. if (isRequest2) {
  57459. request.headers[import_util_retry3.INVOCATION_ID_HEADER] = (0, import_uuid.v4)();
  57460. }
  57461. while (true) {
  57462. try {
  57463. if (isRequest2) {
  57464. request.headers[import_util_retry3.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
  57465. }
  57466. const { response, output } = await next(args);
  57467. retryStrategy.recordSuccess(retryToken);
  57468. output.$metadata.attempts = attempts + 1;
  57469. output.$metadata.totalRetryDelay = totalRetryDelay;
  57470. return { response, output };
  57471. } catch (e4) {
  57472. const retryErrorInfo = getRetryErrorInfo(e4);
  57473. lastError = asSdkError(e4);
  57474. if (isRequest2 && (0, import_isStreamingPayload.isStreamingPayload)(request)) {
  57475. (_a4 = context.logger instanceof import_smithy_client25.NoOpLogger ? console : context.logger) == null ? void 0 : _a4.warn(
  57476. "An error was encountered in a non-retryable streaming request."
  57477. );
  57478. throw lastError;
  57479. }
  57480. try {
  57481. retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo);
  57482. } catch (refreshError) {
  57483. if (!lastError.$metadata) {
  57484. lastError.$metadata = {};
  57485. }
  57486. lastError.$metadata.attempts = attempts + 1;
  57487. lastError.$metadata.totalRetryDelay = totalRetryDelay;
  57488. throw lastError;
  57489. }
  57490. attempts = retryToken.getRetryCount();
  57491. const delay = retryToken.getRetryDelay();
  57492. totalRetryDelay += delay;
  57493. await new Promise((resolve2) => setTimeout(resolve2, delay));
  57494. }
  57495. }
  57496. } else {
  57497. retryStrategy = retryStrategy;
  57498. if (retryStrategy == null ? void 0 : retryStrategy.mode)
  57499. context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]];
  57500. return retryStrategy.retry(next, args);
  57501. }
  57502. }, "retryMiddleware");
  57503. var isRetryStrategyV2 = /* @__PURE__ */ __name((retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined", "isRetryStrategyV2");
  57504. var getRetryErrorInfo = /* @__PURE__ */ __name((error2) => {
  57505. const errorInfo = {
  57506. error: error2,
  57507. errorType: getRetryErrorType(error2)
  57508. };
  57509. const retryAfterHint = getRetryAfterHint(error2.$response);
  57510. if (retryAfterHint) {
  57511. errorInfo.retryAfterHint = retryAfterHint;
  57512. }
  57513. return errorInfo;
  57514. }, "getRetryErrorInfo");
  57515. var getRetryErrorType = /* @__PURE__ */ __name((error2) => {
  57516. if ((0, import_service_error_classification.isThrottlingError)(error2))
  57517. return "THROTTLING";
  57518. if ((0, import_service_error_classification.isTransientError)(error2))
  57519. return "TRANSIENT";
  57520. if ((0, import_service_error_classification.isServerError)(error2))
  57521. return "SERVER_ERROR";
  57522. return "CLIENT_ERROR";
  57523. }, "getRetryErrorType");
  57524. var retryMiddlewareOptions = {
  57525. name: "retryMiddleware",
  57526. tags: ["RETRY"],
  57527. step: "finalizeRequest",
  57528. priority: "high",
  57529. override: true
  57530. };
  57531. var getRetryPlugin3 = /* @__PURE__ */ __name((options) => ({
  57532. applyToStack: (clientStack) => {
  57533. clientStack.add(retryMiddleware(options), retryMiddlewareOptions);
  57534. }
  57535. }), "getRetryPlugin");
  57536. var getRetryAfterHint = /* @__PURE__ */ __name((response) => {
  57537. if (!import_protocol_http15.HttpResponse.isInstance(response))
  57538. return;
  57539. const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after");
  57540. if (!retryAfterHeaderName)
  57541. return;
  57542. const retryAfter = response.headers[retryAfterHeaderName];
  57543. const retryAfterSeconds = Number(retryAfter);
  57544. if (!Number.isNaN(retryAfterSeconds))
  57545. return new Date(retryAfterSeconds * 1e3);
  57546. const retryAfterDate = new Date(retryAfter);
  57547. return retryAfterDate;
  57548. }, "getRetryAfterHint");
  57549. }
  57550. });
  57551. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/auth/httpAuthSchemeProvider.js
  57552. var require_httpAuthSchemeProvider = __commonJS({
  57553. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/auth/httpAuthSchemeProvider.js"(exports2) {
  57554. "use strict";
  57555. Object.defineProperty(exports2, "__esModule", { value: true });
  57556. exports2.resolveHttpAuthSchemeConfig = exports2.defaultRDSDataHttpAuthSchemeProvider = exports2.defaultRDSDataHttpAuthSchemeParametersProvider = void 0;
  57557. var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
  57558. var util_middleware_1 = require_dist_cjs6();
  57559. var defaultRDSDataHttpAuthSchemeParametersProvider = async (config, context, input) => {
  57560. return {
  57561. operation: (0, util_middleware_1.getSmithyContext)(context).operation,
  57562. region: await (0, util_middleware_1.normalizeProvider)(config.region)() || (() => {
  57563. throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
  57564. })()
  57565. };
  57566. };
  57567. exports2.defaultRDSDataHttpAuthSchemeParametersProvider = defaultRDSDataHttpAuthSchemeParametersProvider;
  57568. function createAwsAuthSigv4HttpAuthOption3(authParameters) {
  57569. return {
  57570. schemeId: "aws.auth#sigv4",
  57571. signingProperties: {
  57572. name: "rds-data",
  57573. region: authParameters.region
  57574. },
  57575. propertiesExtractor: (config, context) => ({
  57576. signingProperties: {
  57577. config,
  57578. context
  57579. }
  57580. })
  57581. };
  57582. }
  57583. var defaultRDSDataHttpAuthSchemeProvider = (authParameters) => {
  57584. const options = [];
  57585. switch (authParameters.operation) {
  57586. default: {
  57587. options.push(createAwsAuthSigv4HttpAuthOption3(authParameters));
  57588. }
  57589. }
  57590. return options;
  57591. };
  57592. exports2.defaultRDSDataHttpAuthSchemeProvider = defaultRDSDataHttpAuthSchemeProvider;
  57593. var resolveHttpAuthSchemeConfig3 = (config) => {
  57594. const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config);
  57595. return Object.assign(config_0, {
  57596. authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? [])
  57597. });
  57598. };
  57599. exports2.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig3;
  57600. }
  57601. });
  57602. // ../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs
  57603. var tslib_es6_exports = {};
  57604. __export(tslib_es6_exports, {
  57605. __addDisposableResource: () => __addDisposableResource,
  57606. __assign: () => __assign,
  57607. __asyncDelegator: () => __asyncDelegator,
  57608. __asyncGenerator: () => __asyncGenerator,
  57609. __asyncValues: () => __asyncValues,
  57610. __await: () => __await,
  57611. __awaiter: () => __awaiter,
  57612. __classPrivateFieldGet: () => __classPrivateFieldGet,
  57613. __classPrivateFieldIn: () => __classPrivateFieldIn,
  57614. __classPrivateFieldSet: () => __classPrivateFieldSet,
  57615. __createBinding: () => __createBinding,
  57616. __decorate: () => __decorate,
  57617. __disposeResources: () => __disposeResources,
  57618. __esDecorate: () => __esDecorate,
  57619. __exportStar: () => __exportStar,
  57620. __extends: () => __extends,
  57621. __generator: () => __generator,
  57622. __importDefault: () => __importDefault,
  57623. __importStar: () => __importStar,
  57624. __makeTemplateObject: () => __makeTemplateObject,
  57625. __metadata: () => __metadata,
  57626. __param: () => __param,
  57627. __propKey: () => __propKey,
  57628. __read: () => __read,
  57629. __rest: () => __rest,
  57630. __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension,
  57631. __runInitializers: () => __runInitializers,
  57632. __setFunctionName: () => __setFunctionName,
  57633. __spread: () => __spread,
  57634. __spreadArray: () => __spreadArray,
  57635. __spreadArrays: () => __spreadArrays,
  57636. __values: () => __values,
  57637. default: () => tslib_es6_default
  57638. });
  57639. function __extends(d3, b3) {
  57640. if (typeof b3 !== "function" && b3 !== null)
  57641. throw new TypeError("Class extends value " + String(b3) + " is not a constructor or null");
  57642. extendStatics(d3, b3);
  57643. function __() {
  57644. this.constructor = d3;
  57645. }
  57646. d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __());
  57647. }
  57648. function __rest(s4, e4) {
  57649. var t4 = {};
  57650. for (var p3 in s4) if (Object.prototype.hasOwnProperty.call(s4, p3) && e4.indexOf(p3) < 0)
  57651. t4[p3] = s4[p3];
  57652. if (s4 != null && typeof Object.getOwnPropertySymbols === "function")
  57653. for (var i4 = 0, p3 = Object.getOwnPropertySymbols(s4); i4 < p3.length; i4++) {
  57654. if (e4.indexOf(p3[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s4, p3[i4]))
  57655. t4[p3[i4]] = s4[p3[i4]];
  57656. }
  57657. return t4;
  57658. }
  57659. function __decorate(decorators, target, key, desc) {
  57660. var c3 = arguments.length, r4 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3;
  57661. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r4 = Reflect.decorate(decorators, target, key, desc);
  57662. else for (var i4 = decorators.length - 1; i4 >= 0; i4--) if (d3 = decorators[i4]) r4 = (c3 < 3 ? d3(r4) : c3 > 3 ? d3(target, key, r4) : d3(target, key)) || r4;
  57663. return c3 > 3 && r4 && Object.defineProperty(target, key, r4), r4;
  57664. }
  57665. function __param(paramIndex, decorator) {
  57666. return function(target, key) {
  57667. decorator(target, key, paramIndex);
  57668. };
  57669. }
  57670. function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  57671. function accept(f5) {
  57672. if (f5 !== void 0 && typeof f5 !== "function") throw new TypeError("Function expected");
  57673. return f5;
  57674. }
  57675. var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  57676. var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  57677. var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  57678. var _3, done = false;
  57679. for (var i4 = decorators.length - 1; i4 >= 0; i4--) {
  57680. var context = {};
  57681. for (var p3 in contextIn) context[p3] = p3 === "access" ? {} : contextIn[p3];
  57682. for (var p3 in contextIn.access) context.access[p3] = contextIn.access[p3];
  57683. context.addInitializer = function(f5) {
  57684. if (done) throw new TypeError("Cannot add initializers after decoration has completed");
  57685. extraInitializers.push(accept(f5 || null));
  57686. };
  57687. var result = (0, decorators[i4])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
  57688. if (kind === "accessor") {
  57689. if (result === void 0) continue;
  57690. if (result === null || typeof result !== "object") throw new TypeError("Object expected");
  57691. if (_3 = accept(result.get)) descriptor.get = _3;
  57692. if (_3 = accept(result.set)) descriptor.set = _3;
  57693. if (_3 = accept(result.init)) initializers.unshift(_3);
  57694. } else if (_3 = accept(result)) {
  57695. if (kind === "field") initializers.unshift(_3);
  57696. else descriptor[key] = _3;
  57697. }
  57698. }
  57699. if (target) Object.defineProperty(target, contextIn.name, descriptor);
  57700. done = true;
  57701. }
  57702. function __runInitializers(thisArg, initializers, value) {
  57703. var useValue = arguments.length > 2;
  57704. for (var i4 = 0; i4 < initializers.length; i4++) {
  57705. value = useValue ? initializers[i4].call(thisArg, value) : initializers[i4].call(thisArg);
  57706. }
  57707. return useValue ? value : void 0;
  57708. }
  57709. function __propKey(x4) {
  57710. return typeof x4 === "symbol" ? x4 : "".concat(x4);
  57711. }
  57712. function __setFunctionName(f5, name, prefix2) {
  57713. if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
  57714. return Object.defineProperty(f5, "name", { configurable: true, value: prefix2 ? "".concat(prefix2, " ", name) : name });
  57715. }
  57716. function __metadata(metadataKey, metadataValue) {
  57717. if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
  57718. }
  57719. function __awaiter(thisArg, _arguments, P, generator) {
  57720. function adopt(value) {
  57721. return value instanceof P ? value : new P(function(resolve2) {
  57722. resolve2(value);
  57723. });
  57724. }
  57725. return new (P || (P = Promise))(function(resolve2, reject) {
  57726. function fulfilled(value) {
  57727. try {
  57728. step(generator.next(value));
  57729. } catch (e4) {
  57730. reject(e4);
  57731. }
  57732. }
  57733. function rejected(value) {
  57734. try {
  57735. step(generator["throw"](value));
  57736. } catch (e4) {
  57737. reject(e4);
  57738. }
  57739. }
  57740. function step(result) {
  57741. result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
  57742. }
  57743. step((generator = generator.apply(thisArg, _arguments || [])).next());
  57744. });
  57745. }
  57746. function __generator(thisArg, body) {
  57747. var _3 = { label: 0, sent: function() {
  57748. if (t4[0] & 1) throw t4[1];
  57749. return t4[1];
  57750. }, trys: [], ops: [] }, f5, y2, t4, g3 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  57751. return g3.next = verb(0), g3["throw"] = verb(1), g3["return"] = verb(2), typeof Symbol === "function" && (g3[Symbol.iterator] = function() {
  57752. return this;
  57753. }), g3;
  57754. function verb(n3) {
  57755. return function(v6) {
  57756. return step([n3, v6]);
  57757. };
  57758. }
  57759. function step(op) {
  57760. if (f5) throw new TypeError("Generator is already executing.");
  57761. while (g3 && (g3 = 0, op[0] && (_3 = 0)), _3) try {
  57762. if (f5 = 1, y2 && (t4 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t4 = y2["return"]) && t4.call(y2), 0) : y2.next) && !(t4 = t4.call(y2, op[1])).done) return t4;
  57763. if (y2 = 0, t4) op = [op[0] & 2, t4.value];
  57764. switch (op[0]) {
  57765. case 0:
  57766. case 1:
  57767. t4 = op;
  57768. break;
  57769. case 4:
  57770. _3.label++;
  57771. return { value: op[1], done: false };
  57772. case 5:
  57773. _3.label++;
  57774. y2 = op[1];
  57775. op = [0];
  57776. continue;
  57777. case 7:
  57778. op = _3.ops.pop();
  57779. _3.trys.pop();
  57780. continue;
  57781. default:
  57782. if (!(t4 = _3.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) {
  57783. _3 = 0;
  57784. continue;
  57785. }
  57786. if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) {
  57787. _3.label = op[1];
  57788. break;
  57789. }
  57790. if (op[0] === 6 && _3.label < t4[1]) {
  57791. _3.label = t4[1];
  57792. t4 = op;
  57793. break;
  57794. }
  57795. if (t4 && _3.label < t4[2]) {
  57796. _3.label = t4[2];
  57797. _3.ops.push(op);
  57798. break;
  57799. }
  57800. if (t4[2]) _3.ops.pop();
  57801. _3.trys.pop();
  57802. continue;
  57803. }
  57804. op = body.call(thisArg, _3);
  57805. } catch (e4) {
  57806. op = [6, e4];
  57807. y2 = 0;
  57808. } finally {
  57809. f5 = t4 = 0;
  57810. }
  57811. if (op[0] & 5) throw op[1];
  57812. return { value: op[0] ? op[1] : void 0, done: true };
  57813. }
  57814. }
  57815. function __exportStar(m4, o3) {
  57816. for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(o3, p3)) __createBinding(o3, m4, p3);
  57817. }
  57818. function __values(o3) {
  57819. var s4 = typeof Symbol === "function" && Symbol.iterator, m4 = s4 && o3[s4], i4 = 0;
  57820. if (m4) return m4.call(o3);
  57821. if (o3 && typeof o3.length === "number") return {
  57822. next: function() {
  57823. if (o3 && i4 >= o3.length) o3 = void 0;
  57824. return { value: o3 && o3[i4++], done: !o3 };
  57825. }
  57826. };
  57827. throw new TypeError(s4 ? "Object is not iterable." : "Symbol.iterator is not defined.");
  57828. }
  57829. function __read(o3, n3) {
  57830. var m4 = typeof Symbol === "function" && o3[Symbol.iterator];
  57831. if (!m4) return o3;
  57832. var i4 = m4.call(o3), r4, ar = [], e4;
  57833. try {
  57834. while ((n3 === void 0 || n3-- > 0) && !(r4 = i4.next()).done) ar.push(r4.value);
  57835. } catch (error2) {
  57836. e4 = { error: error2 };
  57837. } finally {
  57838. try {
  57839. if (r4 && !r4.done && (m4 = i4["return"])) m4.call(i4);
  57840. } finally {
  57841. if (e4) throw e4.error;
  57842. }
  57843. }
  57844. return ar;
  57845. }
  57846. function __spread() {
  57847. for (var ar = [], i4 = 0; i4 < arguments.length; i4++)
  57848. ar = ar.concat(__read(arguments[i4]));
  57849. return ar;
  57850. }
  57851. function __spreadArrays() {
  57852. for (var s4 = 0, i4 = 0, il = arguments.length; i4 < il; i4++) s4 += arguments[i4].length;
  57853. for (var r4 = Array(s4), k3 = 0, i4 = 0; i4 < il; i4++)
  57854. for (var a3 = arguments[i4], j3 = 0, jl = a3.length; j3 < jl; j3++, k3++)
  57855. r4[k3] = a3[j3];
  57856. return r4;
  57857. }
  57858. function __spreadArray(to, from, pack) {
  57859. if (pack || arguments.length === 2) for (var i4 = 0, l3 = from.length, ar; i4 < l3; i4++) {
  57860. if (ar || !(i4 in from)) {
  57861. if (!ar) ar = Array.prototype.slice.call(from, 0, i4);
  57862. ar[i4] = from[i4];
  57863. }
  57864. }
  57865. return to.concat(ar || Array.prototype.slice.call(from));
  57866. }
  57867. function __await(v6) {
  57868. return this instanceof __await ? (this.v = v6, this) : new __await(v6);
  57869. }
  57870. function __asyncGenerator(thisArg, _arguments, generator) {
  57871. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  57872. var g3 = generator.apply(thisArg, _arguments || []), i4, q3 = [];
  57873. return i4 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i4[Symbol.asyncIterator] = function() {
  57874. return this;
  57875. }, i4;
  57876. function awaitReturn(f5) {
  57877. return function(v6) {
  57878. return Promise.resolve(v6).then(f5, reject);
  57879. };
  57880. }
  57881. function verb(n3, f5) {
  57882. if (g3[n3]) {
  57883. i4[n3] = function(v6) {
  57884. return new Promise(function(a3, b3) {
  57885. q3.push([n3, v6, a3, b3]) > 1 || resume(n3, v6);
  57886. });
  57887. };
  57888. if (f5) i4[n3] = f5(i4[n3]);
  57889. }
  57890. }
  57891. function resume(n3, v6) {
  57892. try {
  57893. step(g3[n3](v6));
  57894. } catch (e4) {
  57895. settle(q3[0][3], e4);
  57896. }
  57897. }
  57898. function step(r4) {
  57899. r4.value instanceof __await ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q3[0][2], r4);
  57900. }
  57901. function fulfill(value) {
  57902. resume("next", value);
  57903. }
  57904. function reject(value) {
  57905. resume("throw", value);
  57906. }
  57907. function settle(f5, v6) {
  57908. if (f5(v6), q3.shift(), q3.length) resume(q3[0][0], q3[0][1]);
  57909. }
  57910. }
  57911. function __asyncDelegator(o3) {
  57912. var i4, p3;
  57913. return i4 = {}, verb("next"), verb("throw", function(e4) {
  57914. throw e4;
  57915. }), verb("return"), i4[Symbol.iterator] = function() {
  57916. return this;
  57917. }, i4;
  57918. function verb(n3, f5) {
  57919. i4[n3] = o3[n3] ? function(v6) {
  57920. return (p3 = !p3) ? { value: __await(o3[n3](v6)), done: false } : f5 ? f5(v6) : v6;
  57921. } : f5;
  57922. }
  57923. }
  57924. function __asyncValues(o3) {
  57925. if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  57926. var m4 = o3[Symbol.asyncIterator], i4;
  57927. return m4 ? m4.call(o3) : (o3 = typeof __values === "function" ? __values(o3) : o3[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
  57928. return this;
  57929. }, i4);
  57930. function verb(n3) {
  57931. i4[n3] = o3[n3] && function(v6) {
  57932. return new Promise(function(resolve2, reject) {
  57933. v6 = o3[n3](v6), settle(resolve2, reject, v6.done, v6.value);
  57934. });
  57935. };
  57936. }
  57937. function settle(resolve2, reject, d3, v6) {
  57938. Promise.resolve(v6).then(function(v7) {
  57939. resolve2({ value: v7, done: d3 });
  57940. }, reject);
  57941. }
  57942. }
  57943. function __makeTemplateObject(cooked, raw2) {
  57944. if (Object.defineProperty) {
  57945. Object.defineProperty(cooked, "raw", { value: raw2 });
  57946. } else {
  57947. cooked.raw = raw2;
  57948. }
  57949. return cooked;
  57950. }
  57951. function __importStar(mod) {
  57952. if (mod && mod.__esModule) return mod;
  57953. var result = {};
  57954. if (mod != null) {
  57955. for (var k3 = ownKeys(mod), i4 = 0; i4 < k3.length; i4++) if (k3[i4] !== "default") __createBinding(result, mod, k3[i4]);
  57956. }
  57957. __setModuleDefault(result, mod);
  57958. return result;
  57959. }
  57960. function __importDefault(mod) {
  57961. return mod && mod.__esModule ? mod : { default: mod };
  57962. }
  57963. function __classPrivateFieldGet(receiver, state2, kind, f5) {
  57964. if (kind === "a" && !f5) throw new TypeError("Private accessor was defined without a getter");
  57965. if (typeof state2 === "function" ? receiver !== state2 || !f5 : !state2.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  57966. return kind === "m" ? f5 : kind === "a" ? f5.call(receiver) : f5 ? f5.value : state2.get(receiver);
  57967. }
  57968. function __classPrivateFieldSet(receiver, state2, value, kind, f5) {
  57969. if (kind === "m") throw new TypeError("Private method is not writable");
  57970. if (kind === "a" && !f5) throw new TypeError("Private accessor was defined without a setter");
  57971. if (typeof state2 === "function" ? receiver !== state2 || !f5 : !state2.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  57972. return kind === "a" ? f5.call(receiver, value) : f5 ? f5.value = value : state2.set(receiver, value), value;
  57973. }
  57974. function __classPrivateFieldIn(state2, receiver) {
  57975. if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object");
  57976. return typeof state2 === "function" ? receiver === state2 : state2.has(receiver);
  57977. }
  57978. function __addDisposableResource(env3, value, async) {
  57979. if (value !== null && value !== void 0) {
  57980. if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
  57981. var dispose, inner;
  57982. if (async) {
  57983. if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
  57984. dispose = value[Symbol.asyncDispose];
  57985. }
  57986. if (dispose === void 0) {
  57987. if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
  57988. dispose = value[Symbol.dispose];
  57989. if (async) inner = dispose;
  57990. }
  57991. if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
  57992. if (inner) dispose = function() {
  57993. try {
  57994. inner.call(this);
  57995. } catch (e4) {
  57996. return Promise.reject(e4);
  57997. }
  57998. };
  57999. env3.stack.push({ value, dispose, async });
  58000. } else if (async) {
  58001. env3.stack.push({ async: true });
  58002. }
  58003. return value;
  58004. }
  58005. function __disposeResources(env3) {
  58006. function fail(e4) {
  58007. env3.error = env3.hasError ? new _SuppressedError(e4, env3.error, "An error was suppressed during disposal.") : e4;
  58008. env3.hasError = true;
  58009. }
  58010. var r4, s4 = 0;
  58011. function next() {
  58012. while (r4 = env3.stack.pop()) {
  58013. try {
  58014. if (!r4.async && s4 === 1) return s4 = 0, env3.stack.push(r4), Promise.resolve().then(next);
  58015. if (r4.dispose) {
  58016. var result = r4.dispose.call(r4.value);
  58017. if (r4.async) return s4 |= 2, Promise.resolve(result).then(next, function(e4) {
  58018. fail(e4);
  58019. return next();
  58020. });
  58021. } else s4 |= 1;
  58022. } catch (e4) {
  58023. fail(e4);
  58024. }
  58025. }
  58026. if (s4 === 1) return env3.hasError ? Promise.reject(env3.error) : Promise.resolve();
  58027. if (env3.hasError) throw env3.error;
  58028. }
  58029. return next();
  58030. }
  58031. function __rewriteRelativeImportExtension(path4, preserveJsx) {
  58032. if (typeof path4 === "string" && /^\.\.?\//.test(path4)) {
  58033. return path4.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m4, tsx, d3, ext2, cm) {
  58034. return tsx ? preserveJsx ? ".jsx" : ".js" : d3 && (!ext2 || !cm) ? m4 : d3 + ext2 + "." + cm.toLowerCase() + "js";
  58035. });
  58036. }
  58037. return path4;
  58038. }
  58039. var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default;
  58040. var init_tslib_es6 = __esm({
  58041. "../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs"() {
  58042. extendStatics = function(d3, b3) {
  58043. extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) {
  58044. d4.__proto__ = b4;
  58045. } || function(d4, b4) {
  58046. for (var p3 in b4) if (Object.prototype.hasOwnProperty.call(b4, p3)) d4[p3] = b4[p3];
  58047. };
  58048. return extendStatics(d3, b3);
  58049. };
  58050. __assign = function() {
  58051. __assign = Object.assign || function __assign2(t4) {
  58052. for (var s4, i4 = 1, n3 = arguments.length; i4 < n3; i4++) {
  58053. s4 = arguments[i4];
  58054. for (var p3 in s4) if (Object.prototype.hasOwnProperty.call(s4, p3)) t4[p3] = s4[p3];
  58055. }
  58056. return t4;
  58057. };
  58058. return __assign.apply(this, arguments);
  58059. };
  58060. __createBinding = Object.create ? function(o3, m4, k3, k22) {
  58061. if (k22 === void 0) k22 = k3;
  58062. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  58063. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  58064. desc = { enumerable: true, get: function() {
  58065. return m4[k3];
  58066. } };
  58067. }
  58068. Object.defineProperty(o3, k22, desc);
  58069. } : function(o3, m4, k3, k22) {
  58070. if (k22 === void 0) k22 = k3;
  58071. o3[k22] = m4[k3];
  58072. };
  58073. __setModuleDefault = Object.create ? function(o3, v6) {
  58074. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  58075. } : function(o3, v6) {
  58076. o3["default"] = v6;
  58077. };
  58078. ownKeys = function(o3) {
  58079. ownKeys = Object.getOwnPropertyNames || function(o4) {
  58080. var ar = [];
  58081. for (var k3 in o4) if (Object.prototype.hasOwnProperty.call(o4, k3)) ar[ar.length] = k3;
  58082. return ar;
  58083. };
  58084. return ownKeys(o3);
  58085. };
  58086. _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) {
  58087. var e4 = new Error(message);
  58088. return e4.name = "SuppressedError", e4.error = error2, e4.suppressed = suppressed, e4;
  58089. };
  58090. tslib_es6_default = {
  58091. __extends,
  58092. __assign,
  58093. __rest,
  58094. __decorate,
  58095. __param,
  58096. __esDecorate,
  58097. __runInitializers,
  58098. __propKey,
  58099. __setFunctionName,
  58100. __metadata,
  58101. __awaiter,
  58102. __generator,
  58103. __createBinding,
  58104. __exportStar,
  58105. __values,
  58106. __read,
  58107. __spread,
  58108. __spreadArrays,
  58109. __spreadArray,
  58110. __await,
  58111. __asyncGenerator,
  58112. __asyncDelegator,
  58113. __asyncValues,
  58114. __makeTemplateObject,
  58115. __importStar,
  58116. __importDefault,
  58117. __classPrivateFieldGet,
  58118. __classPrivateFieldSet,
  58119. __classPrivateFieldIn,
  58120. __addDisposableResource,
  58121. __disposeResources,
  58122. __rewriteRelativeImportExtension
  58123. };
  58124. }
  58125. });
  58126. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/package.json
  58127. var require_package2 = __commonJS({
  58128. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/package.json"(exports2, module2) {
  58129. module2.exports = {
  58130. name: "@aws-sdk/client-rds-data",
  58131. description: "AWS SDK for JavaScript Rds Data Client for Node.js, Browser and React Native",
  58132. version: "3.817.0",
  58133. scripts: {
  58134. build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
  58135. "build:cjs": "node ../../scripts/compilation/inline client-rds-data",
  58136. "build:es": "tsc -p tsconfig.es.json",
  58137. "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
  58138. "build:types": "tsc -p tsconfig.types.json",
  58139. "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
  58140. clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
  58141. "extract:docs": "api-extractor run --local",
  58142. "generate:client": "node ../../scripts/generate-clients/single-service --solo rds-data"
  58143. },
  58144. main: "./dist-cjs/index.js",
  58145. types: "./dist-types/index.d.ts",
  58146. module: "./dist-es/index.js",
  58147. sideEffects: false,
  58148. dependencies: {
  58149. "@aws-crypto/sha256-browser": "5.2.0",
  58150. "@aws-crypto/sha256-js": "5.2.0",
  58151. "@aws-sdk/core": "3.816.0",
  58152. "@aws-sdk/credential-provider-node": "3.817.0",
  58153. "@aws-sdk/middleware-host-header": "3.804.0",
  58154. "@aws-sdk/middleware-logger": "3.804.0",
  58155. "@aws-sdk/middleware-recursion-detection": "3.804.0",
  58156. "@aws-sdk/middleware-user-agent": "3.816.0",
  58157. "@aws-sdk/region-config-resolver": "3.808.0",
  58158. "@aws-sdk/types": "3.804.0",
  58159. "@aws-sdk/util-endpoints": "3.808.0",
  58160. "@aws-sdk/util-user-agent-browser": "3.804.0",
  58161. "@aws-sdk/util-user-agent-node": "3.816.0",
  58162. "@smithy/config-resolver": "^4.1.2",
  58163. "@smithy/core": "^3.3.3",
  58164. "@smithy/fetch-http-handler": "^5.0.2",
  58165. "@smithy/hash-node": "^4.0.2",
  58166. "@smithy/invalid-dependency": "^4.0.2",
  58167. "@smithy/middleware-content-length": "^4.0.2",
  58168. "@smithy/middleware-endpoint": "^4.1.6",
  58169. "@smithy/middleware-retry": "^4.1.7",
  58170. "@smithy/middleware-serde": "^4.0.5",
  58171. "@smithy/middleware-stack": "^4.0.2",
  58172. "@smithy/node-config-provider": "^4.1.1",
  58173. "@smithy/node-http-handler": "^4.0.4",
  58174. "@smithy/protocol-http": "^5.1.0",
  58175. "@smithy/smithy-client": "^4.2.6",
  58176. "@smithy/types": "^4.2.0",
  58177. "@smithy/url-parser": "^4.0.2",
  58178. "@smithy/util-base64": "^4.0.0",
  58179. "@smithy/util-body-length-browser": "^4.0.0",
  58180. "@smithy/util-body-length-node": "^4.0.0",
  58181. "@smithy/util-defaults-mode-browser": "^4.0.14",
  58182. "@smithy/util-defaults-mode-node": "^4.0.14",
  58183. "@smithy/util-endpoints": "^3.0.4",
  58184. "@smithy/util-middleware": "^4.0.2",
  58185. "@smithy/util-retry": "^4.0.3",
  58186. "@smithy/util-utf8": "^4.0.0",
  58187. tslib: "^2.6.2"
  58188. },
  58189. devDependencies: {
  58190. "@tsconfig/node18": "18.2.4",
  58191. "@types/node": "^18.19.69",
  58192. concurrently: "7.0.0",
  58193. "downlevel-dts": "0.10.1",
  58194. rimraf: "3.0.2",
  58195. typescript: "~5.8.3"
  58196. },
  58197. engines: {
  58198. node: ">=18.0.0"
  58199. },
  58200. typesVersions: {
  58201. "<4.0": {
  58202. "dist-types/*": [
  58203. "dist-types/ts3.4/*"
  58204. ]
  58205. }
  58206. },
  58207. files: [
  58208. "dist-*/**"
  58209. ],
  58210. author: {
  58211. name: "AWS SDK for JavaScript Team",
  58212. url: "https://aws.amazon.com/javascript/"
  58213. },
  58214. license: "Apache-2.0",
  58215. browser: {
  58216. "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
  58217. },
  58218. "react-native": {
  58219. "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
  58220. },
  58221. homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-rds-data",
  58222. repository: {
  58223. type: "git",
  58224. url: "https://github.com/aws/aws-sdk-js-v3.git",
  58225. directory: "clients/client-rds-data"
  58226. }
  58227. };
  58228. }
  58229. });
  58230. // ../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js
  58231. var require_dist_cjs36 = __commonJS({
  58232. "../node_modules/.pnpm/@aws-sdk+credential-provider-env@3.816.0/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js"(exports2, module2) {
  58233. "use strict";
  58234. var __defProp3 = Object.defineProperty;
  58235. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  58236. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  58237. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  58238. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  58239. var __export2 = (target, all) => {
  58240. for (var name in all)
  58241. __defProp3(target, name, { get: all[name], enumerable: true });
  58242. };
  58243. var __copyProps3 = (to, from, except, desc) => {
  58244. if (from && typeof from === "object" || typeof from === "function") {
  58245. for (let key of __getOwnPropNames3(from))
  58246. if (!__hasOwnProp3.call(to, key) && key !== except)
  58247. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  58248. }
  58249. return to;
  58250. };
  58251. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  58252. var index_exports = {};
  58253. __export2(index_exports, {
  58254. ENV_ACCOUNT_ID: () => ENV_ACCOUNT_ID,
  58255. ENV_CREDENTIAL_SCOPE: () => ENV_CREDENTIAL_SCOPE,
  58256. ENV_EXPIRATION: () => ENV_EXPIRATION,
  58257. ENV_KEY: () => ENV_KEY,
  58258. ENV_SECRET: () => ENV_SECRET,
  58259. ENV_SESSION: () => ENV_SESSION,
  58260. fromEnv: () => fromEnv
  58261. });
  58262. module2.exports = __toCommonJS2(index_exports);
  58263. var import_client3 = (init_client(), __toCommonJS(client_exports));
  58264. var import_property_provider2 = require_dist_cjs20();
  58265. var ENV_KEY = "AWS_ACCESS_KEY_ID";
  58266. var ENV_SECRET = "AWS_SECRET_ACCESS_KEY";
  58267. var ENV_SESSION = "AWS_SESSION_TOKEN";
  58268. var ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION";
  58269. var ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE";
  58270. var ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID";
  58271. var fromEnv = /* @__PURE__ */ __name((init2) => async () => {
  58272. var _a2;
  58273. (_a2 = init2 == null ? void 0 : init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-env - fromEnv");
  58274. const accessKeyId = process.env[ENV_KEY];
  58275. const secretAccessKey = process.env[ENV_SECRET];
  58276. const sessionToken = process.env[ENV_SESSION];
  58277. const expiry = process.env[ENV_EXPIRATION];
  58278. const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];
  58279. const accountId = process.env[ENV_ACCOUNT_ID];
  58280. if (accessKeyId && secretAccessKey) {
  58281. const credentials2 = {
  58282. accessKeyId,
  58283. secretAccessKey,
  58284. ...sessionToken && { sessionToken },
  58285. ...expiry && { expiration: new Date(expiry) },
  58286. ...credentialScope && { credentialScope },
  58287. ...accountId && { accountId }
  58288. };
  58289. (0, import_client3.setCredentialFeature)(credentials2, "CREDENTIALS_ENV_VARS", "g");
  58290. return credentials2;
  58291. }
  58292. throw new import_property_provider2.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init2 == null ? void 0 : init2.logger });
  58293. }, "fromEnv");
  58294. }
  58295. });
  58296. // ../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js
  58297. var require_dist_cjs37 = __commonJS({
  58298. "../node_modules/.pnpm/@smithy+credential-provider-imds@4.0.6/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js"(exports2, module2) {
  58299. var __defProp3 = Object.defineProperty;
  58300. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  58301. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  58302. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  58303. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  58304. var __export2 = (target, all) => {
  58305. for (var name in all)
  58306. __defProp3(target, name, { get: all[name], enumerable: true });
  58307. };
  58308. var __copyProps3 = (to, from, except, desc) => {
  58309. if (from && typeof from === "object" || typeof from === "function") {
  58310. for (let key of __getOwnPropNames3(from))
  58311. if (!__hasOwnProp3.call(to, key) && key !== except)
  58312. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  58313. }
  58314. return to;
  58315. };
  58316. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  58317. var src_exports = {};
  58318. __export2(src_exports, {
  58319. DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES,
  58320. DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
  58321. ENV_CMDS_AUTH_TOKEN: () => ENV_CMDS_AUTH_TOKEN,
  58322. ENV_CMDS_FULL_URI: () => ENV_CMDS_FULL_URI,
  58323. ENV_CMDS_RELATIVE_URI: () => ENV_CMDS_RELATIVE_URI,
  58324. Endpoint: () => Endpoint,
  58325. fromContainerMetadata: () => fromContainerMetadata,
  58326. fromInstanceMetadata: () => fromInstanceMetadata,
  58327. getInstanceMetadataEndpoint: () => getInstanceMetadataEndpoint,
  58328. httpRequest: () => httpRequest,
  58329. providerConfigFromInit: () => providerConfigFromInit
  58330. });
  58331. module2.exports = __toCommonJS2(src_exports);
  58332. var import_url8 = require("url");
  58333. var import_property_provider2 = require_dist_cjs20();
  58334. var import_buffer2 = require("buffer");
  58335. var import_http3 = require("http");
  58336. function httpRequest(options) {
  58337. return new Promise((resolve2, reject) => {
  58338. var _a3;
  58339. const req = (0, import_http3.request)({
  58340. method: "GET",
  58341. ...options,
  58342. // Node.js http module doesn't accept hostname with square brackets
  58343. // Refs: https://github.com/nodejs/node/issues/39738
  58344. hostname: (_a3 = options.hostname) == null ? void 0 : _a3.replace(/^\[(.+)\]$/, "$1")
  58345. });
  58346. req.on("error", (err2) => {
  58347. reject(Object.assign(new import_property_provider2.ProviderError("Unable to connect to instance metadata service"), err2));
  58348. req.destroy();
  58349. });
  58350. req.on("timeout", () => {
  58351. reject(new import_property_provider2.ProviderError("TimeoutError from instance metadata service"));
  58352. req.destroy();
  58353. });
  58354. req.on("response", (res) => {
  58355. const { statusCode = 400 } = res;
  58356. if (statusCode < 200 || 300 <= statusCode) {
  58357. reject(
  58358. Object.assign(new import_property_provider2.ProviderError("Error response received from instance metadata service"), { statusCode })
  58359. );
  58360. req.destroy();
  58361. }
  58362. const chunks = [];
  58363. res.on("data", (chunk) => {
  58364. chunks.push(chunk);
  58365. });
  58366. res.on("end", () => {
  58367. resolve2(import_buffer2.Buffer.concat(chunks));
  58368. req.destroy();
  58369. });
  58370. });
  58371. req.end();
  58372. });
  58373. }
  58374. __name(httpRequest, "httpRequest");
  58375. var isImdsCredentials = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.AccessKeyId === "string" && typeof arg.SecretAccessKey === "string" && typeof arg.Token === "string" && typeof arg.Expiration === "string", "isImdsCredentials");
  58376. var fromImdsCredentials = /* @__PURE__ */ __name((creds) => ({
  58377. accessKeyId: creds.AccessKeyId,
  58378. secretAccessKey: creds.SecretAccessKey,
  58379. sessionToken: creds.Token,
  58380. expiration: new Date(creds.Expiration),
  58381. ...creds.AccountId && { accountId: creds.AccountId }
  58382. }), "fromImdsCredentials");
  58383. var DEFAULT_TIMEOUT = 1e3;
  58384. var DEFAULT_MAX_RETRIES = 0;
  58385. var providerConfigFromInit = /* @__PURE__ */ __name(({
  58386. maxRetries = DEFAULT_MAX_RETRIES,
  58387. timeout = DEFAULT_TIMEOUT
  58388. }) => ({ maxRetries, timeout }), "providerConfigFromInit");
  58389. var retry = /* @__PURE__ */ __name((toRetry, maxRetries) => {
  58390. let promise = toRetry();
  58391. for (let i4 = 0; i4 < maxRetries; i4++) {
  58392. promise = promise.catch(toRetry);
  58393. }
  58394. return promise;
  58395. }, "retry");
  58396. var ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
  58397. var ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
  58398. var ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
  58399. var fromContainerMetadata = /* @__PURE__ */ __name((init2 = {}) => {
  58400. const { timeout, maxRetries } = providerConfigFromInit(init2);
  58401. return () => retry(async () => {
  58402. const requestOptions = await getCmdsUri({ logger: init2.logger });
  58403. const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions));
  58404. if (!isImdsCredentials(credsResponse)) {
  58405. throw new import_property_provider2.CredentialsProviderError("Invalid response received from instance metadata service.", {
  58406. logger: init2.logger
  58407. });
  58408. }
  58409. return fromImdsCredentials(credsResponse);
  58410. }, maxRetries);
  58411. }, "fromContainerMetadata");
  58412. var requestFromEcsImds = /* @__PURE__ */ __name(async (timeout, options) => {
  58413. if (process.env[ENV_CMDS_AUTH_TOKEN]) {
  58414. options.headers = {
  58415. ...options.headers,
  58416. Authorization: process.env[ENV_CMDS_AUTH_TOKEN]
  58417. };
  58418. }
  58419. const buffer = await httpRequest({
  58420. ...options,
  58421. timeout
  58422. });
  58423. return buffer.toString();
  58424. }, "requestFromEcsImds");
  58425. var CMDS_IP = "169.254.170.2";
  58426. var GREENGRASS_HOSTS = {
  58427. localhost: true,
  58428. "127.0.0.1": true
  58429. };
  58430. var GREENGRASS_PROTOCOLS = {
  58431. "http:": true,
  58432. "https:": true
  58433. };
  58434. var getCmdsUri = /* @__PURE__ */ __name(async ({ logger: logger3 }) => {
  58435. if (process.env[ENV_CMDS_RELATIVE_URI]) {
  58436. return {
  58437. hostname: CMDS_IP,
  58438. path: process.env[ENV_CMDS_RELATIVE_URI]
  58439. };
  58440. }
  58441. if (process.env[ENV_CMDS_FULL_URI]) {
  58442. const parsed = (0, import_url8.parse)(process.env[ENV_CMDS_FULL_URI]);
  58443. if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) {
  58444. throw new import_property_provider2.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, {
  58445. tryNextLink: false,
  58446. logger: logger3
  58447. });
  58448. }
  58449. if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) {
  58450. throw new import_property_provider2.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, {
  58451. tryNextLink: false,
  58452. logger: logger3
  58453. });
  58454. }
  58455. return {
  58456. ...parsed,
  58457. port: parsed.port ? parseInt(parsed.port, 10) : void 0
  58458. };
  58459. }
  58460. throw new import_property_provider2.CredentialsProviderError(
  58461. `The container metadata credential provider cannot be used unless the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment variable is set`,
  58462. {
  58463. tryNextLink: false,
  58464. logger: logger3
  58465. }
  58466. );
  58467. }, "getCmdsUri");
  58468. var _a2;
  58469. var InstanceMetadataV1FallbackError = (_a2 = class extends import_property_provider2.CredentialsProviderError {
  58470. constructor(message, tryNextLink = true) {
  58471. super(message, tryNextLink);
  58472. this.tryNextLink = tryNextLink;
  58473. this.name = "InstanceMetadataV1FallbackError";
  58474. Object.setPrototypeOf(this, _a2.prototype);
  58475. }
  58476. }, __name(_a2, "InstanceMetadataV1FallbackError"), _a2);
  58477. var import_node_config_provider3 = require_dist_cjs29();
  58478. var import_url_parser3 = require_dist_cjs31();
  58479. var Endpoint = /* @__PURE__ */ ((Endpoint2) => {
  58480. Endpoint2["IPv4"] = "http://169.254.169.254";
  58481. Endpoint2["IPv6"] = "http://[fd00:ec2::254]";
  58482. return Endpoint2;
  58483. })(Endpoint || {});
  58484. var ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT";
  58485. var CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint";
  58486. var ENDPOINT_CONFIG_OPTIONS = {
  58487. environmentVariableSelector: (env3) => env3[ENV_ENDPOINT_NAME],
  58488. configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME],
  58489. default: void 0
  58490. };
  58491. var EndpointMode = /* @__PURE__ */ ((EndpointMode2) => {
  58492. EndpointMode2["IPv4"] = "IPv4";
  58493. EndpointMode2["IPv6"] = "IPv6";
  58494. return EndpointMode2;
  58495. })(EndpointMode || {});
  58496. var ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE";
  58497. var CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode";
  58498. var ENDPOINT_MODE_CONFIG_OPTIONS = {
  58499. environmentVariableSelector: (env3) => env3[ENV_ENDPOINT_MODE_NAME],
  58500. configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME],
  58501. default: "IPv4"
  58502. /* IPv4 */
  58503. };
  58504. var getInstanceMetadataEndpoint = /* @__PURE__ */ __name(async () => (0, import_url_parser3.parseUrl)(await getFromEndpointConfig() || await getFromEndpointModeConfig()), "getInstanceMetadataEndpoint");
  58505. var getFromEndpointConfig = /* @__PURE__ */ __name(async () => (0, import_node_config_provider3.loadConfig)(ENDPOINT_CONFIG_OPTIONS)(), "getFromEndpointConfig");
  58506. var getFromEndpointModeConfig = /* @__PURE__ */ __name(async () => {
  58507. const endpointMode = await (0, import_node_config_provider3.loadConfig)(ENDPOINT_MODE_CONFIG_OPTIONS)();
  58508. switch (endpointMode) {
  58509. case "IPv4":
  58510. return "http://169.254.169.254";
  58511. case "IPv6":
  58512. return "http://[fd00:ec2::254]";
  58513. default:
  58514. throw new Error(`Unsupported endpoint mode: ${endpointMode}. Select from ${Object.values(EndpointMode)}`);
  58515. }
  58516. }, "getFromEndpointModeConfig");
  58517. var STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60;
  58518. var STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60;
  58519. var STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html";
  58520. var getExtendedInstanceMetadataCredentials = /* @__PURE__ */ __name((credentials2, logger3) => {
  58521. const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS);
  58522. const newExpiration = new Date(Date.now() + refreshInterval * 1e3);
  58523. logger3.warn(
  58524. `Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(newExpiration)}.
  58525. For more information, please visit: ` + STATIC_STABILITY_DOC_URL
  58526. );
  58527. const originalExpiration = credentials2.originalExpiration ?? credentials2.expiration;
  58528. return {
  58529. ...credentials2,
  58530. ...originalExpiration ? { originalExpiration } : {},
  58531. expiration: newExpiration
  58532. };
  58533. }, "getExtendedInstanceMetadataCredentials");
  58534. var staticStabilityProvider = /* @__PURE__ */ __name((provider, options = {}) => {
  58535. const logger3 = (options == null ? void 0 : options.logger) || console;
  58536. let pastCredentials;
  58537. return async () => {
  58538. let credentials2;
  58539. try {
  58540. credentials2 = await provider();
  58541. if (credentials2.expiration && credentials2.expiration.getTime() < Date.now()) {
  58542. credentials2 = getExtendedInstanceMetadataCredentials(credentials2, logger3);
  58543. }
  58544. } catch (e4) {
  58545. if (pastCredentials) {
  58546. logger3.warn("Credential renew failed: ", e4);
  58547. credentials2 = getExtendedInstanceMetadataCredentials(pastCredentials, logger3);
  58548. } else {
  58549. throw e4;
  58550. }
  58551. }
  58552. pastCredentials = credentials2;
  58553. return credentials2;
  58554. };
  58555. }, "staticStabilityProvider");
  58556. var IMDS_PATH = "/latest/meta-data/iam/security-credentials/";
  58557. var IMDS_TOKEN_PATH = "/latest/api/token";
  58558. var AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED";
  58559. var PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled";
  58560. var X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token";
  58561. var fromInstanceMetadata = /* @__PURE__ */ __name((init2 = {}) => staticStabilityProvider(getInstanceMetadataProvider(init2), { logger: init2.logger }), "fromInstanceMetadata");
  58562. var getInstanceMetadataProvider = /* @__PURE__ */ __name((init2 = {}) => {
  58563. let disableFetchToken = false;
  58564. const { logger: logger3, profile } = init2;
  58565. const { timeout, maxRetries } = providerConfigFromInit(init2);
  58566. const getCredentials = /* @__PURE__ */ __name(async (maxRetries2, options) => {
  58567. var _a3;
  58568. const isImdsV1Fallback = disableFetchToken || ((_a3 = options.headers) == null ? void 0 : _a3[X_AWS_EC2_METADATA_TOKEN]) == null;
  58569. if (isImdsV1Fallback) {
  58570. let fallbackBlockedFromProfile = false;
  58571. let fallbackBlockedFromProcessEnv = false;
  58572. const configValue = await (0, import_node_config_provider3.loadConfig)(
  58573. {
  58574. environmentVariableSelector: (env3) => {
  58575. const envValue = env3[AWS_EC2_METADATA_V1_DISABLED];
  58576. fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false";
  58577. if (envValue === void 0) {
  58578. throw new import_property_provider2.CredentialsProviderError(
  58579. `${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`,
  58580. { logger: init2.logger }
  58581. );
  58582. }
  58583. return fallbackBlockedFromProcessEnv;
  58584. },
  58585. configFileSelector: (profile2) => {
  58586. const profileValue = profile2[PROFILE_AWS_EC2_METADATA_V1_DISABLED];
  58587. fallbackBlockedFromProfile = !!profileValue && profileValue !== "false";
  58588. return fallbackBlockedFromProfile;
  58589. },
  58590. default: false
  58591. },
  58592. {
  58593. profile
  58594. }
  58595. )();
  58596. if (init2.ec2MetadataV1Disabled || configValue) {
  58597. const causes = [];
  58598. if (init2.ec2MetadataV1Disabled)
  58599. causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");
  58600. if (fallbackBlockedFromProfile)
  58601. causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`);
  58602. if (fallbackBlockedFromProcessEnv)
  58603. causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`);
  58604. throw new InstanceMetadataV1FallbackError(
  58605. `AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(
  58606. ", "
  58607. )}].`
  58608. );
  58609. }
  58610. }
  58611. const imdsProfile = (await retry(async () => {
  58612. let profile2;
  58613. try {
  58614. profile2 = await getProfile(options);
  58615. } catch (err2) {
  58616. if (err2.statusCode === 401) {
  58617. disableFetchToken = false;
  58618. }
  58619. throw err2;
  58620. }
  58621. return profile2;
  58622. }, maxRetries2)).trim();
  58623. return retry(async () => {
  58624. let creds;
  58625. try {
  58626. creds = await getCredentialsFromProfile(imdsProfile, options, init2);
  58627. } catch (err2) {
  58628. if (err2.statusCode === 401) {
  58629. disableFetchToken = false;
  58630. }
  58631. throw err2;
  58632. }
  58633. return creds;
  58634. }, maxRetries2);
  58635. }, "getCredentials");
  58636. return async () => {
  58637. const endpoint = await getInstanceMetadataEndpoint();
  58638. if (disableFetchToken) {
  58639. logger3 == null ? void 0 : logger3.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)");
  58640. return getCredentials(maxRetries, { ...endpoint, timeout });
  58641. } else {
  58642. let token;
  58643. try {
  58644. token = (await getMetadataToken({ ...endpoint, timeout })).toString();
  58645. } catch (error2) {
  58646. if ((error2 == null ? void 0 : error2.statusCode) === 400) {
  58647. throw Object.assign(error2, {
  58648. message: "EC2 Metadata token request returned error"
  58649. });
  58650. } else if (error2.message === "TimeoutError" || [403, 404, 405].includes(error2.statusCode)) {
  58651. disableFetchToken = true;
  58652. }
  58653. logger3 == null ? void 0 : logger3.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)");
  58654. return getCredentials(maxRetries, { ...endpoint, timeout });
  58655. }
  58656. return getCredentials(maxRetries, {
  58657. ...endpoint,
  58658. headers: {
  58659. [X_AWS_EC2_METADATA_TOKEN]: token
  58660. },
  58661. timeout
  58662. });
  58663. }
  58664. };
  58665. }, "getInstanceMetadataProvider");
  58666. var getMetadataToken = /* @__PURE__ */ __name(async (options) => httpRequest({
  58667. ...options,
  58668. path: IMDS_TOKEN_PATH,
  58669. method: "PUT",
  58670. headers: {
  58671. "x-aws-ec2-metadata-token-ttl-seconds": "21600"
  58672. }
  58673. }), "getMetadataToken");
  58674. var getProfile = /* @__PURE__ */ __name(async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(), "getProfile");
  58675. var getCredentialsFromProfile = /* @__PURE__ */ __name(async (profile, options, init2) => {
  58676. const credentialsResponse = JSON.parse(
  58677. (await httpRequest({
  58678. ...options,
  58679. path: IMDS_PATH + profile
  58680. })).toString()
  58681. );
  58682. if (!isImdsCredentials(credentialsResponse)) {
  58683. throw new import_property_provider2.CredentialsProviderError("Invalid response received from instance metadata service.", {
  58684. logger: init2.logger
  58685. });
  58686. }
  58687. return fromImdsCredentials(credentialsResponse);
  58688. }, "getCredentialsFromProfile");
  58689. }
  58690. });
  58691. // ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js
  58692. var require_checkUrl = __commonJS({
  58693. "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js"(exports2) {
  58694. "use strict";
  58695. Object.defineProperty(exports2, "__esModule", { value: true });
  58696. exports2.checkUrl = void 0;
  58697. var property_provider_1 = require_dist_cjs20();
  58698. var ECS_CONTAINER_HOST = "169.254.170.2";
  58699. var EKS_CONTAINER_HOST_IPv4 = "169.254.170.23";
  58700. var EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]";
  58701. var checkUrl = (url, logger3) => {
  58702. if (url.protocol === "https:") {
  58703. return;
  58704. }
  58705. if (url.hostname === ECS_CONTAINER_HOST || url.hostname === EKS_CONTAINER_HOST_IPv4 || url.hostname === EKS_CONTAINER_HOST_IPv6) {
  58706. return;
  58707. }
  58708. if (url.hostname.includes("[")) {
  58709. if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") {
  58710. return;
  58711. }
  58712. } else {
  58713. if (url.hostname === "localhost") {
  58714. return;
  58715. }
  58716. const ipComponents = url.hostname.split(".");
  58717. const inRange = (component) => {
  58718. const num = parseInt(component, 10);
  58719. return 0 <= num && num <= 255;
  58720. };
  58721. if (ipComponents[0] === "127" && inRange(ipComponents[1]) && inRange(ipComponents[2]) && inRange(ipComponents[3]) && ipComponents.length === 4) {
  58722. return;
  58723. }
  58724. }
  58725. throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following:
  58726. - loopback CIDR 127.0.0.0/8 or [::1/128]
  58727. - ECS container host 169.254.170.2
  58728. - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger: logger3 });
  58729. };
  58730. exports2.checkUrl = checkUrl;
  58731. }
  58732. });
  58733. // ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js
  58734. var require_requestHelpers = __commonJS({
  58735. "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js"(exports2) {
  58736. "use strict";
  58737. Object.defineProperty(exports2, "__esModule", { value: true });
  58738. exports2.createGetRequest = createGetRequest;
  58739. exports2.getCredentials = getCredentials;
  58740. var property_provider_1 = require_dist_cjs20();
  58741. var protocol_http_1 = require_dist_cjs2();
  58742. var smithy_client_1 = require_dist_cjs23();
  58743. var util_stream_1 = require_dist_cjs17();
  58744. function createGetRequest(url) {
  58745. return new protocol_http_1.HttpRequest({
  58746. protocol: url.protocol,
  58747. hostname: url.hostname,
  58748. port: Number(url.port),
  58749. path: url.pathname,
  58750. query: Array.from(url.searchParams.entries()).reduce((acc, [k3, v6]) => {
  58751. acc[k3] = v6;
  58752. return acc;
  58753. }, {}),
  58754. fragment: url.hash
  58755. });
  58756. }
  58757. async function getCredentials(response, logger3) {
  58758. const stream = (0, util_stream_1.sdkStreamMixin)(response.body);
  58759. const str = await stream.transformToString();
  58760. if (response.statusCode === 200) {
  58761. const parsed = JSON.parse(str);
  58762. if (typeof parsed.AccessKeyId !== "string" || typeof parsed.SecretAccessKey !== "string" || typeof parsed.Token !== "string" || typeof parsed.Expiration !== "string") {
  58763. throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger: logger3 });
  58764. }
  58765. return {
  58766. accessKeyId: parsed.AccessKeyId,
  58767. secretAccessKey: parsed.SecretAccessKey,
  58768. sessionToken: parsed.Token,
  58769. expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration)
  58770. };
  58771. }
  58772. if (response.statusCode >= 400 && response.statusCode < 500) {
  58773. let parsedBody = {};
  58774. try {
  58775. parsedBody = JSON.parse(str);
  58776. } catch (e4) {
  58777. }
  58778. throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger3 }), {
  58779. Code: parsedBody.Code,
  58780. Message: parsedBody.Message
  58781. });
  58782. }
  58783. throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger: logger3 });
  58784. }
  58785. }
  58786. });
  58787. // ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js
  58788. var require_retry_wrapper = __commonJS({
  58789. "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js"(exports2) {
  58790. "use strict";
  58791. Object.defineProperty(exports2, "__esModule", { value: true });
  58792. exports2.retryWrapper = void 0;
  58793. var retryWrapper = (toRetry, maxRetries, delayMs) => {
  58794. return async () => {
  58795. for (let i4 = 0; i4 < maxRetries; ++i4) {
  58796. try {
  58797. return await toRetry();
  58798. } catch (e4) {
  58799. await new Promise((resolve2) => setTimeout(resolve2, delayMs));
  58800. }
  58801. }
  58802. return await toRetry();
  58803. };
  58804. };
  58805. exports2.retryWrapper = retryWrapper;
  58806. }
  58807. });
  58808. // ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js
  58809. var require_fromHttp = __commonJS({
  58810. "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js"(exports2) {
  58811. "use strict";
  58812. Object.defineProperty(exports2, "__esModule", { value: true });
  58813. exports2.fromHttp = void 0;
  58814. var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
  58815. var client_1 = (init_client(), __toCommonJS(client_exports));
  58816. var node_http_handler_1 = require_dist_cjs14();
  58817. var property_provider_1 = require_dist_cjs20();
  58818. var promises_1 = tslib_1.__importDefault(require("fs/promises"));
  58819. var checkUrl_1 = require_checkUrl();
  58820. var requestHelpers_1 = require_requestHelpers();
  58821. var retry_wrapper_1 = require_retry_wrapper();
  58822. var AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI";
  58823. var DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2";
  58824. var AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI";
  58825. var AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE";
  58826. var AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN";
  58827. var fromHttp = (options = {}) => {
  58828. var _a2, _b, _c;
  58829. (_a2 = options.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-http - fromHttp");
  58830. let host;
  58831. const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI];
  58832. const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI];
  58833. const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN];
  58834. const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE];
  58835. const warn = ((_c = (_b = options.logger) == null ? void 0 : _b.constructor) == null ? void 0 : _c.name) === "NoOpLogger" || !options.logger ? console.warn : options.logger.warn;
  58836. if (relative && full) {
  58837. warn("@aws-sdk/credential-provider-http: you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri.");
  58838. warn("awsContainerCredentialsFullUri will take precedence.");
  58839. }
  58840. if (token && tokenFile) {
  58841. warn("@aws-sdk/credential-provider-http: you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile.");
  58842. warn("awsContainerAuthorizationToken will take precedence.");
  58843. }
  58844. if (full) {
  58845. host = full;
  58846. } else if (relative) {
  58847. host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`;
  58848. } else {
  58849. throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided.
  58850. Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger });
  58851. }
  58852. const url = new URL(host);
  58853. (0, checkUrl_1.checkUrl)(url, options.logger);
  58854. const requestHandler = new node_http_handler_1.NodeHttpHandler({
  58855. requestTimeout: options.timeout ?? 1e3,
  58856. connectionTimeout: options.timeout ?? 1e3
  58857. });
  58858. return (0, retry_wrapper_1.retryWrapper)(async () => {
  58859. const request = (0, requestHelpers_1.createGetRequest)(url);
  58860. if (token) {
  58861. request.headers.Authorization = token;
  58862. } else if (tokenFile) {
  58863. request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString();
  58864. }
  58865. try {
  58866. const result = await requestHandler.handle(request);
  58867. return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z"));
  58868. } catch (e4) {
  58869. throw new property_provider_1.CredentialsProviderError(String(e4), { logger: options.logger });
  58870. }
  58871. }, options.maxRetries ?? 3, options.timeout ?? 1e3);
  58872. };
  58873. exports2.fromHttp = fromHttp;
  58874. }
  58875. });
  58876. // ../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js
  58877. var require_dist_cjs38 = __commonJS({
  58878. "../node_modules/.pnpm/@aws-sdk+credential-provider-http@3.816.0/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js"(exports2) {
  58879. "use strict";
  58880. Object.defineProperty(exports2, "__esModule", { value: true });
  58881. exports2.fromHttp = void 0;
  58882. var fromHttp_1 = require_fromHttp();
  58883. Object.defineProperty(exports2, "fromHttp", { enumerable: true, get: function() {
  58884. return fromHttp_1.fromHttp;
  58885. } });
  58886. }
  58887. });
  58888. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js
  58889. var require_httpAuthSchemeProvider2 = __commonJS({
  58890. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js"(exports2) {
  58891. "use strict";
  58892. Object.defineProperty(exports2, "__esModule", { value: true });
  58893. exports2.resolveHttpAuthSchemeConfig = exports2.defaultSSOHttpAuthSchemeProvider = exports2.defaultSSOHttpAuthSchemeParametersProvider = void 0;
  58894. var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
  58895. var util_middleware_1 = require_dist_cjs6();
  58896. var defaultSSOHttpAuthSchemeParametersProvider = async (config, context, input) => {
  58897. return {
  58898. operation: (0, util_middleware_1.getSmithyContext)(context).operation,
  58899. region: await (0, util_middleware_1.normalizeProvider)(config.region)() || (() => {
  58900. throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
  58901. })()
  58902. };
  58903. };
  58904. exports2.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider;
  58905. function createAwsAuthSigv4HttpAuthOption3(authParameters) {
  58906. return {
  58907. schemeId: "aws.auth#sigv4",
  58908. signingProperties: {
  58909. name: "awsssoportal",
  58910. region: authParameters.region
  58911. },
  58912. propertiesExtractor: (config, context) => ({
  58913. signingProperties: {
  58914. config,
  58915. context
  58916. }
  58917. })
  58918. };
  58919. }
  58920. function createSmithyApiNoAuthHttpAuthOption3(authParameters) {
  58921. return {
  58922. schemeId: "smithy.api#noAuth"
  58923. };
  58924. }
  58925. var defaultSSOHttpAuthSchemeProvider = (authParameters) => {
  58926. const options = [];
  58927. switch (authParameters.operation) {
  58928. case "GetRoleCredentials": {
  58929. options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
  58930. break;
  58931. }
  58932. case "ListAccountRoles": {
  58933. options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
  58934. break;
  58935. }
  58936. case "ListAccounts": {
  58937. options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
  58938. break;
  58939. }
  58940. case "Logout": {
  58941. options.push(createSmithyApiNoAuthHttpAuthOption3(authParameters));
  58942. break;
  58943. }
  58944. default: {
  58945. options.push(createAwsAuthSigv4HttpAuthOption3(authParameters));
  58946. }
  58947. }
  58948. return options;
  58949. };
  58950. exports2.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider;
  58951. var resolveHttpAuthSchemeConfig3 = (config) => {
  58952. const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config);
  58953. return Object.assign(config_0, {
  58954. authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? [])
  58955. });
  58956. };
  58957. exports2.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig3;
  58958. }
  58959. });
  58960. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/package.json
  58961. var require_package3 = __commonJS({
  58962. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/package.json"(exports2, module2) {
  58963. module2.exports = {
  58964. name: "@aws-sdk/client-sso",
  58965. description: "AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native",
  58966. version: "3.817.0",
  58967. scripts: {
  58968. build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
  58969. "build:cjs": "node ../../scripts/compilation/inline client-sso",
  58970. "build:es": "tsc -p tsconfig.es.json",
  58971. "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
  58972. "build:types": "tsc -p tsconfig.types.json",
  58973. "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
  58974. clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
  58975. "extract:docs": "api-extractor run --local",
  58976. "generate:client": "node ../../scripts/generate-clients/single-service --solo sso"
  58977. },
  58978. main: "./dist-cjs/index.js",
  58979. types: "./dist-types/index.d.ts",
  58980. module: "./dist-es/index.js",
  58981. sideEffects: false,
  58982. dependencies: {
  58983. "@aws-crypto/sha256-browser": "5.2.0",
  58984. "@aws-crypto/sha256-js": "5.2.0",
  58985. "@aws-sdk/core": "3.816.0",
  58986. "@aws-sdk/middleware-host-header": "3.804.0",
  58987. "@aws-sdk/middleware-logger": "3.804.0",
  58988. "@aws-sdk/middleware-recursion-detection": "3.804.0",
  58989. "@aws-sdk/middleware-user-agent": "3.816.0",
  58990. "@aws-sdk/region-config-resolver": "3.808.0",
  58991. "@aws-sdk/types": "3.804.0",
  58992. "@aws-sdk/util-endpoints": "3.808.0",
  58993. "@aws-sdk/util-user-agent-browser": "3.804.0",
  58994. "@aws-sdk/util-user-agent-node": "3.816.0",
  58995. "@smithy/config-resolver": "^4.1.2",
  58996. "@smithy/core": "^3.3.3",
  58997. "@smithy/fetch-http-handler": "^5.0.2",
  58998. "@smithy/hash-node": "^4.0.2",
  58999. "@smithy/invalid-dependency": "^4.0.2",
  59000. "@smithy/middleware-content-length": "^4.0.2",
  59001. "@smithy/middleware-endpoint": "^4.1.6",
  59002. "@smithy/middleware-retry": "^4.1.7",
  59003. "@smithy/middleware-serde": "^4.0.5",
  59004. "@smithy/middleware-stack": "^4.0.2",
  59005. "@smithy/node-config-provider": "^4.1.1",
  59006. "@smithy/node-http-handler": "^4.0.4",
  59007. "@smithy/protocol-http": "^5.1.0",
  59008. "@smithy/smithy-client": "^4.2.6",
  59009. "@smithy/types": "^4.2.0",
  59010. "@smithy/url-parser": "^4.0.2",
  59011. "@smithy/util-base64": "^4.0.0",
  59012. "@smithy/util-body-length-browser": "^4.0.0",
  59013. "@smithy/util-body-length-node": "^4.0.0",
  59014. "@smithy/util-defaults-mode-browser": "^4.0.14",
  59015. "@smithy/util-defaults-mode-node": "^4.0.14",
  59016. "@smithy/util-endpoints": "^3.0.4",
  59017. "@smithy/util-middleware": "^4.0.2",
  59018. "@smithy/util-retry": "^4.0.3",
  59019. "@smithy/util-utf8": "^4.0.0",
  59020. tslib: "^2.6.2"
  59021. },
  59022. devDependencies: {
  59023. "@tsconfig/node18": "18.2.4",
  59024. "@types/node": "^18.19.69",
  59025. concurrently: "7.0.0",
  59026. "downlevel-dts": "0.10.1",
  59027. rimraf: "3.0.2",
  59028. typescript: "~5.8.3"
  59029. },
  59030. engines: {
  59031. node: ">=18.0.0"
  59032. },
  59033. typesVersions: {
  59034. "<4.0": {
  59035. "dist-types/*": [
  59036. "dist-types/ts3.4/*"
  59037. ]
  59038. }
  59039. },
  59040. files: [
  59041. "dist-*/**"
  59042. ],
  59043. author: {
  59044. name: "AWS SDK for JavaScript Team",
  59045. url: "https://aws.amazon.com/javascript/"
  59046. },
  59047. license: "Apache-2.0",
  59048. browser: {
  59049. "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
  59050. },
  59051. "react-native": {
  59052. "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
  59053. },
  59054. homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-sso",
  59055. repository: {
  59056. type: "git",
  59057. url: "https://github.com/aws/aws-sdk-js-v3.git",
  59058. directory: "clients/client-sso"
  59059. }
  59060. };
  59061. }
  59062. });
  59063. // ../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js
  59064. var require_dist_cjs39 = __commonJS({
  59065. "../node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.816.0/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js"(exports2, module2) {
  59066. "use strict";
  59067. var __defProp3 = Object.defineProperty;
  59068. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  59069. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  59070. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  59071. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  59072. var __export2 = (target, all) => {
  59073. for (var name in all)
  59074. __defProp3(target, name, { get: all[name], enumerable: true });
  59075. };
  59076. var __copyProps3 = (to, from, except, desc) => {
  59077. if (from && typeof from === "object" || typeof from === "function") {
  59078. for (let key of __getOwnPropNames3(from))
  59079. if (!__hasOwnProp3.call(to, key) && key !== except)
  59080. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  59081. }
  59082. return to;
  59083. };
  59084. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  59085. var index_exports = {};
  59086. __export2(index_exports, {
  59087. NODE_APP_ID_CONFIG_OPTIONS: () => NODE_APP_ID_CONFIG_OPTIONS3,
  59088. UA_APP_ID_ENV_NAME: () => UA_APP_ID_ENV_NAME,
  59089. UA_APP_ID_INI_NAME: () => UA_APP_ID_INI_NAME,
  59090. createDefaultUserAgentProvider: () => createDefaultUserAgentProvider3,
  59091. crtAvailability: () => crtAvailability,
  59092. defaultUserAgent: () => defaultUserAgent
  59093. });
  59094. module2.exports = __toCommonJS2(index_exports);
  59095. var import_os = require("os");
  59096. var import_process = require("process");
  59097. var crtAvailability = {
  59098. isCrtAvailable: false
  59099. };
  59100. var isCrtAvailable = /* @__PURE__ */ __name(() => {
  59101. if (crtAvailability.isCrtAvailable) {
  59102. return ["md/crt-avail"];
  59103. }
  59104. return null;
  59105. }, "isCrtAvailable");
  59106. var createDefaultUserAgentProvider3 = /* @__PURE__ */ __name(({ serviceId, clientVersion }) => {
  59107. return async (config) => {
  59108. var _a2;
  59109. const sections = [
  59110. // sdk-metadata
  59111. ["aws-sdk-js", clientVersion],
  59112. // ua-metadata
  59113. ["ua", "2.1"],
  59114. // os-metadata
  59115. [`os/${(0, import_os.platform)()}`, (0, import_os.release)()],
  59116. // language-metadata
  59117. // ECMAScript edition doesn't matter in JS, so no version needed.
  59118. ["lang/js"],
  59119. ["md/nodejs", `${import_process.versions.node}`]
  59120. ];
  59121. const crtAvailable = isCrtAvailable();
  59122. if (crtAvailable) {
  59123. sections.push(crtAvailable);
  59124. }
  59125. if (serviceId) {
  59126. sections.push([`api/${serviceId}`, clientVersion]);
  59127. }
  59128. if (import_process.env.AWS_EXECUTION_ENV) {
  59129. sections.push([`exec-env/${import_process.env.AWS_EXECUTION_ENV}`]);
  59130. }
  59131. const appId = await ((_a2 = config == null ? void 0 : config.userAgentAppId) == null ? void 0 : _a2.call(config));
  59132. const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections];
  59133. return resolvedUserAgent;
  59134. };
  59135. }, "createDefaultUserAgentProvider");
  59136. var defaultUserAgent = createDefaultUserAgentProvider3;
  59137. var import_middleware_user_agent3 = require_dist_cjs24();
  59138. var UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID";
  59139. var UA_APP_ID_INI_NAME = "sdk_ua_app_id";
  59140. var UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id";
  59141. var NODE_APP_ID_CONFIG_OPTIONS3 = {
  59142. environmentVariableSelector: /* @__PURE__ */ __name((env22) => env22[UA_APP_ID_ENV_NAME], "environmentVariableSelector"),
  59143. configFileSelector: /* @__PURE__ */ __name((profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], "configFileSelector"),
  59144. default: import_middleware_user_agent3.DEFAULT_UA_APP_ID
  59145. };
  59146. }
  59147. });
  59148. // ../node_modules/.pnpm/@smithy+hash-node@4.0.4/node_modules/@smithy/hash-node/dist-cjs/index.js
  59149. var require_dist_cjs40 = __commonJS({
  59150. "../node_modules/.pnpm/@smithy+hash-node@4.0.4/node_modules/@smithy/hash-node/dist-cjs/index.js"(exports2, module2) {
  59151. var __defProp3 = Object.defineProperty;
  59152. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  59153. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  59154. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  59155. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  59156. var __export2 = (target, all) => {
  59157. for (var name in all)
  59158. __defProp3(target, name, { get: all[name], enumerable: true });
  59159. };
  59160. var __copyProps3 = (to, from, except, desc) => {
  59161. if (from && typeof from === "object" || typeof from === "function") {
  59162. for (let key of __getOwnPropNames3(from))
  59163. if (!__hasOwnProp3.call(to, key) && key !== except)
  59164. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  59165. }
  59166. return to;
  59167. };
  59168. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  59169. var src_exports = {};
  59170. __export2(src_exports, {
  59171. Hash: () => Hash3
  59172. });
  59173. module2.exports = __toCommonJS2(src_exports);
  59174. var import_util_buffer_from = require_dist_cjs9();
  59175. var import_util_utf85 = require_dist_cjs10();
  59176. var import_buffer2 = require("buffer");
  59177. var import_crypto10 = require("crypto");
  59178. var _a2;
  59179. var Hash3 = (_a2 = class {
  59180. constructor(algorithmIdentifier, secret) {
  59181. this.algorithmIdentifier = algorithmIdentifier;
  59182. this.secret = secret;
  59183. this.reset();
  59184. }
  59185. update(toHash, encoding) {
  59186. this.hash.update((0, import_util_utf85.toUint8Array)(castSourceData(toHash, encoding)));
  59187. }
  59188. digest() {
  59189. return Promise.resolve(this.hash.digest());
  59190. }
  59191. reset() {
  59192. this.hash = this.secret ? (0, import_crypto10.createHmac)(this.algorithmIdentifier, castSourceData(this.secret)) : (0, import_crypto10.createHash)(this.algorithmIdentifier);
  59193. }
  59194. }, __name(_a2, "Hash"), _a2);
  59195. function castSourceData(toCast, encoding) {
  59196. if (import_buffer2.Buffer.isBuffer(toCast)) {
  59197. return toCast;
  59198. }
  59199. if (typeof toCast === "string") {
  59200. return (0, import_util_buffer_from.fromString)(toCast, encoding);
  59201. }
  59202. if (ArrayBuffer.isView(toCast)) {
  59203. return (0, import_util_buffer_from.fromArrayBuffer)(toCast.buffer, toCast.byteOffset, toCast.byteLength);
  59204. }
  59205. return (0, import_util_buffer_from.fromArrayBuffer)(toCast);
  59206. }
  59207. __name(castSourceData, "castSourceData");
  59208. }
  59209. });
  59210. // ../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-cjs/index.js
  59211. var require_dist_cjs41 = __commonJS({
  59212. "../node_modules/.pnpm/@smithy+util-body-length-node@4.0.0/node_modules/@smithy/util-body-length-node/dist-cjs/index.js"(exports2, module2) {
  59213. var __defProp3 = Object.defineProperty;
  59214. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  59215. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  59216. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  59217. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  59218. var __export2 = (target, all) => {
  59219. for (var name in all)
  59220. __defProp3(target, name, { get: all[name], enumerable: true });
  59221. };
  59222. var __copyProps3 = (to, from, except, desc) => {
  59223. if (from && typeof from === "object" || typeof from === "function") {
  59224. for (let key of __getOwnPropNames3(from))
  59225. if (!__hasOwnProp3.call(to, key) && key !== except)
  59226. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  59227. }
  59228. return to;
  59229. };
  59230. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  59231. var src_exports = {};
  59232. __export2(src_exports, {
  59233. calculateBodyLength: () => calculateBodyLength3
  59234. });
  59235. module2.exports = __toCommonJS2(src_exports);
  59236. var import_fs14 = require("fs");
  59237. var calculateBodyLength3 = /* @__PURE__ */ __name((body) => {
  59238. if (!body) {
  59239. return 0;
  59240. }
  59241. if (typeof body === "string") {
  59242. return Buffer.byteLength(body);
  59243. } else if (typeof body.byteLength === "number") {
  59244. return body.byteLength;
  59245. } else if (typeof body.size === "number") {
  59246. return body.size;
  59247. } else if (typeof body.start === "number" && typeof body.end === "number") {
  59248. return body.end + 1 - body.start;
  59249. } else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) {
  59250. return (0, import_fs14.lstatSync)(body.path).size;
  59251. } else if (typeof body.fd === "number") {
  59252. return (0, import_fs14.fstatSync)(body.fd).size;
  59253. }
  59254. throw new Error(`Body Length computation failed for ${body}`);
  59255. }, "calculateBodyLength");
  59256. }
  59257. });
  59258. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js
  59259. var require_ruleset = __commonJS({
  59260. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js"(exports2) {
  59261. "use strict";
  59262. Object.defineProperty(exports2, "__esModule", { value: true });
  59263. exports2.ruleSet = void 0;
  59264. var u3 = "required";
  59265. var v6 = "fn";
  59266. var w3 = "argv";
  59267. var x4 = "ref";
  59268. var a3 = true;
  59269. var b3 = "isSet";
  59270. var c3 = "booleanEquals";
  59271. var d3 = "error";
  59272. var e4 = "endpoint";
  59273. var f5 = "tree";
  59274. var g3 = "PartitionResult";
  59275. var h4 = "getAttr";
  59276. var i4 = { [u3]: false, "type": "String" };
  59277. var j3 = { [u3]: true, "default": false, "type": "Boolean" };
  59278. var k3 = { [x4]: "Endpoint" };
  59279. var l3 = { [v6]: c3, [w3]: [{ [x4]: "UseFIPS" }, true] };
  59280. var m4 = { [v6]: c3, [w3]: [{ [x4]: "UseDualStack" }, true] };
  59281. var n3 = {};
  59282. var o3 = { [v6]: h4, [w3]: [{ [x4]: g3 }, "supportsFIPS"] };
  59283. var p3 = { [x4]: g3 };
  59284. var q3 = { [v6]: c3, [w3]: [true, { [v6]: h4, [w3]: [p3, "supportsDualStack"] }] };
  59285. var r4 = [l3];
  59286. var s4 = [m4];
  59287. var t4 = [{ [x4]: "Region" }];
  59288. var _data3 = { version: "1.0", parameters: { Region: i4, UseDualStack: j3, UseFIPS: j3, Endpoint: i4 }, rules: [{ conditions: [{ [v6]: b3, [w3]: [k3] }], rules: [{ conditions: r4, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d3 }, { conditions: s4, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d3 }, { endpoint: { url: k3, properties: n3, headers: n3 }, type: e4 }], type: f5 }, { conditions: [{ [v6]: b3, [w3]: t4 }], rules: [{ conditions: [{ [v6]: "aws.partition", [w3]: t4, assign: g3 }], rules: [{ conditions: [l3, m4], rules: [{ conditions: [{ [v6]: c3, [w3]: [a3, o3] }, q3], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f5 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d3 }], type: f5 }, { conditions: r4, rules: [{ conditions: [{ [v6]: c3, [w3]: [o3, a3] }], rules: [{ conditions: [{ [v6]: "stringEquals", [w3]: [{ [v6]: h4, [w3]: [p3, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n3, headers: n3 }, type: e4 }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f5 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d3 }], type: f5 }, { conditions: s4, rules: [{ conditions: [q3], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f5 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d3 }], type: f5 }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n3, headers: n3 }, type: e4 }], type: f5 }], type: f5 }, { error: "Invalid Configuration: Missing Region", type: d3 }] };
  59289. exports2.ruleSet = _data3;
  59290. }
  59291. });
  59292. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js
  59293. var require_endpointResolver = __commonJS({
  59294. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js"(exports2) {
  59295. "use strict";
  59296. Object.defineProperty(exports2, "__esModule", { value: true });
  59297. exports2.defaultEndpointResolver = void 0;
  59298. var util_endpoints_1 = require_dist_cjs19();
  59299. var util_endpoints_2 = require_dist_cjs18();
  59300. var ruleset_1 = require_ruleset();
  59301. var cache3 = new util_endpoints_2.EndpointCache({
  59302. size: 50,
  59303. params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
  59304. });
  59305. var defaultEndpointResolver3 = (endpointParams, context = {}) => {
  59306. return cache3.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
  59307. endpointParams,
  59308. logger: context.logger
  59309. }));
  59310. };
  59311. exports2.defaultEndpointResolver = defaultEndpointResolver3;
  59312. util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
  59313. }
  59314. });
  59315. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js
  59316. var require_runtimeConfig_shared = __commonJS({
  59317. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js"(exports2) {
  59318. "use strict";
  59319. Object.defineProperty(exports2, "__esModule", { value: true });
  59320. exports2.getRuntimeConfig = void 0;
  59321. var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
  59322. var core_2 = (init_dist_es(), __toCommonJS(dist_es_exports));
  59323. var smithy_client_1 = require_dist_cjs23();
  59324. var url_parser_1 = require_dist_cjs31();
  59325. var util_base64_1 = require_dist_cjs11();
  59326. var util_utf8_1 = require_dist_cjs10();
  59327. var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider2();
  59328. var endpointResolver_1 = require_endpointResolver();
  59329. var getRuntimeConfig5 = (config) => {
  59330. return {
  59331. apiVersion: "2019-06-10",
  59332. base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? util_base64_1.fromBase64,
  59333. base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? util_base64_1.toBase64,
  59334. disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
  59335. endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? endpointResolver_1.defaultEndpointResolver,
  59336. extensions: (config == null ? void 0 : config.extensions) ?? [],
  59337. httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? httpAuthSchemeProvider_1.defaultSSOHttpAuthSchemeProvider,
  59338. httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
  59339. {
  59340. schemeId: "aws.auth#sigv4",
  59341. identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
  59342. signer: new core_1.AwsSdkSigV4Signer()
  59343. },
  59344. {
  59345. schemeId: "smithy.api#noAuth",
  59346. identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
  59347. signer: new core_2.NoAuthSigner()
  59348. }
  59349. ],
  59350. logger: (config == null ? void 0 : config.logger) ?? new smithy_client_1.NoOpLogger(),
  59351. serviceId: (config == null ? void 0 : config.serviceId) ?? "SSO",
  59352. urlParser: (config == null ? void 0 : config.urlParser) ?? url_parser_1.parseUrl,
  59353. utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? util_utf8_1.fromUtf8,
  59354. utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? util_utf8_1.toUtf8
  59355. };
  59356. };
  59357. exports2.getRuntimeConfig = getRuntimeConfig5;
  59358. }
  59359. });
  59360. // ../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js
  59361. var require_dist_cjs42 = __commonJS({
  59362. "../node_modules/.pnpm/@smithy+util-defaults-mode-node@4.0.17/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js"(exports2, module2) {
  59363. var __create3 = Object.create;
  59364. var __defProp3 = Object.defineProperty;
  59365. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  59366. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  59367. var __getProtoOf3 = Object.getPrototypeOf;
  59368. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  59369. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  59370. var __export2 = (target, all) => {
  59371. for (var name in all)
  59372. __defProp3(target, name, { get: all[name], enumerable: true });
  59373. };
  59374. var __copyProps3 = (to, from, except, desc) => {
  59375. if (from && typeof from === "object" || typeof from === "function") {
  59376. for (let key of __getOwnPropNames3(from))
  59377. if (!__hasOwnProp3.call(to, key) && key !== except)
  59378. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  59379. }
  59380. return to;
  59381. };
  59382. var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
  59383. // If the importer is in node compatibility mode or this is not an ESM
  59384. // file that has been converted to a CommonJS file using a Babel-
  59385. // compatible transform (i.e. "__esModule" has not been set), then set
  59386. // "default" to the CommonJS "module.exports" for node compatibility.
  59387. isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
  59388. mod
  59389. ));
  59390. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  59391. var src_exports = {};
  59392. __export2(src_exports, {
  59393. resolveDefaultsModeConfig: () => resolveDefaultsModeConfig3
  59394. });
  59395. module2.exports = __toCommonJS2(src_exports);
  59396. var import_config_resolver5 = require_dist_cjs26();
  59397. var import_node_config_provider3 = require_dist_cjs29();
  59398. var import_property_provider2 = require_dist_cjs20();
  59399. var AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV";
  59400. var AWS_REGION_ENV = "AWS_REGION";
  59401. var AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION";
  59402. var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
  59403. var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"];
  59404. var IMDS_REGION_PATH = "/latest/meta-data/placement/region";
  59405. var AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE";
  59406. var AWS_DEFAULTS_MODE_CONFIG = "defaults_mode";
  59407. var NODE_DEFAULTS_MODE_CONFIG_OPTIONS = {
  59408. environmentVariableSelector: (env3) => {
  59409. return env3[AWS_DEFAULTS_MODE_ENV];
  59410. },
  59411. configFileSelector: (profile) => {
  59412. return profile[AWS_DEFAULTS_MODE_CONFIG];
  59413. },
  59414. default: "legacy"
  59415. };
  59416. var resolveDefaultsModeConfig3 = /* @__PURE__ */ __name(({
  59417. region = (0, import_node_config_provider3.loadConfig)(import_config_resolver5.NODE_REGION_CONFIG_OPTIONS),
  59418. defaultsMode = (0, import_node_config_provider3.loadConfig)(NODE_DEFAULTS_MODE_CONFIG_OPTIONS)
  59419. } = {}) => (0, import_property_provider2.memoize)(async () => {
  59420. const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode;
  59421. switch (mode == null ? void 0 : mode.toLowerCase()) {
  59422. case "auto":
  59423. return resolveNodeDefaultsModeAuto(region);
  59424. case "in-region":
  59425. case "cross-region":
  59426. case "mobile":
  59427. case "standard":
  59428. case "legacy":
  59429. return Promise.resolve(mode == null ? void 0 : mode.toLocaleLowerCase());
  59430. case void 0:
  59431. return Promise.resolve("legacy");
  59432. default:
  59433. throw new Error(
  59434. `Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`
  59435. );
  59436. }
  59437. }), "resolveDefaultsModeConfig");
  59438. var resolveNodeDefaultsModeAuto = /* @__PURE__ */ __name(async (clientRegion) => {
  59439. if (clientRegion) {
  59440. const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion;
  59441. const inferredRegion = await inferPhysicalRegion();
  59442. if (!inferredRegion) {
  59443. return "standard";
  59444. }
  59445. if (resolvedRegion === inferredRegion) {
  59446. return "in-region";
  59447. } else {
  59448. return "cross-region";
  59449. }
  59450. }
  59451. return "standard";
  59452. }, "resolveNodeDefaultsModeAuto");
  59453. var inferPhysicalRegion = /* @__PURE__ */ __name(async () => {
  59454. if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) {
  59455. return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV];
  59456. }
  59457. if (!process.env[ENV_IMDS_DISABLED]) {
  59458. try {
  59459. const { getInstanceMetadataEndpoint, httpRequest } = await Promise.resolve().then(() => __toESM3(require_dist_cjs37()));
  59460. const endpoint = await getInstanceMetadataEndpoint();
  59461. return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString();
  59462. } catch (e4) {
  59463. }
  59464. }
  59465. }, "inferPhysicalRegion");
  59466. }
  59467. });
  59468. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js
  59469. var require_runtimeConfig = __commonJS({
  59470. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js"(exports2) {
  59471. "use strict";
  59472. Object.defineProperty(exports2, "__esModule", { value: true });
  59473. exports2.getRuntimeConfig = void 0;
  59474. var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
  59475. var package_json_1 = tslib_1.__importDefault(require_package3());
  59476. var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
  59477. var util_user_agent_node_1 = require_dist_cjs39();
  59478. var config_resolver_1 = require_dist_cjs26();
  59479. var hash_node_1 = require_dist_cjs40();
  59480. var middleware_retry_1 = require_dist_cjs35();
  59481. var node_config_provider_1 = require_dist_cjs29();
  59482. var node_http_handler_1 = require_dist_cjs14();
  59483. var util_body_length_node_1 = require_dist_cjs41();
  59484. var util_retry_1 = require_dist_cjs34();
  59485. var runtimeConfig_shared_1 = require_runtimeConfig_shared();
  59486. var smithy_client_1 = require_dist_cjs23();
  59487. var util_defaults_mode_node_1 = require_dist_cjs42();
  59488. var smithy_client_2 = require_dist_cjs23();
  59489. var getRuntimeConfig5 = (config) => {
  59490. (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version);
  59491. const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config);
  59492. const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
  59493. const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config);
  59494. (0, core_1.emitWarningIfUnsupportedVersion)(process.version);
  59495. const loaderConfig = {
  59496. profile: config == null ? void 0 : config.profile,
  59497. logger: clientSharedValues.logger
  59498. };
  59499. return {
  59500. ...clientSharedValues,
  59501. ...config,
  59502. runtime: "node",
  59503. defaultsMode,
  59504. authSchemePreference: (config == null ? void 0 : config.authSchemePreference) ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
  59505. bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? util_body_length_node_1.calculateBodyLength,
  59506. defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
  59507. maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
  59508. region: (config == null ? void 0 : config.region) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
  59509. requestHandler: node_http_handler_1.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
  59510. retryMode: (config == null ? void 0 : config.retryMode) ?? (0, node_config_provider_1.loadConfig)({
  59511. ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
  59512. default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
  59513. }, config),
  59514. sha256: (config == null ? void 0 : config.sha256) ?? hash_node_1.Hash.bind(null, "sha256"),
  59515. streamCollector: (config == null ? void 0 : config.streamCollector) ?? node_http_handler_1.streamCollector,
  59516. useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  59517. useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  59518. userAgentAppId: (config == null ? void 0 : config.userAgentAppId) ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
  59519. };
  59520. };
  59521. exports2.getRuntimeConfig = getRuntimeConfig5;
  59522. }
  59523. });
  59524. // ../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js
  59525. var require_dist_cjs43 = __commonJS({
  59526. "../node_modules/.pnpm/@aws-sdk+region-config-resolver@3.808.0/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js"(exports2, module2) {
  59527. "use strict";
  59528. var __defProp3 = Object.defineProperty;
  59529. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  59530. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  59531. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  59532. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  59533. var __export2 = (target, all) => {
  59534. for (var name in all)
  59535. __defProp3(target, name, { get: all[name], enumerable: true });
  59536. };
  59537. var __copyProps3 = (to, from, except, desc) => {
  59538. if (from && typeof from === "object" || typeof from === "function") {
  59539. for (let key of __getOwnPropNames3(from))
  59540. if (!__hasOwnProp3.call(to, key) && key !== except)
  59541. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  59542. }
  59543. return to;
  59544. };
  59545. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  59546. var index_exports = {};
  59547. __export2(index_exports, {
  59548. NODE_REGION_CONFIG_FILE_OPTIONS: () => NODE_REGION_CONFIG_FILE_OPTIONS3,
  59549. NODE_REGION_CONFIG_OPTIONS: () => NODE_REGION_CONFIG_OPTIONS3,
  59550. REGION_ENV_NAME: () => REGION_ENV_NAME,
  59551. REGION_INI_NAME: () => REGION_INI_NAME,
  59552. getAwsRegionExtensionConfiguration: () => getAwsRegionExtensionConfiguration3,
  59553. resolveAwsRegionExtensionConfiguration: () => resolveAwsRegionExtensionConfiguration3,
  59554. resolveRegionConfig: () => resolveRegionConfig3
  59555. });
  59556. module2.exports = __toCommonJS2(index_exports);
  59557. var getAwsRegionExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
  59558. return {
  59559. setRegion(region) {
  59560. runtimeConfig.region = region;
  59561. },
  59562. region() {
  59563. return runtimeConfig.region;
  59564. }
  59565. };
  59566. }, "getAwsRegionExtensionConfiguration");
  59567. var resolveAwsRegionExtensionConfiguration3 = /* @__PURE__ */ __name((awsRegionExtensionConfiguration) => {
  59568. return {
  59569. region: awsRegionExtensionConfiguration.region()
  59570. };
  59571. }, "resolveAwsRegionExtensionConfiguration");
  59572. var REGION_ENV_NAME = "AWS_REGION";
  59573. var REGION_INI_NAME = "region";
  59574. var NODE_REGION_CONFIG_OPTIONS3 = {
  59575. environmentVariableSelector: /* @__PURE__ */ __name((env3) => env3[REGION_ENV_NAME], "environmentVariableSelector"),
  59576. configFileSelector: /* @__PURE__ */ __name((profile) => profile[REGION_INI_NAME], "configFileSelector"),
  59577. default: /* @__PURE__ */ __name(() => {
  59578. throw new Error("Region is missing");
  59579. }, "default")
  59580. };
  59581. var NODE_REGION_CONFIG_FILE_OPTIONS3 = {
  59582. preferredFile: "credentials"
  59583. };
  59584. var isFipsRegion = /* @__PURE__ */ __name((region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")), "isFipsRegion");
  59585. var getRealRegion = /* @__PURE__ */ __name((region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region, "getRealRegion");
  59586. var resolveRegionConfig3 = /* @__PURE__ */ __name((input) => {
  59587. const { region, useFipsEndpoint } = input;
  59588. if (!region) {
  59589. throw new Error("Region is missing");
  59590. }
  59591. return Object.assign(input, {
  59592. region: /* @__PURE__ */ __name(async () => {
  59593. if (typeof region === "string") {
  59594. return getRealRegion(region);
  59595. }
  59596. const providedRegion = await region();
  59597. return getRealRegion(providedRegion);
  59598. }, "region"),
  59599. useFipsEndpoint: /* @__PURE__ */ __name(async () => {
  59600. const providedRegion = typeof region === "string" ? region : await region();
  59601. if (isFipsRegion(providedRegion)) {
  59602. return true;
  59603. }
  59604. return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
  59605. }, "useFipsEndpoint")
  59606. });
  59607. }, "resolveRegionConfig");
  59608. }
  59609. });
  59610. // ../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/index.js
  59611. var require_dist_cjs44 = __commonJS({
  59612. "../node_modules/.pnpm/@aws-sdk+client-sso@3.817.0/node_modules/@aws-sdk/client-sso/dist-cjs/index.js"(exports2, module2) {
  59613. "use strict";
  59614. var __defProp3 = Object.defineProperty;
  59615. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  59616. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  59617. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  59618. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  59619. var __export2 = (target, all) => {
  59620. for (var name in all)
  59621. __defProp3(target, name, { get: all[name], enumerable: true });
  59622. };
  59623. var __copyProps3 = (to, from, except, desc) => {
  59624. if (from && typeof from === "object" || typeof from === "function") {
  59625. for (let key of __getOwnPropNames3(from))
  59626. if (!__hasOwnProp3.call(to, key) && key !== except)
  59627. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  59628. }
  59629. return to;
  59630. };
  59631. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  59632. var index_exports = {};
  59633. __export2(index_exports, {
  59634. GetRoleCredentialsCommand: () => GetRoleCredentialsCommand,
  59635. GetRoleCredentialsRequestFilterSensitiveLog: () => GetRoleCredentialsRequestFilterSensitiveLog,
  59636. GetRoleCredentialsResponseFilterSensitiveLog: () => GetRoleCredentialsResponseFilterSensitiveLog,
  59637. InvalidRequestException: () => InvalidRequestException2,
  59638. ListAccountRolesCommand: () => ListAccountRolesCommand,
  59639. ListAccountRolesRequestFilterSensitiveLog: () => ListAccountRolesRequestFilterSensitiveLog,
  59640. ListAccountsCommand: () => ListAccountsCommand,
  59641. ListAccountsRequestFilterSensitiveLog: () => ListAccountsRequestFilterSensitiveLog,
  59642. LogoutCommand: () => LogoutCommand,
  59643. LogoutRequestFilterSensitiveLog: () => LogoutRequestFilterSensitiveLog,
  59644. ResourceNotFoundException: () => ResourceNotFoundException,
  59645. RoleCredentialsFilterSensitiveLog: () => RoleCredentialsFilterSensitiveLog,
  59646. SSO: () => SSO,
  59647. SSOClient: () => SSOClient,
  59648. SSOServiceException: () => SSOServiceException,
  59649. TooManyRequestsException: () => TooManyRequestsException,
  59650. UnauthorizedException: () => UnauthorizedException,
  59651. __Client: () => import_smithy_client25.Client,
  59652. paginateListAccountRoles: () => paginateListAccountRoles,
  59653. paginateListAccounts: () => paginateListAccounts
  59654. });
  59655. module2.exports = __toCommonJS2(index_exports);
  59656. var import_middleware_host_header3 = require_dist_cjs3();
  59657. var import_middleware_logger3 = require_dist_cjs4();
  59658. var import_middleware_recursion_detection3 = require_dist_cjs5();
  59659. var import_middleware_user_agent3 = require_dist_cjs24();
  59660. var import_config_resolver5 = require_dist_cjs26();
  59661. var import_core17 = (init_dist_es(), __toCommonJS(dist_es_exports));
  59662. var import_middleware_content_length3 = require_dist_cjs27();
  59663. var import_middleware_endpoint6 = require_dist_cjs32();
  59664. var import_middleware_retry5 = require_dist_cjs35();
  59665. var import_httpAuthSchemeProvider5 = require_httpAuthSchemeProvider2();
  59666. var resolveClientEndpointParameters3 = /* @__PURE__ */ __name((options) => {
  59667. return Object.assign(options, {
  59668. useDualstackEndpoint: options.useDualstackEndpoint ?? false,
  59669. useFipsEndpoint: options.useFipsEndpoint ?? false,
  59670. defaultSigningName: "awsssoportal"
  59671. });
  59672. }, "resolveClientEndpointParameters");
  59673. var commonParams3 = {
  59674. UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
  59675. Endpoint: { type: "builtInParams", name: "endpoint" },
  59676. Region: { type: "builtInParams", name: "region" },
  59677. UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
  59678. };
  59679. var import_runtimeConfig5 = require_runtimeConfig();
  59680. var import_region_config_resolver3 = require_dist_cjs43();
  59681. var import_protocol_http15 = require_dist_cjs2();
  59682. var import_smithy_client25 = require_dist_cjs23();
  59683. var getHttpAuthExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
  59684. const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
  59685. let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
  59686. let _credentials = runtimeConfig.credentials;
  59687. return {
  59688. setHttpAuthScheme(httpAuthScheme) {
  59689. const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
  59690. if (index6 === -1) {
  59691. _httpAuthSchemes.push(httpAuthScheme);
  59692. } else {
  59693. _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
  59694. }
  59695. },
  59696. httpAuthSchemes() {
  59697. return _httpAuthSchemes;
  59698. },
  59699. setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
  59700. _httpAuthSchemeProvider = httpAuthSchemeProvider;
  59701. },
  59702. httpAuthSchemeProvider() {
  59703. return _httpAuthSchemeProvider;
  59704. },
  59705. setCredentials(credentials2) {
  59706. _credentials = credentials2;
  59707. },
  59708. credentials() {
  59709. return _credentials;
  59710. }
  59711. };
  59712. }, "getHttpAuthExtensionConfiguration");
  59713. var resolveHttpAuthRuntimeConfig3 = /* @__PURE__ */ __name((config) => {
  59714. return {
  59715. httpAuthSchemes: config.httpAuthSchemes(),
  59716. httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
  59717. credentials: config.credentials()
  59718. };
  59719. }, "resolveHttpAuthRuntimeConfig");
  59720. var resolveRuntimeExtensions3 = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
  59721. const extensionConfiguration = Object.assign(
  59722. (0, import_region_config_resolver3.getAwsRegionExtensionConfiguration)(runtimeConfig),
  59723. (0, import_smithy_client25.getDefaultExtensionConfiguration)(runtimeConfig),
  59724. (0, import_protocol_http15.getHttpHandlerExtensionConfiguration)(runtimeConfig),
  59725. getHttpAuthExtensionConfiguration3(runtimeConfig)
  59726. );
  59727. extensions.forEach((extension) => extension.configure(extensionConfiguration));
  59728. return Object.assign(
  59729. runtimeConfig,
  59730. (0, import_region_config_resolver3.resolveAwsRegionExtensionConfiguration)(extensionConfiguration),
  59731. (0, import_smithy_client25.resolveDefaultRuntimeConfig)(extensionConfiguration),
  59732. (0, import_protocol_http15.resolveHttpHandlerRuntimeConfig)(extensionConfiguration),
  59733. resolveHttpAuthRuntimeConfig3(extensionConfiguration)
  59734. );
  59735. }, "resolveRuntimeExtensions");
  59736. var _a2;
  59737. var SSOClient = (_a2 = class extends import_smithy_client25.Client {
  59738. /**
  59739. * The resolved configuration of SSOClient class. This is resolved and normalized from the {@link SSOClientConfig | constructor configuration interface}.
  59740. */
  59741. config;
  59742. constructor(...[configuration]) {
  59743. const _config_0 = (0, import_runtimeConfig5.getRuntimeConfig)(configuration || {});
  59744. super(_config_0);
  59745. this.initConfig = _config_0;
  59746. const _config_1 = resolveClientEndpointParameters3(_config_0);
  59747. const _config_2 = (0, import_middleware_user_agent3.resolveUserAgentConfig)(_config_1);
  59748. const _config_3 = (0, import_middleware_retry5.resolveRetryConfig)(_config_2);
  59749. const _config_4 = (0, import_config_resolver5.resolveRegionConfig)(_config_3);
  59750. const _config_5 = (0, import_middleware_host_header3.resolveHostHeaderConfig)(_config_4);
  59751. const _config_6 = (0, import_middleware_endpoint6.resolveEndpointConfig)(_config_5);
  59752. const _config_7 = (0, import_httpAuthSchemeProvider5.resolveHttpAuthSchemeConfig)(_config_6);
  59753. const _config_8 = resolveRuntimeExtensions3(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
  59754. this.config = _config_8;
  59755. this.middlewareStack.use((0, import_middleware_user_agent3.getUserAgentPlugin)(this.config));
  59756. this.middlewareStack.use((0, import_middleware_retry5.getRetryPlugin)(this.config));
  59757. this.middlewareStack.use((0, import_middleware_content_length3.getContentLengthPlugin)(this.config));
  59758. this.middlewareStack.use((0, import_middleware_host_header3.getHostHeaderPlugin)(this.config));
  59759. this.middlewareStack.use((0, import_middleware_logger3.getLoggerPlugin)(this.config));
  59760. this.middlewareStack.use((0, import_middleware_recursion_detection3.getRecursionDetectionPlugin)(this.config));
  59761. this.middlewareStack.use(
  59762. (0, import_core17.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, {
  59763. httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider5.defaultSSOHttpAuthSchemeParametersProvider,
  59764. identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core17.DefaultIdentityProviderConfig({
  59765. "aws.auth#sigv4": config.credentials
  59766. }), "identityProviderConfigProvider")
  59767. })
  59768. );
  59769. this.middlewareStack.use((0, import_core17.getHttpSigningPlugin)(this.config));
  59770. }
  59771. /**
  59772. * Destroy underlying resources, like sockets. It's usually not necessary to do this.
  59773. * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
  59774. * Otherwise, sockets might stay open for quite a long time before the server terminates them.
  59775. */
  59776. destroy() {
  59777. super.destroy();
  59778. }
  59779. }, __name(_a2, "SSOClient"), _a2);
  59780. var import_middleware_serde5 = require_dist_cjs7();
  59781. var _a3;
  59782. var SSOServiceException = (_a3 = class extends import_smithy_client25.ServiceException {
  59783. /**
  59784. * @internal
  59785. */
  59786. constructor(options) {
  59787. super(options);
  59788. Object.setPrototypeOf(this, _a3.prototype);
  59789. }
  59790. }, __name(_a3, "SSOServiceException"), _a3);
  59791. var _a4;
  59792. var InvalidRequestException2 = (_a4 = class extends SSOServiceException {
  59793. name = "InvalidRequestException";
  59794. $fault = "client";
  59795. /**
  59796. * @internal
  59797. */
  59798. constructor(opts) {
  59799. super({
  59800. name: "InvalidRequestException",
  59801. $fault: "client",
  59802. ...opts
  59803. });
  59804. Object.setPrototypeOf(this, _a4.prototype);
  59805. }
  59806. }, __name(_a4, "InvalidRequestException"), _a4);
  59807. var _a5;
  59808. var ResourceNotFoundException = (_a5 = class extends SSOServiceException {
  59809. name = "ResourceNotFoundException";
  59810. $fault = "client";
  59811. /**
  59812. * @internal
  59813. */
  59814. constructor(opts) {
  59815. super({
  59816. name: "ResourceNotFoundException",
  59817. $fault: "client",
  59818. ...opts
  59819. });
  59820. Object.setPrototypeOf(this, _a5.prototype);
  59821. }
  59822. }, __name(_a5, "ResourceNotFoundException"), _a5);
  59823. var _a6;
  59824. var TooManyRequestsException = (_a6 = class extends SSOServiceException {
  59825. name = "TooManyRequestsException";
  59826. $fault = "client";
  59827. /**
  59828. * @internal
  59829. */
  59830. constructor(opts) {
  59831. super({
  59832. name: "TooManyRequestsException",
  59833. $fault: "client",
  59834. ...opts
  59835. });
  59836. Object.setPrototypeOf(this, _a6.prototype);
  59837. }
  59838. }, __name(_a6, "TooManyRequestsException"), _a6);
  59839. var _a7;
  59840. var UnauthorizedException = (_a7 = class extends SSOServiceException {
  59841. name = "UnauthorizedException";
  59842. $fault = "client";
  59843. /**
  59844. * @internal
  59845. */
  59846. constructor(opts) {
  59847. super({
  59848. name: "UnauthorizedException",
  59849. $fault: "client",
  59850. ...opts
  59851. });
  59852. Object.setPrototypeOf(this, _a7.prototype);
  59853. }
  59854. }, __name(_a7, "UnauthorizedException"), _a7);
  59855. var GetRoleCredentialsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
  59856. ...obj,
  59857. ...obj.accessToken && { accessToken: import_smithy_client25.SENSITIVE_STRING }
  59858. }), "GetRoleCredentialsRequestFilterSensitiveLog");
  59859. var RoleCredentialsFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
  59860. ...obj,
  59861. ...obj.secretAccessKey && { secretAccessKey: import_smithy_client25.SENSITIVE_STRING },
  59862. ...obj.sessionToken && { sessionToken: import_smithy_client25.SENSITIVE_STRING }
  59863. }), "RoleCredentialsFilterSensitiveLog");
  59864. var GetRoleCredentialsResponseFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
  59865. ...obj,
  59866. ...obj.roleCredentials && { roleCredentials: RoleCredentialsFilterSensitiveLog(obj.roleCredentials) }
  59867. }), "GetRoleCredentialsResponseFilterSensitiveLog");
  59868. var ListAccountRolesRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
  59869. ...obj,
  59870. ...obj.accessToken && { accessToken: import_smithy_client25.SENSITIVE_STRING }
  59871. }), "ListAccountRolesRequestFilterSensitiveLog");
  59872. var ListAccountsRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
  59873. ...obj,
  59874. ...obj.accessToken && { accessToken: import_smithy_client25.SENSITIVE_STRING }
  59875. }), "ListAccountsRequestFilterSensitiveLog");
  59876. var LogoutRequestFilterSensitiveLog = /* @__PURE__ */ __name((obj) => ({
  59877. ...obj,
  59878. ...obj.accessToken && { accessToken: import_smithy_client25.SENSITIVE_STRING }
  59879. }), "LogoutRequestFilterSensitiveLog");
  59880. var import_core22 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
  59881. var se_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (input, context) => {
  59882. const b3 = (0, import_core17.requestBuilder)(input, context);
  59883. const headers = (0, import_smithy_client25.map)({}, import_smithy_client25.isSerializableHeaderValue, {
  59884. [_xasbt]: input[_aT]
  59885. });
  59886. b3.bp("/federation/credentials");
  59887. const query = (0, import_smithy_client25.map)({
  59888. [_rn]: [, (0, import_smithy_client25.expectNonNull)(input[_rN], `roleName`)],
  59889. [_ai]: [, (0, import_smithy_client25.expectNonNull)(input[_aI], `accountId`)]
  59890. });
  59891. let body;
  59892. b3.m("GET").h(headers).q(query).b(body);
  59893. return b3.build();
  59894. }, "se_GetRoleCredentialsCommand");
  59895. var se_ListAccountRolesCommand = /* @__PURE__ */ __name(async (input, context) => {
  59896. const b3 = (0, import_core17.requestBuilder)(input, context);
  59897. const headers = (0, import_smithy_client25.map)({}, import_smithy_client25.isSerializableHeaderValue, {
  59898. [_xasbt]: input[_aT]
  59899. });
  59900. b3.bp("/assignment/roles");
  59901. const query = (0, import_smithy_client25.map)({
  59902. [_nt]: [, input[_nT]],
  59903. [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()],
  59904. [_ai]: [, (0, import_smithy_client25.expectNonNull)(input[_aI], `accountId`)]
  59905. });
  59906. let body;
  59907. b3.m("GET").h(headers).q(query).b(body);
  59908. return b3.build();
  59909. }, "se_ListAccountRolesCommand");
  59910. var se_ListAccountsCommand = /* @__PURE__ */ __name(async (input, context) => {
  59911. const b3 = (0, import_core17.requestBuilder)(input, context);
  59912. const headers = (0, import_smithy_client25.map)({}, import_smithy_client25.isSerializableHeaderValue, {
  59913. [_xasbt]: input[_aT]
  59914. });
  59915. b3.bp("/assignment/accounts");
  59916. const query = (0, import_smithy_client25.map)({
  59917. [_nt]: [, input[_nT]],
  59918. [_mr]: [() => input.maxResults !== void 0, () => input[_mR].toString()]
  59919. });
  59920. let body;
  59921. b3.m("GET").h(headers).q(query).b(body);
  59922. return b3.build();
  59923. }, "se_ListAccountsCommand");
  59924. var se_LogoutCommand = /* @__PURE__ */ __name(async (input, context) => {
  59925. const b3 = (0, import_core17.requestBuilder)(input, context);
  59926. const headers = (0, import_smithy_client25.map)({}, import_smithy_client25.isSerializableHeaderValue, {
  59927. [_xasbt]: input[_aT]
  59928. });
  59929. b3.bp("/logout");
  59930. let body;
  59931. b3.m("POST").h(headers).b(body);
  59932. return b3.build();
  59933. }, "se_LogoutCommand");
  59934. var de_GetRoleCredentialsCommand = /* @__PURE__ */ __name(async (output, context) => {
  59935. if (output.statusCode !== 200 && output.statusCode >= 300) {
  59936. return de_CommandError3(output, context);
  59937. }
  59938. const contents = (0, import_smithy_client25.map)({
  59939. $metadata: deserializeMetadata3(output)
  59940. });
  59941. const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
  59942. const doc = (0, import_smithy_client25.take)(data, {
  59943. roleCredentials: import_smithy_client25._json
  59944. });
  59945. Object.assign(contents, doc);
  59946. return contents;
  59947. }, "de_GetRoleCredentialsCommand");
  59948. var de_ListAccountRolesCommand = /* @__PURE__ */ __name(async (output, context) => {
  59949. if (output.statusCode !== 200 && output.statusCode >= 300) {
  59950. return de_CommandError3(output, context);
  59951. }
  59952. const contents = (0, import_smithy_client25.map)({
  59953. $metadata: deserializeMetadata3(output)
  59954. });
  59955. const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
  59956. const doc = (0, import_smithy_client25.take)(data, {
  59957. nextToken: import_smithy_client25.expectString,
  59958. roleList: import_smithy_client25._json
  59959. });
  59960. Object.assign(contents, doc);
  59961. return contents;
  59962. }, "de_ListAccountRolesCommand");
  59963. var de_ListAccountsCommand = /* @__PURE__ */ __name(async (output, context) => {
  59964. if (output.statusCode !== 200 && output.statusCode >= 300) {
  59965. return de_CommandError3(output, context);
  59966. }
  59967. const contents = (0, import_smithy_client25.map)({
  59968. $metadata: deserializeMetadata3(output)
  59969. });
  59970. const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
  59971. const doc = (0, import_smithy_client25.take)(data, {
  59972. accountList: import_smithy_client25._json,
  59973. nextToken: import_smithy_client25.expectString
  59974. });
  59975. Object.assign(contents, doc);
  59976. return contents;
  59977. }, "de_ListAccountsCommand");
  59978. var de_LogoutCommand = /* @__PURE__ */ __name(async (output, context) => {
  59979. if (output.statusCode !== 200 && output.statusCode >= 300) {
  59980. return de_CommandError3(output, context);
  59981. }
  59982. const contents = (0, import_smithy_client25.map)({
  59983. $metadata: deserializeMetadata3(output)
  59984. });
  59985. await (0, import_smithy_client25.collectBody)(output.body, context);
  59986. return contents;
  59987. }, "de_LogoutCommand");
  59988. var de_CommandError3 = /* @__PURE__ */ __name(async (output, context) => {
  59989. const parsedOutput = {
  59990. ...output,
  59991. body: await (0, import_core22.parseJsonErrorBody)(output.body, context)
  59992. };
  59993. const errorCode = (0, import_core22.loadRestJsonErrorCode)(output, parsedOutput.body);
  59994. switch (errorCode) {
  59995. case "InvalidRequestException":
  59996. case "com.amazonaws.sso#InvalidRequestException":
  59997. throw await de_InvalidRequestExceptionRes2(parsedOutput, context);
  59998. case "ResourceNotFoundException":
  59999. case "com.amazonaws.sso#ResourceNotFoundException":
  60000. throw await de_ResourceNotFoundExceptionRes(parsedOutput, context);
  60001. case "TooManyRequestsException":
  60002. case "com.amazonaws.sso#TooManyRequestsException":
  60003. throw await de_TooManyRequestsExceptionRes(parsedOutput, context);
  60004. case "UnauthorizedException":
  60005. case "com.amazonaws.sso#UnauthorizedException":
  60006. throw await de_UnauthorizedExceptionRes(parsedOutput, context);
  60007. default:
  60008. const parsedBody = parsedOutput.body;
  60009. return throwDefaultError3({
  60010. output,
  60011. parsedBody,
  60012. errorCode
  60013. });
  60014. }
  60015. }, "de_CommandError");
  60016. var throwDefaultError3 = (0, import_smithy_client25.withBaseException)(SSOServiceException);
  60017. var de_InvalidRequestExceptionRes2 = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  60018. const contents = (0, import_smithy_client25.map)({});
  60019. const data = parsedOutput.body;
  60020. const doc = (0, import_smithy_client25.take)(data, {
  60021. message: import_smithy_client25.expectString
  60022. });
  60023. Object.assign(contents, doc);
  60024. const exception = new InvalidRequestException2({
  60025. $metadata: deserializeMetadata3(parsedOutput),
  60026. ...contents
  60027. });
  60028. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  60029. }, "de_InvalidRequestExceptionRes");
  60030. var de_ResourceNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  60031. const contents = (0, import_smithy_client25.map)({});
  60032. const data = parsedOutput.body;
  60033. const doc = (0, import_smithy_client25.take)(data, {
  60034. message: import_smithy_client25.expectString
  60035. });
  60036. Object.assign(contents, doc);
  60037. const exception = new ResourceNotFoundException({
  60038. $metadata: deserializeMetadata3(parsedOutput),
  60039. ...contents
  60040. });
  60041. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  60042. }, "de_ResourceNotFoundExceptionRes");
  60043. var de_TooManyRequestsExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  60044. const contents = (0, import_smithy_client25.map)({});
  60045. const data = parsedOutput.body;
  60046. const doc = (0, import_smithy_client25.take)(data, {
  60047. message: import_smithy_client25.expectString
  60048. });
  60049. Object.assign(contents, doc);
  60050. const exception = new TooManyRequestsException({
  60051. $metadata: deserializeMetadata3(parsedOutput),
  60052. ...contents
  60053. });
  60054. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  60055. }, "de_TooManyRequestsExceptionRes");
  60056. var de_UnauthorizedExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  60057. const contents = (0, import_smithy_client25.map)({});
  60058. const data = parsedOutput.body;
  60059. const doc = (0, import_smithy_client25.take)(data, {
  60060. message: import_smithy_client25.expectString
  60061. });
  60062. Object.assign(contents, doc);
  60063. const exception = new UnauthorizedException({
  60064. $metadata: deserializeMetadata3(parsedOutput),
  60065. ...contents
  60066. });
  60067. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  60068. }, "de_UnauthorizedExceptionRes");
  60069. var deserializeMetadata3 = /* @__PURE__ */ __name((output) => ({
  60070. httpStatusCode: output.statusCode,
  60071. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  60072. extendedRequestId: output.headers["x-amz-id-2"],
  60073. cfId: output.headers["x-amz-cf-id"]
  60074. }), "deserializeMetadata");
  60075. var _aI = "accountId";
  60076. var _aT = "accessToken";
  60077. var _ai = "account_id";
  60078. var _mR = "maxResults";
  60079. var _mr = "max_result";
  60080. var _nT = "nextToken";
  60081. var _nt = "next_token";
  60082. var _rN = "roleName";
  60083. var _rn = "role_name";
  60084. var _xasbt = "x-amz-sso_bearer_token";
  60085. var _a8;
  60086. var GetRoleCredentialsCommand = (_a8 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
  60087. return [
  60088. (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
  60089. (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  60090. ];
  60091. }).s("SWBPortalService", "GetRoleCredentials", {}).n("SSOClient", "GetRoleCredentialsCommand").f(GetRoleCredentialsRequestFilterSensitiveLog, GetRoleCredentialsResponseFilterSensitiveLog).ser(se_GetRoleCredentialsCommand).de(de_GetRoleCredentialsCommand).build() {
  60092. }, __name(_a8, "GetRoleCredentialsCommand"), _a8);
  60093. var _a9;
  60094. var ListAccountRolesCommand = (_a9 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
  60095. return [
  60096. (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
  60097. (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  60098. ];
  60099. }).s("SWBPortalService", "ListAccountRoles", {}).n("SSOClient", "ListAccountRolesCommand").f(ListAccountRolesRequestFilterSensitiveLog, void 0).ser(se_ListAccountRolesCommand).de(de_ListAccountRolesCommand).build() {
  60100. }, __name(_a9, "ListAccountRolesCommand"), _a9);
  60101. var _a10;
  60102. var ListAccountsCommand = (_a10 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
  60103. return [
  60104. (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
  60105. (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  60106. ];
  60107. }).s("SWBPortalService", "ListAccounts", {}).n("SSOClient", "ListAccountsCommand").f(ListAccountsRequestFilterSensitiveLog, void 0).ser(se_ListAccountsCommand).de(de_ListAccountsCommand).build() {
  60108. }, __name(_a10, "ListAccountsCommand"), _a10);
  60109. var _a11;
  60110. var LogoutCommand = (_a11 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
  60111. return [
  60112. (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
  60113. (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  60114. ];
  60115. }).s("SWBPortalService", "Logout", {}).n("SSOClient", "LogoutCommand").f(LogoutRequestFilterSensitiveLog, void 0).ser(se_LogoutCommand).de(de_LogoutCommand).build() {
  60116. }, __name(_a11, "LogoutCommand"), _a11);
  60117. var commands3 = {
  60118. GetRoleCredentialsCommand,
  60119. ListAccountRolesCommand,
  60120. ListAccountsCommand,
  60121. LogoutCommand
  60122. };
  60123. var _a12;
  60124. var SSO = (_a12 = class extends SSOClient {
  60125. }, __name(_a12, "SSO"), _a12);
  60126. (0, import_smithy_client25.createAggregatedClient)(commands3, SSO);
  60127. var paginateListAccountRoles = (0, import_core17.createPaginator)(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults");
  60128. var paginateListAccounts = (0, import_core17.createPaginator)(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults");
  60129. }
  60130. });
  60131. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js
  60132. function createAwsAuthSigv4HttpAuthOption(authParameters) {
  60133. return {
  60134. schemeId: "aws.auth#sigv4",
  60135. signingProperties: {
  60136. name: "sso-oauth",
  60137. region: authParameters.region
  60138. },
  60139. propertiesExtractor: (config, context) => ({
  60140. signingProperties: {
  60141. config,
  60142. context
  60143. }
  60144. })
  60145. };
  60146. }
  60147. function createSmithyApiNoAuthHttpAuthOption(authParameters) {
  60148. return {
  60149. schemeId: "smithy.api#noAuth"
  60150. };
  60151. }
  60152. var import_util_middleware5, defaultSSOOIDCHttpAuthSchemeParametersProvider, defaultSSOOIDCHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig;
  60153. var init_httpAuthSchemeProvider = __esm({
  60154. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js"() {
  60155. init_dist_es2();
  60156. import_util_middleware5 = __toESM(require_dist_cjs6());
  60157. defaultSSOOIDCHttpAuthSchemeParametersProvider = async (config, context, input) => {
  60158. return {
  60159. operation: (0, import_util_middleware5.getSmithyContext)(context).operation,
  60160. region: await (0, import_util_middleware5.normalizeProvider)(config.region)() || (() => {
  60161. throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
  60162. })()
  60163. };
  60164. };
  60165. defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => {
  60166. const options = [];
  60167. switch (authParameters.operation) {
  60168. case "CreateToken": {
  60169. options.push(createSmithyApiNoAuthHttpAuthOption(authParameters));
  60170. break;
  60171. }
  60172. default: {
  60173. options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
  60174. }
  60175. }
  60176. return options;
  60177. };
  60178. resolveHttpAuthSchemeConfig = (config) => {
  60179. const config_0 = resolveAwsSdkSigV4Config(config);
  60180. return Object.assign(config_0, {
  60181. authSchemePreference: (0, import_util_middleware5.normalizeProvider)(config.authSchemePreference ?? [])
  60182. });
  60183. };
  60184. }
  60185. });
  60186. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js
  60187. var resolveClientEndpointParameters, commonParams;
  60188. var init_EndpointParameters = __esm({
  60189. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js"() {
  60190. resolveClientEndpointParameters = (options) => {
  60191. return Object.assign(options, {
  60192. useDualstackEndpoint: options.useDualstackEndpoint ?? false,
  60193. useFipsEndpoint: options.useFipsEndpoint ?? false,
  60194. defaultSigningName: "sso-oauth"
  60195. });
  60196. };
  60197. commonParams = {
  60198. UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
  60199. Endpoint: { type: "builtInParams", name: "endpoint" },
  60200. Region: { type: "builtInParams", name: "region" },
  60201. UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
  60202. };
  60203. }
  60204. });
  60205. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/package.json
  60206. var package_default;
  60207. var init_package = __esm({
  60208. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/package.json"() {
  60209. package_default = {
  60210. name: "@aws-sdk/nested-clients",
  60211. version: "3.817.0",
  60212. description: "Nested clients for AWS SDK packages.",
  60213. main: "./dist-cjs/index.js",
  60214. module: "./dist-es/index.js",
  60215. types: "./dist-types/index.d.ts",
  60216. scripts: {
  60217. build: "yarn lint && concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
  60218. "build:cjs": "node ../../scripts/compilation/inline nested-clients",
  60219. "build:es": "tsc -p tsconfig.es.json",
  60220. "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
  60221. "build:types": "tsc -p tsconfig.types.json",
  60222. "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
  60223. clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
  60224. lint: "node ../../scripts/validation/submodules-linter.js --pkg nested-clients",
  60225. test: "yarn g:vitest run",
  60226. "test:watch": "yarn g:vitest watch"
  60227. },
  60228. engines: {
  60229. node: ">=18.0.0"
  60230. },
  60231. author: {
  60232. name: "AWS SDK for JavaScript Team",
  60233. url: "https://aws.amazon.com/javascript/"
  60234. },
  60235. license: "Apache-2.0",
  60236. dependencies: {
  60237. "@aws-crypto/sha256-browser": "5.2.0",
  60238. "@aws-crypto/sha256-js": "5.2.0",
  60239. "@aws-sdk/core": "3.816.0",
  60240. "@aws-sdk/middleware-host-header": "3.804.0",
  60241. "@aws-sdk/middleware-logger": "3.804.0",
  60242. "@aws-sdk/middleware-recursion-detection": "3.804.0",
  60243. "@aws-sdk/middleware-user-agent": "3.816.0",
  60244. "@aws-sdk/region-config-resolver": "3.808.0",
  60245. "@aws-sdk/types": "3.804.0",
  60246. "@aws-sdk/util-endpoints": "3.808.0",
  60247. "@aws-sdk/util-user-agent-browser": "3.804.0",
  60248. "@aws-sdk/util-user-agent-node": "3.816.0",
  60249. "@smithy/config-resolver": "^4.1.2",
  60250. "@smithy/core": "^3.3.3",
  60251. "@smithy/fetch-http-handler": "^5.0.2",
  60252. "@smithy/hash-node": "^4.0.2",
  60253. "@smithy/invalid-dependency": "^4.0.2",
  60254. "@smithy/middleware-content-length": "^4.0.2",
  60255. "@smithy/middleware-endpoint": "^4.1.6",
  60256. "@smithy/middleware-retry": "^4.1.7",
  60257. "@smithy/middleware-serde": "^4.0.5",
  60258. "@smithy/middleware-stack": "^4.0.2",
  60259. "@smithy/node-config-provider": "^4.1.1",
  60260. "@smithy/node-http-handler": "^4.0.4",
  60261. "@smithy/protocol-http": "^5.1.0",
  60262. "@smithy/smithy-client": "^4.2.6",
  60263. "@smithy/types": "^4.2.0",
  60264. "@smithy/url-parser": "^4.0.2",
  60265. "@smithy/util-base64": "^4.0.0",
  60266. "@smithy/util-body-length-browser": "^4.0.0",
  60267. "@smithy/util-body-length-node": "^4.0.0",
  60268. "@smithy/util-defaults-mode-browser": "^4.0.14",
  60269. "@smithy/util-defaults-mode-node": "^4.0.14",
  60270. "@smithy/util-endpoints": "^3.0.4",
  60271. "@smithy/util-middleware": "^4.0.2",
  60272. "@smithy/util-retry": "^4.0.3",
  60273. "@smithy/util-utf8": "^4.0.0",
  60274. tslib: "^2.6.2"
  60275. },
  60276. devDependencies: {
  60277. concurrently: "7.0.0",
  60278. "downlevel-dts": "0.10.1",
  60279. rimraf: "3.0.2",
  60280. typescript: "~5.8.3"
  60281. },
  60282. typesVersions: {
  60283. "<4.0": {
  60284. "dist-types/*": [
  60285. "dist-types/ts3.4/*"
  60286. ]
  60287. }
  60288. },
  60289. files: [
  60290. "./sso-oidc.d.ts",
  60291. "./sso-oidc.js",
  60292. "./sts.d.ts",
  60293. "./sts.js",
  60294. "dist-*/**"
  60295. ],
  60296. browser: {
  60297. "./dist-es/submodules/sso-oidc/runtimeConfig": "./dist-es/submodules/sso-oidc/runtimeConfig.browser",
  60298. "./dist-es/submodules/sts/runtimeConfig": "./dist-es/submodules/sts/runtimeConfig.browser"
  60299. },
  60300. "react-native": {},
  60301. homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients",
  60302. repository: {
  60303. type: "git",
  60304. url: "https://github.com/aws/aws-sdk-js-v3.git",
  60305. directory: "packages/nested-clients"
  60306. },
  60307. exports: {
  60308. "./sso-oidc": {
  60309. types: "./dist-types/submodules/sso-oidc/index.d.ts",
  60310. module: "./dist-es/submodules/sso-oidc/index.js",
  60311. node: "./dist-cjs/submodules/sso-oidc/index.js",
  60312. import: "./dist-es/submodules/sso-oidc/index.js",
  60313. require: "./dist-cjs/submodules/sso-oidc/index.js"
  60314. },
  60315. "./sts": {
  60316. types: "./dist-types/submodules/sts/index.d.ts",
  60317. module: "./dist-es/submodules/sts/index.js",
  60318. node: "./dist-cjs/submodules/sts/index.js",
  60319. import: "./dist-es/submodules/sts/index.js",
  60320. require: "./dist-cjs/submodules/sts/index.js"
  60321. }
  60322. }
  60323. };
  60324. }
  60325. });
  60326. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js
  60327. var u, v, w, x2, a, b, c, d, e2, f3, g, h2, i2, j, k, l, m2, n, o, p, q, r2, s2, t2, _data, ruleSet;
  60328. var init_ruleset = __esm({
  60329. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js"() {
  60330. u = "required";
  60331. v = "fn";
  60332. w = "argv";
  60333. x2 = "ref";
  60334. a = true;
  60335. b = "isSet";
  60336. c = "booleanEquals";
  60337. d = "error";
  60338. e2 = "endpoint";
  60339. f3 = "tree";
  60340. g = "PartitionResult";
  60341. h2 = "getAttr";
  60342. i2 = { [u]: false, "type": "String" };
  60343. j = { [u]: true, "default": false, "type": "Boolean" };
  60344. k = { [x2]: "Endpoint" };
  60345. l = { [v]: c, [w]: [{ [x2]: "UseFIPS" }, true] };
  60346. m2 = { [v]: c, [w]: [{ [x2]: "UseDualStack" }, true] };
  60347. n = {};
  60348. o = { [v]: h2, [w]: [{ [x2]: g }, "supportsFIPS"] };
  60349. p = { [x2]: g };
  60350. q = { [v]: c, [w]: [true, { [v]: h2, [w]: [p, "supportsDualStack"] }] };
  60351. r2 = [l];
  60352. s2 = [m2];
  60353. t2 = [{ [x2]: "Region" }];
  60354. _data = { version: "1.0", parameters: { Region: i2, UseDualStack: j, UseFIPS: j, Endpoint: i2 }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r2, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s2, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e2 }], type: f3 }, { conditions: [{ [v]: b, [w]: t2 }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t2, assign: g }], rules: [{ conditions: [l, m2], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f3 }, { conditions: r2, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h2, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e2 }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f3 }, { conditions: s2, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f3 }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e2 }], type: f3 }], type: f3 }, { error: "Invalid Configuration: Missing Region", type: d }] };
  60355. ruleSet = _data;
  60356. }
  60357. });
  60358. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js
  60359. var import_util_endpoints, import_util_endpoints2, cache, defaultEndpointResolver;
  60360. var init_endpointResolver = __esm({
  60361. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js"() {
  60362. import_util_endpoints = __toESM(require_dist_cjs19());
  60363. import_util_endpoints2 = __toESM(require_dist_cjs18());
  60364. init_ruleset();
  60365. cache = new import_util_endpoints2.EndpointCache({
  60366. size: 50,
  60367. params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
  60368. });
  60369. defaultEndpointResolver = (endpointParams, context = {}) => {
  60370. return cache.get(endpointParams, () => (0, import_util_endpoints2.resolveEndpoint)(ruleSet, {
  60371. endpointParams,
  60372. logger: context.logger
  60373. }));
  60374. };
  60375. import_util_endpoints2.customEndpointFunctions.aws = import_util_endpoints.awsEndpointFunctions;
  60376. }
  60377. });
  60378. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js
  60379. var import_smithy_client4, import_url_parser, import_util_base643, import_util_utf83, getRuntimeConfig;
  60380. var init_runtimeConfig_shared = __esm({
  60381. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js"() {
  60382. init_dist_es2();
  60383. init_dist_es();
  60384. import_smithy_client4 = __toESM(require_dist_cjs23());
  60385. import_url_parser = __toESM(require_dist_cjs31());
  60386. import_util_base643 = __toESM(require_dist_cjs11());
  60387. import_util_utf83 = __toESM(require_dist_cjs10());
  60388. init_httpAuthSchemeProvider();
  60389. init_endpointResolver();
  60390. getRuntimeConfig = (config) => {
  60391. return {
  60392. apiVersion: "2019-06-10",
  60393. base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? import_util_base643.fromBase64,
  60394. base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? import_util_base643.toBase64,
  60395. disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
  60396. endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? defaultEndpointResolver,
  60397. extensions: (config == null ? void 0 : config.extensions) ?? [],
  60398. httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? defaultSSOOIDCHttpAuthSchemeProvider,
  60399. httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
  60400. {
  60401. schemeId: "aws.auth#sigv4",
  60402. identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
  60403. signer: new AwsSdkSigV4Signer()
  60404. },
  60405. {
  60406. schemeId: "smithy.api#noAuth",
  60407. identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
  60408. signer: new NoAuthSigner()
  60409. }
  60410. ],
  60411. logger: (config == null ? void 0 : config.logger) ?? new import_smithy_client4.NoOpLogger(),
  60412. serviceId: (config == null ? void 0 : config.serviceId) ?? "SSO OIDC",
  60413. urlParser: (config == null ? void 0 : config.urlParser) ?? import_url_parser.parseUrl,
  60414. utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? import_util_utf83.fromUtf8,
  60415. utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? import_util_utf83.toUtf8
  60416. };
  60417. };
  60418. }
  60419. });
  60420. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js
  60421. var import_util_user_agent_node, import_config_resolver, import_hash_node, import_middleware_retry, import_node_config_provider, import_node_http_handler, import_util_body_length_node, import_util_retry, import_smithy_client5, import_util_defaults_mode_node, import_smithy_client6, getRuntimeConfig2;
  60422. var init_runtimeConfig = __esm({
  60423. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js"() {
  60424. init_package();
  60425. init_dist_es2();
  60426. import_util_user_agent_node = __toESM(require_dist_cjs39());
  60427. import_config_resolver = __toESM(require_dist_cjs26());
  60428. import_hash_node = __toESM(require_dist_cjs40());
  60429. import_middleware_retry = __toESM(require_dist_cjs35());
  60430. import_node_config_provider = __toESM(require_dist_cjs29());
  60431. import_node_http_handler = __toESM(require_dist_cjs14());
  60432. import_util_body_length_node = __toESM(require_dist_cjs41());
  60433. import_util_retry = __toESM(require_dist_cjs34());
  60434. init_runtimeConfig_shared();
  60435. import_smithy_client5 = __toESM(require_dist_cjs23());
  60436. import_util_defaults_mode_node = __toESM(require_dist_cjs42());
  60437. import_smithy_client6 = __toESM(require_dist_cjs23());
  60438. getRuntimeConfig2 = (config) => {
  60439. (0, import_smithy_client6.emitWarningIfUnsupportedVersion)(process.version);
  60440. const defaultsMode = (0, import_util_defaults_mode_node.resolveDefaultsModeConfig)(config);
  60441. const defaultConfigProvider = () => defaultsMode().then(import_smithy_client5.loadConfigsForDefaultMode);
  60442. const clientSharedValues = getRuntimeConfig(config);
  60443. emitWarningIfUnsupportedVersion(process.version);
  60444. const loaderConfig = {
  60445. profile: config == null ? void 0 : config.profile,
  60446. logger: clientSharedValues.logger
  60447. };
  60448. return {
  60449. ...clientSharedValues,
  60450. ...config,
  60451. runtime: "node",
  60452. defaultsMode,
  60453. authSchemePreference: (config == null ? void 0 : config.authSchemePreference) ?? (0, import_node_config_provider.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
  60454. bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? import_util_body_length_node.calculateBodyLength,
  60455. defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, import_util_user_agent_node.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }),
  60456. maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, import_node_config_provider.loadConfig)(import_middleware_retry.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
  60457. region: (config == null ? void 0 : config.region) ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
  60458. requestHandler: import_node_http_handler.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
  60459. retryMode: (config == null ? void 0 : config.retryMode) ?? (0, import_node_config_provider.loadConfig)({
  60460. ...import_middleware_retry.NODE_RETRY_MODE_CONFIG_OPTIONS,
  60461. default: async () => (await defaultConfigProvider()).retryMode || import_util_retry.DEFAULT_RETRY_MODE
  60462. }, config),
  60463. sha256: (config == null ? void 0 : config.sha256) ?? import_hash_node.Hash.bind(null, "sha256"),
  60464. streamCollector: (config == null ? void 0 : config.streamCollector) ?? import_node_http_handler.streamCollector,
  60465. useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  60466. useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, import_node_config_provider.loadConfig)(import_config_resolver.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  60467. userAgentAppId: (config == null ? void 0 : config.userAgentAppId) ?? (0, import_node_config_provider.loadConfig)(import_util_user_agent_node.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
  60468. };
  60469. };
  60470. }
  60471. });
  60472. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js
  60473. var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig;
  60474. var init_httpAuthExtensionConfiguration = __esm({
  60475. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js"() {
  60476. getHttpAuthExtensionConfiguration = (runtimeConfig) => {
  60477. const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
  60478. let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
  60479. let _credentials = runtimeConfig.credentials;
  60480. return {
  60481. setHttpAuthScheme(httpAuthScheme) {
  60482. const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
  60483. if (index6 === -1) {
  60484. _httpAuthSchemes.push(httpAuthScheme);
  60485. } else {
  60486. _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
  60487. }
  60488. },
  60489. httpAuthSchemes() {
  60490. return _httpAuthSchemes;
  60491. },
  60492. setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
  60493. _httpAuthSchemeProvider = httpAuthSchemeProvider;
  60494. },
  60495. httpAuthSchemeProvider() {
  60496. return _httpAuthSchemeProvider;
  60497. },
  60498. setCredentials(credentials2) {
  60499. _credentials = credentials2;
  60500. },
  60501. credentials() {
  60502. return _credentials;
  60503. }
  60504. };
  60505. };
  60506. resolveHttpAuthRuntimeConfig = (config) => {
  60507. return {
  60508. httpAuthSchemes: config.httpAuthSchemes(),
  60509. httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
  60510. credentials: config.credentials()
  60511. };
  60512. };
  60513. }
  60514. });
  60515. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js
  60516. var import_region_config_resolver, import_protocol_http12, import_smithy_client7, resolveRuntimeExtensions;
  60517. var init_runtimeExtensions = __esm({
  60518. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js"() {
  60519. import_region_config_resolver = __toESM(require_dist_cjs43());
  60520. import_protocol_http12 = __toESM(require_dist_cjs2());
  60521. import_smithy_client7 = __toESM(require_dist_cjs23());
  60522. init_httpAuthExtensionConfiguration();
  60523. resolveRuntimeExtensions = (runtimeConfig, extensions) => {
  60524. const extensionConfiguration = Object.assign((0, import_region_config_resolver.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client7.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http12.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));
  60525. extensions.forEach((extension) => extension.configure(extensionConfiguration));
  60526. return Object.assign(runtimeConfig, (0, import_region_config_resolver.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client7.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http12.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));
  60527. };
  60528. }
  60529. });
  60530. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js
  60531. var import_middleware_host_header, import_middleware_logger, import_middleware_recursion_detection, import_middleware_user_agent, import_config_resolver2, import_middleware_content_length, import_middleware_endpoint, import_middleware_retry2, import_smithy_client8, SSOOIDCClient;
  60532. var init_SSOOIDCClient = __esm({
  60533. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js"() {
  60534. import_middleware_host_header = __toESM(require_dist_cjs3());
  60535. import_middleware_logger = __toESM(require_dist_cjs4());
  60536. import_middleware_recursion_detection = __toESM(require_dist_cjs5());
  60537. import_middleware_user_agent = __toESM(require_dist_cjs24());
  60538. import_config_resolver2 = __toESM(require_dist_cjs26());
  60539. init_dist_es();
  60540. import_middleware_content_length = __toESM(require_dist_cjs27());
  60541. import_middleware_endpoint = __toESM(require_dist_cjs32());
  60542. import_middleware_retry2 = __toESM(require_dist_cjs35());
  60543. import_smithy_client8 = __toESM(require_dist_cjs23());
  60544. init_httpAuthSchemeProvider();
  60545. init_EndpointParameters();
  60546. init_runtimeConfig();
  60547. init_runtimeExtensions();
  60548. SSOOIDCClient = class extends import_smithy_client8.Client {
  60549. config;
  60550. constructor(...[configuration]) {
  60551. const _config_0 = getRuntimeConfig2(configuration || {});
  60552. super(_config_0);
  60553. this.initConfig = _config_0;
  60554. const _config_1 = resolveClientEndpointParameters(_config_0);
  60555. const _config_2 = (0, import_middleware_user_agent.resolveUserAgentConfig)(_config_1);
  60556. const _config_3 = (0, import_middleware_retry2.resolveRetryConfig)(_config_2);
  60557. const _config_4 = (0, import_config_resolver2.resolveRegionConfig)(_config_3);
  60558. const _config_5 = (0, import_middleware_host_header.resolveHostHeaderConfig)(_config_4);
  60559. const _config_6 = (0, import_middleware_endpoint.resolveEndpointConfig)(_config_5);
  60560. const _config_7 = resolveHttpAuthSchemeConfig(_config_6);
  60561. const _config_8 = resolveRuntimeExtensions(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
  60562. this.config = _config_8;
  60563. this.middlewareStack.use((0, import_middleware_user_agent.getUserAgentPlugin)(this.config));
  60564. this.middlewareStack.use((0, import_middleware_retry2.getRetryPlugin)(this.config));
  60565. this.middlewareStack.use((0, import_middleware_content_length.getContentLengthPlugin)(this.config));
  60566. this.middlewareStack.use((0, import_middleware_host_header.getHostHeaderPlugin)(this.config));
  60567. this.middlewareStack.use((0, import_middleware_logger.getLoggerPlugin)(this.config));
  60568. this.middlewareStack.use((0, import_middleware_recursion_detection.getRecursionDetectionPlugin)(this.config));
  60569. this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
  60570. httpAuthSchemeParametersProvider: defaultSSOOIDCHttpAuthSchemeParametersProvider,
  60571. identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
  60572. "aws.auth#sigv4": config.credentials
  60573. })
  60574. }));
  60575. this.middlewareStack.use(getHttpSigningPlugin(this.config));
  60576. }
  60577. destroy() {
  60578. super.destroy();
  60579. }
  60580. };
  60581. }
  60582. });
  60583. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js
  60584. var import_smithy_client9, SSOOIDCServiceException;
  60585. var init_SSOOIDCServiceException = __esm({
  60586. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js"() {
  60587. import_smithy_client9 = __toESM(require_dist_cjs23());
  60588. SSOOIDCServiceException = class _SSOOIDCServiceException extends import_smithy_client9.ServiceException {
  60589. constructor(options) {
  60590. super(options);
  60591. Object.setPrototypeOf(this, _SSOOIDCServiceException.prototype);
  60592. }
  60593. };
  60594. }
  60595. });
  60596. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js
  60597. var import_smithy_client10, AccessDeniedException, AuthorizationPendingException, CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog, ExpiredTokenException, InternalServerException, InvalidClientException, InvalidGrantException, InvalidRequestException, InvalidScopeException, SlowDownException, UnauthorizedClientException, UnsupportedGrantTypeException;
  60598. var init_models_0 = __esm({
  60599. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js"() {
  60600. import_smithy_client10 = __toESM(require_dist_cjs23());
  60601. init_SSOOIDCServiceException();
  60602. AccessDeniedException = class _AccessDeniedException extends SSOOIDCServiceException {
  60603. name = "AccessDeniedException";
  60604. $fault = "client";
  60605. error;
  60606. error_description;
  60607. constructor(opts) {
  60608. super({
  60609. name: "AccessDeniedException",
  60610. $fault: "client",
  60611. ...opts
  60612. });
  60613. Object.setPrototypeOf(this, _AccessDeniedException.prototype);
  60614. this.error = opts.error;
  60615. this.error_description = opts.error_description;
  60616. }
  60617. };
  60618. AuthorizationPendingException = class _AuthorizationPendingException extends SSOOIDCServiceException {
  60619. name = "AuthorizationPendingException";
  60620. $fault = "client";
  60621. error;
  60622. error_description;
  60623. constructor(opts) {
  60624. super({
  60625. name: "AuthorizationPendingException",
  60626. $fault: "client",
  60627. ...opts
  60628. });
  60629. Object.setPrototypeOf(this, _AuthorizationPendingException.prototype);
  60630. this.error = opts.error;
  60631. this.error_description = opts.error_description;
  60632. }
  60633. };
  60634. CreateTokenRequestFilterSensitiveLog = (obj) => ({
  60635. ...obj,
  60636. ...obj.clientSecret && { clientSecret: import_smithy_client10.SENSITIVE_STRING },
  60637. ...obj.refreshToken && { refreshToken: import_smithy_client10.SENSITIVE_STRING },
  60638. ...obj.codeVerifier && { codeVerifier: import_smithy_client10.SENSITIVE_STRING }
  60639. });
  60640. CreateTokenResponseFilterSensitiveLog = (obj) => ({
  60641. ...obj,
  60642. ...obj.accessToken && { accessToken: import_smithy_client10.SENSITIVE_STRING },
  60643. ...obj.refreshToken && { refreshToken: import_smithy_client10.SENSITIVE_STRING },
  60644. ...obj.idToken && { idToken: import_smithy_client10.SENSITIVE_STRING }
  60645. });
  60646. ExpiredTokenException = class _ExpiredTokenException extends SSOOIDCServiceException {
  60647. name = "ExpiredTokenException";
  60648. $fault = "client";
  60649. error;
  60650. error_description;
  60651. constructor(opts) {
  60652. super({
  60653. name: "ExpiredTokenException",
  60654. $fault: "client",
  60655. ...opts
  60656. });
  60657. Object.setPrototypeOf(this, _ExpiredTokenException.prototype);
  60658. this.error = opts.error;
  60659. this.error_description = opts.error_description;
  60660. }
  60661. };
  60662. InternalServerException = class _InternalServerException extends SSOOIDCServiceException {
  60663. name = "InternalServerException";
  60664. $fault = "server";
  60665. error;
  60666. error_description;
  60667. constructor(opts) {
  60668. super({
  60669. name: "InternalServerException",
  60670. $fault: "server",
  60671. ...opts
  60672. });
  60673. Object.setPrototypeOf(this, _InternalServerException.prototype);
  60674. this.error = opts.error;
  60675. this.error_description = opts.error_description;
  60676. }
  60677. };
  60678. InvalidClientException = class _InvalidClientException extends SSOOIDCServiceException {
  60679. name = "InvalidClientException";
  60680. $fault = "client";
  60681. error;
  60682. error_description;
  60683. constructor(opts) {
  60684. super({
  60685. name: "InvalidClientException",
  60686. $fault: "client",
  60687. ...opts
  60688. });
  60689. Object.setPrototypeOf(this, _InvalidClientException.prototype);
  60690. this.error = opts.error;
  60691. this.error_description = opts.error_description;
  60692. }
  60693. };
  60694. InvalidGrantException = class _InvalidGrantException extends SSOOIDCServiceException {
  60695. name = "InvalidGrantException";
  60696. $fault = "client";
  60697. error;
  60698. error_description;
  60699. constructor(opts) {
  60700. super({
  60701. name: "InvalidGrantException",
  60702. $fault: "client",
  60703. ...opts
  60704. });
  60705. Object.setPrototypeOf(this, _InvalidGrantException.prototype);
  60706. this.error = opts.error;
  60707. this.error_description = opts.error_description;
  60708. }
  60709. };
  60710. InvalidRequestException = class _InvalidRequestException extends SSOOIDCServiceException {
  60711. name = "InvalidRequestException";
  60712. $fault = "client";
  60713. error;
  60714. error_description;
  60715. constructor(opts) {
  60716. super({
  60717. name: "InvalidRequestException",
  60718. $fault: "client",
  60719. ...opts
  60720. });
  60721. Object.setPrototypeOf(this, _InvalidRequestException.prototype);
  60722. this.error = opts.error;
  60723. this.error_description = opts.error_description;
  60724. }
  60725. };
  60726. InvalidScopeException = class _InvalidScopeException extends SSOOIDCServiceException {
  60727. name = "InvalidScopeException";
  60728. $fault = "client";
  60729. error;
  60730. error_description;
  60731. constructor(opts) {
  60732. super({
  60733. name: "InvalidScopeException",
  60734. $fault: "client",
  60735. ...opts
  60736. });
  60737. Object.setPrototypeOf(this, _InvalidScopeException.prototype);
  60738. this.error = opts.error;
  60739. this.error_description = opts.error_description;
  60740. }
  60741. };
  60742. SlowDownException = class _SlowDownException extends SSOOIDCServiceException {
  60743. name = "SlowDownException";
  60744. $fault = "client";
  60745. error;
  60746. error_description;
  60747. constructor(opts) {
  60748. super({
  60749. name: "SlowDownException",
  60750. $fault: "client",
  60751. ...opts
  60752. });
  60753. Object.setPrototypeOf(this, _SlowDownException.prototype);
  60754. this.error = opts.error;
  60755. this.error_description = opts.error_description;
  60756. }
  60757. };
  60758. UnauthorizedClientException = class _UnauthorizedClientException extends SSOOIDCServiceException {
  60759. name = "UnauthorizedClientException";
  60760. $fault = "client";
  60761. error;
  60762. error_description;
  60763. constructor(opts) {
  60764. super({
  60765. name: "UnauthorizedClientException",
  60766. $fault: "client",
  60767. ...opts
  60768. });
  60769. Object.setPrototypeOf(this, _UnauthorizedClientException.prototype);
  60770. this.error = opts.error;
  60771. this.error_description = opts.error_description;
  60772. }
  60773. };
  60774. UnsupportedGrantTypeException = class _UnsupportedGrantTypeException extends SSOOIDCServiceException {
  60775. name = "UnsupportedGrantTypeException";
  60776. $fault = "client";
  60777. error;
  60778. error_description;
  60779. constructor(opts) {
  60780. super({
  60781. name: "UnsupportedGrantTypeException",
  60782. $fault: "client",
  60783. ...opts
  60784. });
  60785. Object.setPrototypeOf(this, _UnsupportedGrantTypeException.prototype);
  60786. this.error = opts.error;
  60787. this.error_description = opts.error_description;
  60788. }
  60789. };
  60790. }
  60791. });
  60792. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/protocols/Aws_restJson1.js
  60793. var import_smithy_client11, se_CreateTokenCommand, de_CreateTokenCommand, de_CommandError, throwDefaultError, de_AccessDeniedExceptionRes, de_AuthorizationPendingExceptionRes, de_ExpiredTokenExceptionRes, de_InternalServerExceptionRes, de_InvalidClientExceptionRes, de_InvalidGrantExceptionRes, de_InvalidRequestExceptionRes, de_InvalidScopeExceptionRes, de_SlowDownExceptionRes, de_UnauthorizedClientExceptionRes, de_UnsupportedGrantTypeExceptionRes, deserializeMetadata;
  60794. var init_Aws_restJson1 = __esm({
  60795. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/protocols/Aws_restJson1.js"() {
  60796. init_dist_es2();
  60797. init_dist_es();
  60798. import_smithy_client11 = __toESM(require_dist_cjs23());
  60799. init_models_0();
  60800. init_SSOOIDCServiceException();
  60801. se_CreateTokenCommand = async (input, context) => {
  60802. const b3 = requestBuilder(input, context);
  60803. const headers = {
  60804. "content-type": "application/json"
  60805. };
  60806. b3.bp("/token");
  60807. let body;
  60808. body = JSON.stringify((0, import_smithy_client11.take)(input, {
  60809. clientId: [],
  60810. clientSecret: [],
  60811. code: [],
  60812. codeVerifier: [],
  60813. deviceCode: [],
  60814. grantType: [],
  60815. redirectUri: [],
  60816. refreshToken: [],
  60817. scope: (_3) => (0, import_smithy_client11._json)(_3)
  60818. }));
  60819. b3.m("POST").h(headers).b(body);
  60820. return b3.build();
  60821. };
  60822. de_CreateTokenCommand = async (output, context) => {
  60823. if (output.statusCode !== 200 && output.statusCode >= 300) {
  60824. return de_CommandError(output, context);
  60825. }
  60826. const contents = (0, import_smithy_client11.map)({
  60827. $metadata: deserializeMetadata(output)
  60828. });
  60829. const data = (0, import_smithy_client11.expectNonNull)((0, import_smithy_client11.expectObject)(await parseJsonBody(output.body, context)), "body");
  60830. const doc = (0, import_smithy_client11.take)(data, {
  60831. accessToken: import_smithy_client11.expectString,
  60832. expiresIn: import_smithy_client11.expectInt32,
  60833. idToken: import_smithy_client11.expectString,
  60834. refreshToken: import_smithy_client11.expectString,
  60835. tokenType: import_smithy_client11.expectString
  60836. });
  60837. Object.assign(contents, doc);
  60838. return contents;
  60839. };
  60840. de_CommandError = async (output, context) => {
  60841. const parsedOutput = {
  60842. ...output,
  60843. body: await parseJsonErrorBody(output.body, context)
  60844. };
  60845. const errorCode = loadRestJsonErrorCode(output, parsedOutput.body);
  60846. switch (errorCode) {
  60847. case "AccessDeniedException":
  60848. case "com.amazonaws.ssooidc#AccessDeniedException":
  60849. throw await de_AccessDeniedExceptionRes(parsedOutput, context);
  60850. case "AuthorizationPendingException":
  60851. case "com.amazonaws.ssooidc#AuthorizationPendingException":
  60852. throw await de_AuthorizationPendingExceptionRes(parsedOutput, context);
  60853. case "ExpiredTokenException":
  60854. case "com.amazonaws.ssooidc#ExpiredTokenException":
  60855. throw await de_ExpiredTokenExceptionRes(parsedOutput, context);
  60856. case "InternalServerException":
  60857. case "com.amazonaws.ssooidc#InternalServerException":
  60858. throw await de_InternalServerExceptionRes(parsedOutput, context);
  60859. case "InvalidClientException":
  60860. case "com.amazonaws.ssooidc#InvalidClientException":
  60861. throw await de_InvalidClientExceptionRes(parsedOutput, context);
  60862. case "InvalidGrantException":
  60863. case "com.amazonaws.ssooidc#InvalidGrantException":
  60864. throw await de_InvalidGrantExceptionRes(parsedOutput, context);
  60865. case "InvalidRequestException":
  60866. case "com.amazonaws.ssooidc#InvalidRequestException":
  60867. throw await de_InvalidRequestExceptionRes(parsedOutput, context);
  60868. case "InvalidScopeException":
  60869. case "com.amazonaws.ssooidc#InvalidScopeException":
  60870. throw await de_InvalidScopeExceptionRes(parsedOutput, context);
  60871. case "SlowDownException":
  60872. case "com.amazonaws.ssooidc#SlowDownException":
  60873. throw await de_SlowDownExceptionRes(parsedOutput, context);
  60874. case "UnauthorizedClientException":
  60875. case "com.amazonaws.ssooidc#UnauthorizedClientException":
  60876. throw await de_UnauthorizedClientExceptionRes(parsedOutput, context);
  60877. case "UnsupportedGrantTypeException":
  60878. case "com.amazonaws.ssooidc#UnsupportedGrantTypeException":
  60879. throw await de_UnsupportedGrantTypeExceptionRes(parsedOutput, context);
  60880. default:
  60881. const parsedBody = parsedOutput.body;
  60882. return throwDefaultError({
  60883. output,
  60884. parsedBody,
  60885. errorCode
  60886. });
  60887. }
  60888. };
  60889. throwDefaultError = (0, import_smithy_client11.withBaseException)(SSOOIDCServiceException);
  60890. de_AccessDeniedExceptionRes = async (parsedOutput, context) => {
  60891. const contents = (0, import_smithy_client11.map)({});
  60892. const data = parsedOutput.body;
  60893. const doc = (0, import_smithy_client11.take)(data, {
  60894. error: import_smithy_client11.expectString,
  60895. error_description: import_smithy_client11.expectString
  60896. });
  60897. Object.assign(contents, doc);
  60898. const exception = new AccessDeniedException({
  60899. $metadata: deserializeMetadata(parsedOutput),
  60900. ...contents
  60901. });
  60902. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  60903. };
  60904. de_AuthorizationPendingExceptionRes = async (parsedOutput, context) => {
  60905. const contents = (0, import_smithy_client11.map)({});
  60906. const data = parsedOutput.body;
  60907. const doc = (0, import_smithy_client11.take)(data, {
  60908. error: import_smithy_client11.expectString,
  60909. error_description: import_smithy_client11.expectString
  60910. });
  60911. Object.assign(contents, doc);
  60912. const exception = new AuthorizationPendingException({
  60913. $metadata: deserializeMetadata(parsedOutput),
  60914. ...contents
  60915. });
  60916. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  60917. };
  60918. de_ExpiredTokenExceptionRes = async (parsedOutput, context) => {
  60919. const contents = (0, import_smithy_client11.map)({});
  60920. const data = parsedOutput.body;
  60921. const doc = (0, import_smithy_client11.take)(data, {
  60922. error: import_smithy_client11.expectString,
  60923. error_description: import_smithy_client11.expectString
  60924. });
  60925. Object.assign(contents, doc);
  60926. const exception = new ExpiredTokenException({
  60927. $metadata: deserializeMetadata(parsedOutput),
  60928. ...contents
  60929. });
  60930. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  60931. };
  60932. de_InternalServerExceptionRes = async (parsedOutput, context) => {
  60933. const contents = (0, import_smithy_client11.map)({});
  60934. const data = parsedOutput.body;
  60935. const doc = (0, import_smithy_client11.take)(data, {
  60936. error: import_smithy_client11.expectString,
  60937. error_description: import_smithy_client11.expectString
  60938. });
  60939. Object.assign(contents, doc);
  60940. const exception = new InternalServerException({
  60941. $metadata: deserializeMetadata(parsedOutput),
  60942. ...contents
  60943. });
  60944. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  60945. };
  60946. de_InvalidClientExceptionRes = async (parsedOutput, context) => {
  60947. const contents = (0, import_smithy_client11.map)({});
  60948. const data = parsedOutput.body;
  60949. const doc = (0, import_smithy_client11.take)(data, {
  60950. error: import_smithy_client11.expectString,
  60951. error_description: import_smithy_client11.expectString
  60952. });
  60953. Object.assign(contents, doc);
  60954. const exception = new InvalidClientException({
  60955. $metadata: deserializeMetadata(parsedOutput),
  60956. ...contents
  60957. });
  60958. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  60959. };
  60960. de_InvalidGrantExceptionRes = async (parsedOutput, context) => {
  60961. const contents = (0, import_smithy_client11.map)({});
  60962. const data = parsedOutput.body;
  60963. const doc = (0, import_smithy_client11.take)(data, {
  60964. error: import_smithy_client11.expectString,
  60965. error_description: import_smithy_client11.expectString
  60966. });
  60967. Object.assign(contents, doc);
  60968. const exception = new InvalidGrantException({
  60969. $metadata: deserializeMetadata(parsedOutput),
  60970. ...contents
  60971. });
  60972. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  60973. };
  60974. de_InvalidRequestExceptionRes = async (parsedOutput, context) => {
  60975. const contents = (0, import_smithy_client11.map)({});
  60976. const data = parsedOutput.body;
  60977. const doc = (0, import_smithy_client11.take)(data, {
  60978. error: import_smithy_client11.expectString,
  60979. error_description: import_smithy_client11.expectString
  60980. });
  60981. Object.assign(contents, doc);
  60982. const exception = new InvalidRequestException({
  60983. $metadata: deserializeMetadata(parsedOutput),
  60984. ...contents
  60985. });
  60986. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  60987. };
  60988. de_InvalidScopeExceptionRes = async (parsedOutput, context) => {
  60989. const contents = (0, import_smithy_client11.map)({});
  60990. const data = parsedOutput.body;
  60991. const doc = (0, import_smithy_client11.take)(data, {
  60992. error: import_smithy_client11.expectString,
  60993. error_description: import_smithy_client11.expectString
  60994. });
  60995. Object.assign(contents, doc);
  60996. const exception = new InvalidScopeException({
  60997. $metadata: deserializeMetadata(parsedOutput),
  60998. ...contents
  60999. });
  61000. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  61001. };
  61002. de_SlowDownExceptionRes = async (parsedOutput, context) => {
  61003. const contents = (0, import_smithy_client11.map)({});
  61004. const data = parsedOutput.body;
  61005. const doc = (0, import_smithy_client11.take)(data, {
  61006. error: import_smithy_client11.expectString,
  61007. error_description: import_smithy_client11.expectString
  61008. });
  61009. Object.assign(contents, doc);
  61010. const exception = new SlowDownException({
  61011. $metadata: deserializeMetadata(parsedOutput),
  61012. ...contents
  61013. });
  61014. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  61015. };
  61016. de_UnauthorizedClientExceptionRes = async (parsedOutput, context) => {
  61017. const contents = (0, import_smithy_client11.map)({});
  61018. const data = parsedOutput.body;
  61019. const doc = (0, import_smithy_client11.take)(data, {
  61020. error: import_smithy_client11.expectString,
  61021. error_description: import_smithy_client11.expectString
  61022. });
  61023. Object.assign(contents, doc);
  61024. const exception = new UnauthorizedClientException({
  61025. $metadata: deserializeMetadata(parsedOutput),
  61026. ...contents
  61027. });
  61028. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  61029. };
  61030. de_UnsupportedGrantTypeExceptionRes = async (parsedOutput, context) => {
  61031. const contents = (0, import_smithy_client11.map)({});
  61032. const data = parsedOutput.body;
  61033. const doc = (0, import_smithy_client11.take)(data, {
  61034. error: import_smithy_client11.expectString,
  61035. error_description: import_smithy_client11.expectString
  61036. });
  61037. Object.assign(contents, doc);
  61038. const exception = new UnsupportedGrantTypeException({
  61039. $metadata: deserializeMetadata(parsedOutput),
  61040. ...contents
  61041. });
  61042. return (0, import_smithy_client11.decorateServiceException)(exception, parsedOutput.body);
  61043. };
  61044. deserializeMetadata = (output) => ({
  61045. httpStatusCode: output.statusCode,
  61046. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  61047. extendedRequestId: output.headers["x-amz-id-2"],
  61048. cfId: output.headers["x-amz-cf-id"]
  61049. });
  61050. }
  61051. });
  61052. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js
  61053. var import_middleware_endpoint2, import_middleware_serde2, import_smithy_client12, CreateTokenCommand;
  61054. var init_CreateTokenCommand = __esm({
  61055. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js"() {
  61056. import_middleware_endpoint2 = __toESM(require_dist_cjs32());
  61057. import_middleware_serde2 = __toESM(require_dist_cjs7());
  61058. import_smithy_client12 = __toESM(require_dist_cjs23());
  61059. init_EndpointParameters();
  61060. init_models_0();
  61061. init_Aws_restJson1();
  61062. CreateTokenCommand = class extends import_smithy_client12.Command.classBuilder().ep(commonParams).m(function(Command, cs, config, o3) {
  61063. return [
  61064. (0, import_middleware_serde2.getSerdePlugin)(config, this.serialize, this.deserialize),
  61065. (0, import_middleware_endpoint2.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  61066. ];
  61067. }).s("AWSSSOOIDCService", "CreateToken", {}).n("SSOOIDCClient", "CreateTokenCommand").f(CreateTokenRequestFilterSensitiveLog, CreateTokenResponseFilterSensitiveLog).ser(se_CreateTokenCommand).de(de_CreateTokenCommand).build() {
  61068. };
  61069. }
  61070. });
  61071. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js
  61072. var import_smithy_client13, commands, SSOOIDC;
  61073. var init_SSOOIDC = __esm({
  61074. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js"() {
  61075. import_smithy_client13 = __toESM(require_dist_cjs23());
  61076. init_CreateTokenCommand();
  61077. init_SSOOIDCClient();
  61078. commands = {
  61079. CreateTokenCommand
  61080. };
  61081. SSOOIDC = class extends SSOOIDCClient {
  61082. };
  61083. (0, import_smithy_client13.createAggregatedClient)(commands, SSOOIDC);
  61084. }
  61085. });
  61086. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js
  61087. var init_commands = __esm({
  61088. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js"() {
  61089. init_CreateTokenCommand();
  61090. }
  61091. });
  61092. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/index.js
  61093. var init_models = __esm({
  61094. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/index.js"() {
  61095. init_models_0();
  61096. }
  61097. });
  61098. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js
  61099. var sso_oidc_exports = {};
  61100. __export(sso_oidc_exports, {
  61101. $Command: () => import_smithy_client12.Command,
  61102. AccessDeniedException: () => AccessDeniedException,
  61103. AuthorizationPendingException: () => AuthorizationPendingException,
  61104. CreateTokenCommand: () => CreateTokenCommand,
  61105. CreateTokenRequestFilterSensitiveLog: () => CreateTokenRequestFilterSensitiveLog,
  61106. CreateTokenResponseFilterSensitiveLog: () => CreateTokenResponseFilterSensitiveLog,
  61107. ExpiredTokenException: () => ExpiredTokenException,
  61108. InternalServerException: () => InternalServerException,
  61109. InvalidClientException: () => InvalidClientException,
  61110. InvalidGrantException: () => InvalidGrantException,
  61111. InvalidRequestException: () => InvalidRequestException,
  61112. InvalidScopeException: () => InvalidScopeException,
  61113. SSOOIDC: () => SSOOIDC,
  61114. SSOOIDCClient: () => SSOOIDCClient,
  61115. SSOOIDCServiceException: () => SSOOIDCServiceException,
  61116. SlowDownException: () => SlowDownException,
  61117. UnauthorizedClientException: () => UnauthorizedClientException,
  61118. UnsupportedGrantTypeException: () => UnsupportedGrantTypeException,
  61119. __Client: () => import_smithy_client8.Client
  61120. });
  61121. var init_sso_oidc = __esm({
  61122. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js"() {
  61123. init_SSOOIDCClient();
  61124. init_SSOOIDC();
  61125. init_commands();
  61126. init_models();
  61127. init_SSOOIDCServiceException();
  61128. }
  61129. });
  61130. // ../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js
  61131. var require_dist_cjs45 = __commonJS({
  61132. "../node_modules/.pnpm/@aws-sdk+token-providers@3.817.0/node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports2, module2) {
  61133. "use strict";
  61134. var __create3 = Object.create;
  61135. var __defProp3 = Object.defineProperty;
  61136. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  61137. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  61138. var __getProtoOf3 = Object.getPrototypeOf;
  61139. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  61140. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  61141. var __export2 = (target, all) => {
  61142. for (var name in all)
  61143. __defProp3(target, name, { get: all[name], enumerable: true });
  61144. };
  61145. var __copyProps3 = (to, from, except, desc) => {
  61146. if (from && typeof from === "object" || typeof from === "function") {
  61147. for (let key of __getOwnPropNames3(from))
  61148. if (!__hasOwnProp3.call(to, key) && key !== except)
  61149. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  61150. }
  61151. return to;
  61152. };
  61153. var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
  61154. // If the importer is in node compatibility mode or this is not an ESM
  61155. // file that has been converted to a CommonJS file using a Babel-
  61156. // compatible transform (i.e. "__esModule" has not been set), then set
  61157. // "default" to the CommonJS "module.exports" for node compatibility.
  61158. isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
  61159. mod
  61160. ));
  61161. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  61162. var index_exports = {};
  61163. __export2(index_exports, {
  61164. fromEnvSigningName: () => fromEnvSigningName,
  61165. fromSso: () => fromSso,
  61166. fromStatic: () => fromStatic,
  61167. nodeProvider: () => nodeProvider
  61168. });
  61169. module2.exports = __toCommonJS2(index_exports);
  61170. var import_core17 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
  61171. var import_property_provider2 = require_dist_cjs20();
  61172. var fromEnvSigningName = /* @__PURE__ */ __name(({ logger: logger3, signingName } = {}) => async () => {
  61173. var _a2;
  61174. (_a2 = logger3 == null ? void 0 : logger3.debug) == null ? void 0 : _a2.call(logger3, "@aws-sdk/token-providers - fromEnvSigningName");
  61175. if (!signingName) {
  61176. throw new import_property_provider2.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger: logger3 });
  61177. }
  61178. const bearerTokenKey = (0, import_core17.getBearerTokenEnvKey)(signingName);
  61179. if (!(bearerTokenKey in process.env)) {
  61180. throw new import_property_provider2.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger: logger3 });
  61181. }
  61182. return { token: process.env[bearerTokenKey] };
  61183. }, "fromEnvSigningName");
  61184. var EXPIRE_WINDOW_MS = 5 * 60 * 1e3;
  61185. var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
  61186. var getSsoOidcClient = /* @__PURE__ */ __name(async (ssoRegion, init2 = {}) => {
  61187. var _a2, _b, _c;
  61188. const { SSOOIDCClient: SSOOIDCClient2 } = await Promise.resolve().then(() => __toESM3((init_sso_oidc(), __toCommonJS(sso_oidc_exports))));
  61189. const ssoOidcClient = new SSOOIDCClient2(
  61190. Object.assign({}, init2.clientConfig ?? {}, {
  61191. region: ssoRegion ?? ((_a2 = init2.clientConfig) == null ? void 0 : _a2.region),
  61192. logger: ((_b = init2.clientConfig) == null ? void 0 : _b.logger) ?? ((_c = init2.parentClientConfig) == null ? void 0 : _c.logger)
  61193. })
  61194. );
  61195. return ssoOidcClient;
  61196. }, "getSsoOidcClient");
  61197. var getNewSsoOidcToken = /* @__PURE__ */ __name(async (ssoToken, ssoRegion, init2 = {}) => {
  61198. const { CreateTokenCommand: CreateTokenCommand2 } = await Promise.resolve().then(() => __toESM3((init_sso_oidc(), __toCommonJS(sso_oidc_exports))));
  61199. const ssoOidcClient = await getSsoOidcClient(ssoRegion, init2);
  61200. return ssoOidcClient.send(
  61201. new CreateTokenCommand2({
  61202. clientId: ssoToken.clientId,
  61203. clientSecret: ssoToken.clientSecret,
  61204. refreshToken: ssoToken.refreshToken,
  61205. grantType: "refresh_token"
  61206. })
  61207. );
  61208. }, "getNewSsoOidcToken");
  61209. var validateTokenExpiry = /* @__PURE__ */ __name((token) => {
  61210. if (token.expiration && token.expiration.getTime() < Date.now()) {
  61211. throw new import_property_provider2.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);
  61212. }
  61213. }, "validateTokenExpiry");
  61214. var validateTokenKey = /* @__PURE__ */ __name((key, value, forRefresh = false) => {
  61215. if (typeof value === "undefined") {
  61216. throw new import_property_provider2.TokenProviderError(
  61217. `Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`,
  61218. false
  61219. );
  61220. }
  61221. }, "validateTokenKey");
  61222. var import_shared_ini_file_loader = require_dist_cjs28();
  61223. var import_fs14 = require("fs");
  61224. var { writeFile } = import_fs14.promises;
  61225. var writeSSOTokenToFile = /* @__PURE__ */ __name((id, ssoToken) => {
  61226. const tokenFilepath = (0, import_shared_ini_file_loader.getSSOTokenFilepath)(id);
  61227. const tokenString = JSON.stringify(ssoToken, null, 2);
  61228. return writeFile(tokenFilepath, tokenString);
  61229. }, "writeSSOTokenToFile");
  61230. var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0);
  61231. var fromSso = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => {
  61232. var _a2;
  61233. const init2 = {
  61234. ..._init,
  61235. parentClientConfig: {
  61236. ...callerClientConfig,
  61237. ..._init.parentClientConfig
  61238. }
  61239. };
  61240. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/token-providers - fromSso");
  61241. const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
  61242. const profileName = (0, import_shared_ini_file_loader.getProfileName)({
  61243. profile: init2.profile ?? (callerClientConfig == null ? void 0 : callerClientConfig.profile)
  61244. });
  61245. const profile = profiles[profileName];
  61246. if (!profile) {
  61247. throw new import_property_provider2.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);
  61248. } else if (!profile["sso_session"]) {
  61249. throw new import_property_provider2.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);
  61250. }
  61251. const ssoSessionName = profile["sso_session"];
  61252. const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init2);
  61253. const ssoSession = ssoSessions[ssoSessionName];
  61254. if (!ssoSession) {
  61255. throw new import_property_provider2.TokenProviderError(
  61256. `Sso session '${ssoSessionName}' could not be found in shared credentials file.`,
  61257. false
  61258. );
  61259. }
  61260. for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) {
  61261. if (!ssoSession[ssoSessionRequiredKey]) {
  61262. throw new import_property_provider2.TokenProviderError(
  61263. `Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`,
  61264. false
  61265. );
  61266. }
  61267. }
  61268. const ssoStartUrl = ssoSession["sso_start_url"];
  61269. const ssoRegion = ssoSession["sso_region"];
  61270. let ssoToken;
  61271. try {
  61272. ssoToken = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoSessionName);
  61273. } catch (e4) {
  61274. throw new import_property_provider2.TokenProviderError(
  61275. `The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`,
  61276. false
  61277. );
  61278. }
  61279. validateTokenKey("accessToken", ssoToken.accessToken);
  61280. validateTokenKey("expiresAt", ssoToken.expiresAt);
  61281. const { accessToken, expiresAt } = ssoToken;
  61282. const existingToken = { token: accessToken, expiration: new Date(expiresAt) };
  61283. if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {
  61284. return existingToken;
  61285. }
  61286. if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) {
  61287. validateTokenExpiry(existingToken);
  61288. return existingToken;
  61289. }
  61290. validateTokenKey("clientId", ssoToken.clientId, true);
  61291. validateTokenKey("clientSecret", ssoToken.clientSecret, true);
  61292. validateTokenKey("refreshToken", ssoToken.refreshToken, true);
  61293. try {
  61294. lastRefreshAttemptTime.setTime(Date.now());
  61295. const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init2);
  61296. validateTokenKey("accessToken", newSsoOidcToken.accessToken);
  61297. validateTokenKey("expiresIn", newSsoOidcToken.expiresIn);
  61298. const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3);
  61299. try {
  61300. await writeSSOTokenToFile(ssoSessionName, {
  61301. ...ssoToken,
  61302. accessToken: newSsoOidcToken.accessToken,
  61303. expiresAt: newTokenExpiration.toISOString(),
  61304. refreshToken: newSsoOidcToken.refreshToken
  61305. });
  61306. } catch (error2) {
  61307. }
  61308. return {
  61309. token: newSsoOidcToken.accessToken,
  61310. expiration: newTokenExpiration
  61311. };
  61312. } catch (error2) {
  61313. validateTokenExpiry(existingToken);
  61314. return existingToken;
  61315. }
  61316. }, "fromSso");
  61317. var fromStatic = /* @__PURE__ */ __name(({ token, logger: logger3 }) => async () => {
  61318. logger3 == null ? void 0 : logger3.debug("@aws-sdk/token-providers - fromStatic");
  61319. if (!token || !token.token) {
  61320. throw new import_property_provider2.TokenProviderError(`Please pass a valid token to fromStatic`, false);
  61321. }
  61322. return token;
  61323. }, "fromStatic");
  61324. var nodeProvider = /* @__PURE__ */ __name((init2 = {}) => (0, import_property_provider2.memoize)(
  61325. (0, import_property_provider2.chain)(fromSso(init2), async () => {
  61326. throw new import_property_provider2.TokenProviderError("Could not load token from any providers", false);
  61327. }),
  61328. (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5,
  61329. (token) => token.expiration !== void 0
  61330. ), "nodeProvider");
  61331. }
  61332. });
  61333. // ../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js
  61334. var require_dist_cjs46 = __commonJS({
  61335. "../node_modules/.pnpm/@aws-sdk+credential-provider-sso@3.817.0/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js"(exports2, module2) {
  61336. "use strict";
  61337. var __defProp3 = Object.defineProperty;
  61338. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  61339. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  61340. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  61341. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  61342. var __esm2 = (fn, res) => function __init() {
  61343. return fn && (res = (0, fn[__getOwnPropNames3(fn)[0]])(fn = 0)), res;
  61344. };
  61345. var __export2 = (target, all) => {
  61346. for (var name in all)
  61347. __defProp3(target, name, { get: all[name], enumerable: true });
  61348. };
  61349. var __copyProps3 = (to, from, except, desc) => {
  61350. if (from && typeof from === "object" || typeof from === "function") {
  61351. for (let key of __getOwnPropNames3(from))
  61352. if (!__hasOwnProp3.call(to, key) && key !== except)
  61353. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  61354. }
  61355. return to;
  61356. };
  61357. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  61358. var loadSso_exports = {};
  61359. __export2(loadSso_exports, {
  61360. GetRoleCredentialsCommand: () => import_client_sso.GetRoleCredentialsCommand,
  61361. SSOClient: () => import_client_sso.SSOClient
  61362. });
  61363. var import_client_sso;
  61364. var init_loadSso = __esm2({
  61365. "src/loadSso.ts"() {
  61366. "use strict";
  61367. import_client_sso = require_dist_cjs44();
  61368. }
  61369. });
  61370. var index_exports = {};
  61371. __export2(index_exports, {
  61372. fromSSO: () => fromSSO,
  61373. isSsoProfile: () => isSsoProfile,
  61374. validateSsoProfile: () => validateSsoProfile
  61375. });
  61376. module2.exports = __toCommonJS2(index_exports);
  61377. var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile");
  61378. var import_client3 = (init_client(), __toCommonJS(client_exports));
  61379. var import_token_providers = require_dist_cjs45();
  61380. var import_property_provider2 = require_dist_cjs20();
  61381. var import_shared_ini_file_loader = require_dist_cjs28();
  61382. var SHOULD_FAIL_CREDENTIAL_CHAIN = false;
  61383. var resolveSSOCredentials = /* @__PURE__ */ __name(async ({
  61384. ssoStartUrl,
  61385. ssoSession,
  61386. ssoAccountId,
  61387. ssoRegion,
  61388. ssoRoleName,
  61389. ssoClient,
  61390. clientConfig,
  61391. parentClientConfig,
  61392. profile,
  61393. logger: logger3
  61394. }) => {
  61395. let token;
  61396. const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`;
  61397. if (ssoSession) {
  61398. try {
  61399. const _token = await (0, import_token_providers.fromSso)({ profile })();
  61400. token = {
  61401. accessToken: _token.token,
  61402. expiresAt: new Date(_token.expiration).toISOString()
  61403. };
  61404. } catch (e4) {
  61405. throw new import_property_provider2.CredentialsProviderError(e4.message, {
  61406. tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
  61407. logger: logger3
  61408. });
  61409. }
  61410. } else {
  61411. try {
  61412. token = await (0, import_shared_ini_file_loader.getSSOTokenFromFile)(ssoStartUrl);
  61413. } catch (e4) {
  61414. throw new import_property_provider2.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, {
  61415. tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
  61416. logger: logger3
  61417. });
  61418. }
  61419. }
  61420. if (new Date(token.expiresAt).getTime() - Date.now() <= 0) {
  61421. throw new import_property_provider2.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, {
  61422. tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
  61423. logger: logger3
  61424. });
  61425. }
  61426. const { accessToken } = token;
  61427. const { SSOClient: SSOClient2, GetRoleCredentialsCommand: GetRoleCredentialsCommand2 } = await Promise.resolve().then(() => (init_loadSso(), loadSso_exports));
  61428. const sso = ssoClient || new SSOClient2(
  61429. Object.assign({}, clientConfig ?? {}, {
  61430. logger: (clientConfig == null ? void 0 : clientConfig.logger) ?? (parentClientConfig == null ? void 0 : parentClientConfig.logger),
  61431. region: (clientConfig == null ? void 0 : clientConfig.region) ?? ssoRegion
  61432. })
  61433. );
  61434. let ssoResp;
  61435. try {
  61436. ssoResp = await sso.send(
  61437. new GetRoleCredentialsCommand2({
  61438. accountId: ssoAccountId,
  61439. roleName: ssoRoleName,
  61440. accessToken
  61441. })
  61442. );
  61443. } catch (e4) {
  61444. throw new import_property_provider2.CredentialsProviderError(e4, {
  61445. tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
  61446. logger: logger3
  61447. });
  61448. }
  61449. const {
  61450. roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}
  61451. } = ssoResp;
  61452. if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) {
  61453. throw new import_property_provider2.CredentialsProviderError("SSO returns an invalid temporary credential.", {
  61454. tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN,
  61455. logger: logger3
  61456. });
  61457. }
  61458. const credentials2 = {
  61459. accessKeyId,
  61460. secretAccessKey,
  61461. sessionToken,
  61462. expiration: new Date(expiration),
  61463. ...credentialScope && { credentialScope },
  61464. ...accountId && { accountId }
  61465. };
  61466. if (ssoSession) {
  61467. (0, import_client3.setCredentialFeature)(credentials2, "CREDENTIALS_SSO", "s");
  61468. } else {
  61469. (0, import_client3.setCredentialFeature)(credentials2, "CREDENTIALS_SSO_LEGACY", "u");
  61470. }
  61471. return credentials2;
  61472. }, "resolveSSOCredentials");
  61473. var validateSsoProfile = /* @__PURE__ */ __name((profile, logger3) => {
  61474. const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile;
  61475. if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) {
  61476. throw new import_property_provider2.CredentialsProviderError(
  61477. `Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(
  61478. ", "
  61479. )}
  61480. Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,
  61481. { tryNextLink: false, logger: logger3 }
  61482. );
  61483. }
  61484. return profile;
  61485. }, "validateSsoProfile");
  61486. var fromSSO = /* @__PURE__ */ __name((init2 = {}) => async ({ callerClientConfig } = {}) => {
  61487. var _a2;
  61488. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-sso - fromSSO");
  61489. const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
  61490. const { ssoClient } = init2;
  61491. const profileName = (0, import_shared_ini_file_loader.getProfileName)({
  61492. profile: init2.profile ?? (callerClientConfig == null ? void 0 : callerClientConfig.profile)
  61493. });
  61494. if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
  61495. const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
  61496. const profile = profiles[profileName];
  61497. if (!profile) {
  61498. throw new import_property_provider2.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init2.logger });
  61499. }
  61500. if (!isSsoProfile(profile)) {
  61501. throw new import_property_provider2.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, {
  61502. logger: init2.logger
  61503. });
  61504. }
  61505. if (profile == null ? void 0 : profile.sso_session) {
  61506. const ssoSessions = await (0, import_shared_ini_file_loader.loadSsoSessionData)(init2);
  61507. const session = ssoSessions[profile.sso_session];
  61508. const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`;
  61509. if (ssoRegion && ssoRegion !== session.sso_region) {
  61510. throw new import_property_provider2.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, {
  61511. tryNextLink: false,
  61512. logger: init2.logger
  61513. });
  61514. }
  61515. if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) {
  61516. throw new import_property_provider2.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, {
  61517. tryNextLink: false,
  61518. logger: init2.logger
  61519. });
  61520. }
  61521. profile.sso_region = session.sso_region;
  61522. profile.sso_start_url = session.sso_start_url;
  61523. }
  61524. const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(
  61525. profile,
  61526. init2.logger
  61527. );
  61528. return resolveSSOCredentials({
  61529. ssoStartUrl: sso_start_url,
  61530. ssoSession: sso_session,
  61531. ssoAccountId: sso_account_id,
  61532. ssoRegion: sso_region,
  61533. ssoRoleName: sso_role_name,
  61534. ssoClient,
  61535. clientConfig: init2.clientConfig,
  61536. parentClientConfig: init2.parentClientConfig,
  61537. profile: profileName
  61538. });
  61539. } else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) {
  61540. throw new import_property_provider2.CredentialsProviderError(
  61541. 'Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"',
  61542. { tryNextLink: false, logger: init2.logger }
  61543. );
  61544. } else {
  61545. return resolveSSOCredentials({
  61546. ssoStartUrl,
  61547. ssoSession,
  61548. ssoAccountId,
  61549. ssoRegion,
  61550. ssoRoleName,
  61551. ssoClient,
  61552. clientConfig: init2.clientConfig,
  61553. parentClientConfig: init2.parentClientConfig,
  61554. profile: profileName
  61555. });
  61556. }
  61557. }, "fromSSO");
  61558. }
  61559. });
  61560. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js
  61561. function createAwsAuthSigv4HttpAuthOption2(authParameters) {
  61562. return {
  61563. schemeId: "aws.auth#sigv4",
  61564. signingProperties: {
  61565. name: "sts",
  61566. region: authParameters.region
  61567. },
  61568. propertiesExtractor: (config, context) => ({
  61569. signingProperties: {
  61570. config,
  61571. context
  61572. }
  61573. })
  61574. };
  61575. }
  61576. function createSmithyApiNoAuthHttpAuthOption2(authParameters) {
  61577. return {
  61578. schemeId: "smithy.api#noAuth"
  61579. };
  61580. }
  61581. var import_util_middleware6, defaultSTSHttpAuthSchemeParametersProvider, defaultSTSHttpAuthSchemeProvider, resolveStsAuthConfig, resolveHttpAuthSchemeConfig2;
  61582. var init_httpAuthSchemeProvider2 = __esm({
  61583. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js"() {
  61584. init_dist_es2();
  61585. import_util_middleware6 = __toESM(require_dist_cjs6());
  61586. init_STSClient();
  61587. defaultSTSHttpAuthSchemeParametersProvider = async (config, context, input) => {
  61588. return {
  61589. operation: (0, import_util_middleware6.getSmithyContext)(context).operation,
  61590. region: await (0, import_util_middleware6.normalizeProvider)(config.region)() || (() => {
  61591. throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
  61592. })()
  61593. };
  61594. };
  61595. defaultSTSHttpAuthSchemeProvider = (authParameters) => {
  61596. const options = [];
  61597. switch (authParameters.operation) {
  61598. case "AssumeRoleWithWebIdentity": {
  61599. options.push(createSmithyApiNoAuthHttpAuthOption2(authParameters));
  61600. break;
  61601. }
  61602. default: {
  61603. options.push(createAwsAuthSigv4HttpAuthOption2(authParameters));
  61604. }
  61605. }
  61606. return options;
  61607. };
  61608. resolveStsAuthConfig = (input) => Object.assign(input, {
  61609. stsClientCtor: STSClient
  61610. });
  61611. resolveHttpAuthSchemeConfig2 = (config) => {
  61612. const config_0 = resolveStsAuthConfig(config);
  61613. const config_1 = resolveAwsSdkSigV4Config(config_0);
  61614. return Object.assign(config_1, {
  61615. authSchemePreference: (0, import_util_middleware6.normalizeProvider)(config.authSchemePreference ?? [])
  61616. });
  61617. };
  61618. }
  61619. });
  61620. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js
  61621. var resolveClientEndpointParameters2, commonParams2;
  61622. var init_EndpointParameters2 = __esm({
  61623. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js"() {
  61624. resolveClientEndpointParameters2 = (options) => {
  61625. return Object.assign(options, {
  61626. useDualstackEndpoint: options.useDualstackEndpoint ?? false,
  61627. useFipsEndpoint: options.useFipsEndpoint ?? false,
  61628. useGlobalEndpoint: options.useGlobalEndpoint ?? false,
  61629. defaultSigningName: "sts"
  61630. });
  61631. };
  61632. commonParams2 = {
  61633. UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" },
  61634. UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
  61635. Endpoint: { type: "builtInParams", name: "endpoint" },
  61636. Region: { type: "builtInParams", name: "region" },
  61637. UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
  61638. };
  61639. }
  61640. });
  61641. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js
  61642. var F2, G, H, I, J, a2, b2, c2, d2, e3, f4, g2, h3, i3, j2, k2, l2, m3, n2, o2, p2, q2, r3, s3, t3, u2, v2, w2, x3, y, z, A2, B, C, D, E, _data2, ruleSet2;
  61643. var init_ruleset2 = __esm({
  61644. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js"() {
  61645. F2 = "required";
  61646. G = "type";
  61647. H = "fn";
  61648. I = "argv";
  61649. J = "ref";
  61650. a2 = false;
  61651. b2 = true;
  61652. c2 = "booleanEquals";
  61653. d2 = "stringEquals";
  61654. e3 = "sigv4";
  61655. f4 = "sts";
  61656. g2 = "us-east-1";
  61657. h3 = "endpoint";
  61658. i3 = "https://sts.{Region}.{PartitionResult#dnsSuffix}";
  61659. j2 = "tree";
  61660. k2 = "error";
  61661. l2 = "getAttr";
  61662. m3 = { [F2]: false, [G]: "String" };
  61663. n2 = { [F2]: true, "default": false, [G]: "Boolean" };
  61664. o2 = { [J]: "Endpoint" };
  61665. p2 = { [H]: "isSet", [I]: [{ [J]: "Region" }] };
  61666. q2 = { [J]: "Region" };
  61667. r3 = { [H]: "aws.partition", [I]: [q2], "assign": "PartitionResult" };
  61668. s3 = { [J]: "UseFIPS" };
  61669. t3 = { [J]: "UseDualStack" };
  61670. u2 = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e3, "signingName": f4, "signingRegion": g2 }] }, "headers": {} };
  61671. v2 = {};
  61672. w2 = { "conditions": [{ [H]: d2, [I]: [q2, "aws-global"] }], [h3]: u2, [G]: h3 };
  61673. x3 = { [H]: c2, [I]: [s3, true] };
  61674. y = { [H]: c2, [I]: [t3, true] };
  61675. z = { [H]: l2, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] };
  61676. A2 = { [J]: "PartitionResult" };
  61677. B = { [H]: c2, [I]: [true, { [H]: l2, [I]: [A2, "supportsDualStack"] }] };
  61678. C = [{ [H]: "isSet", [I]: [o2] }];
  61679. D = [x3];
  61680. E = [y];
  61681. _data2 = { version: "1.0", parameters: { Region: m3, UseDualStack: n2, UseFIPS: n2, Endpoint: m3, UseGlobalEndpoint: n2 }, rules: [{ conditions: [{ [H]: c2, [I]: [{ [J]: "UseGlobalEndpoint" }, b2] }, { [H]: "not", [I]: C }, p2, r3, { [H]: c2, [I]: [s3, a2] }, { [H]: c2, [I]: [t3, a2] }], rules: [{ conditions: [{ [H]: d2, [I]: [q2, "ap-northeast-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "ap-south-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "ap-southeast-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "ap-southeast-2"] }], endpoint: u2, [G]: h3 }, w2, { conditions: [{ [H]: d2, [I]: [q2, "ca-central-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-central-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-north-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-west-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-west-2"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "eu-west-3"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "sa-east-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, g2] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "us-east-2"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "us-west-1"] }], endpoint: u2, [G]: h3 }, { conditions: [{ [H]: d2, [I]: [q2, "us-west-2"] }], endpoint: u2, [G]: h3 }, { endpoint: { url: i3, properties: { authSchemes: [{ name: e3, signingName: f4, signingRegion: "{Region}" }] }, headers: v2 }, [G]: h3 }], [G]: j2 }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k2 }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k2 }, { endpoint: { url: o2, properties: v2, headers: v2 }, [G]: h3 }], [G]: j2 }, { conditions: [p2], rules: [{ conditions: [r3], rules: [{ conditions: [x3, y], rules: [{ conditions: [{ [H]: c2, [I]: [b2, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v2, headers: v2 }, [G]: h3 }], [G]: j2 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k2 }], [G]: j2 }, { conditions: D, rules: [{ conditions: [{ [H]: c2, [I]: [z, b2] }], rules: [{ conditions: [{ [H]: d2, [I]: [{ [H]: l2, [I]: [A2, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v2, headers: v2 }, [G]: h3 }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v2, headers: v2 }, [G]: h3 }], [G]: j2 }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k2 }], [G]: j2 }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v2, headers: v2 }, [G]: h3 }], [G]: j2 }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k2 }], [G]: j2 }, w2, { endpoint: { url: i3, properties: v2, headers: v2 }, [G]: h3 }], [G]: j2 }], [G]: j2 }, { error: "Invalid Configuration: Missing Region", [G]: k2 }] };
  61682. ruleSet2 = _data2;
  61683. }
  61684. });
  61685. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js
  61686. var import_util_endpoints3, import_util_endpoints4, cache2, defaultEndpointResolver2;
  61687. var init_endpointResolver2 = __esm({
  61688. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js"() {
  61689. import_util_endpoints3 = __toESM(require_dist_cjs19());
  61690. import_util_endpoints4 = __toESM(require_dist_cjs18());
  61691. init_ruleset2();
  61692. cache2 = new import_util_endpoints4.EndpointCache({
  61693. size: 50,
  61694. params: ["Endpoint", "Region", "UseDualStack", "UseFIPS", "UseGlobalEndpoint"]
  61695. });
  61696. defaultEndpointResolver2 = (endpointParams, context = {}) => {
  61697. return cache2.get(endpointParams, () => (0, import_util_endpoints4.resolveEndpoint)(ruleSet2, {
  61698. endpointParams,
  61699. logger: context.logger
  61700. }));
  61701. };
  61702. import_util_endpoints4.customEndpointFunctions.aws = import_util_endpoints3.awsEndpointFunctions;
  61703. }
  61704. });
  61705. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js
  61706. var import_smithy_client14, import_url_parser2, import_util_base644, import_util_utf84, getRuntimeConfig3;
  61707. var init_runtimeConfig_shared2 = __esm({
  61708. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js"() {
  61709. init_dist_es2();
  61710. init_dist_es();
  61711. import_smithy_client14 = __toESM(require_dist_cjs23());
  61712. import_url_parser2 = __toESM(require_dist_cjs31());
  61713. import_util_base644 = __toESM(require_dist_cjs11());
  61714. import_util_utf84 = __toESM(require_dist_cjs10());
  61715. init_httpAuthSchemeProvider2();
  61716. init_endpointResolver2();
  61717. getRuntimeConfig3 = (config) => {
  61718. return {
  61719. apiVersion: "2011-06-15",
  61720. base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? import_util_base644.fromBase64,
  61721. base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? import_util_base644.toBase64,
  61722. disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
  61723. endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? defaultEndpointResolver2,
  61724. extensions: (config == null ? void 0 : config.extensions) ?? [],
  61725. httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? defaultSTSHttpAuthSchemeProvider,
  61726. httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
  61727. {
  61728. schemeId: "aws.auth#sigv4",
  61729. identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
  61730. signer: new AwsSdkSigV4Signer()
  61731. },
  61732. {
  61733. schemeId: "smithy.api#noAuth",
  61734. identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
  61735. signer: new NoAuthSigner()
  61736. }
  61737. ],
  61738. logger: (config == null ? void 0 : config.logger) ?? new import_smithy_client14.NoOpLogger(),
  61739. serviceId: (config == null ? void 0 : config.serviceId) ?? "STS",
  61740. urlParser: (config == null ? void 0 : config.urlParser) ?? import_url_parser2.parseUrl,
  61741. utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? import_util_utf84.fromUtf8,
  61742. utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? import_util_utf84.toUtf8
  61743. };
  61744. };
  61745. }
  61746. });
  61747. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js
  61748. var import_util_user_agent_node2, import_config_resolver3, import_hash_node2, import_middleware_retry3, import_node_config_provider2, import_node_http_handler2, import_util_body_length_node2, import_util_retry2, import_smithy_client15, import_util_defaults_mode_node2, import_smithy_client16, getRuntimeConfig4;
  61749. var init_runtimeConfig2 = __esm({
  61750. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js"() {
  61751. init_package();
  61752. init_dist_es2();
  61753. import_util_user_agent_node2 = __toESM(require_dist_cjs39());
  61754. import_config_resolver3 = __toESM(require_dist_cjs26());
  61755. init_dist_es();
  61756. import_hash_node2 = __toESM(require_dist_cjs40());
  61757. import_middleware_retry3 = __toESM(require_dist_cjs35());
  61758. import_node_config_provider2 = __toESM(require_dist_cjs29());
  61759. import_node_http_handler2 = __toESM(require_dist_cjs14());
  61760. import_util_body_length_node2 = __toESM(require_dist_cjs41());
  61761. import_util_retry2 = __toESM(require_dist_cjs34());
  61762. init_runtimeConfig_shared2();
  61763. import_smithy_client15 = __toESM(require_dist_cjs23());
  61764. import_util_defaults_mode_node2 = __toESM(require_dist_cjs42());
  61765. import_smithy_client16 = __toESM(require_dist_cjs23());
  61766. getRuntimeConfig4 = (config) => {
  61767. (0, import_smithy_client16.emitWarningIfUnsupportedVersion)(process.version);
  61768. const defaultsMode = (0, import_util_defaults_mode_node2.resolveDefaultsModeConfig)(config);
  61769. const defaultConfigProvider = () => defaultsMode().then(import_smithy_client15.loadConfigsForDefaultMode);
  61770. const clientSharedValues = getRuntimeConfig3(config);
  61771. emitWarningIfUnsupportedVersion(process.version);
  61772. const loaderConfig = {
  61773. profile: config == null ? void 0 : config.profile,
  61774. logger: clientSharedValues.logger
  61775. };
  61776. return {
  61777. ...clientSharedValues,
  61778. ...config,
  61779. runtime: "node",
  61780. defaultsMode,
  61781. authSchemePreference: (config == null ? void 0 : config.authSchemePreference) ?? (0, import_node_config_provider2.loadConfig)(NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
  61782. bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? import_util_body_length_node2.calculateBodyLength,
  61783. defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, import_util_user_agent_node2.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }),
  61784. httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
  61785. {
  61786. schemeId: "aws.auth#sigv4",
  61787. identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || (async (idProps) => await config.credentialDefaultProvider((idProps == null ? void 0 : idProps.__config) || {})()),
  61788. signer: new AwsSdkSigV4Signer()
  61789. },
  61790. {
  61791. schemeId: "smithy.api#noAuth",
  61792. identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})),
  61793. signer: new NoAuthSigner()
  61794. }
  61795. ],
  61796. maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, import_node_config_provider2.loadConfig)(import_middleware_retry3.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
  61797. region: (config == null ? void 0 : config.region) ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver3.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
  61798. requestHandler: import_node_http_handler2.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
  61799. retryMode: (config == null ? void 0 : config.retryMode) ?? (0, import_node_config_provider2.loadConfig)({
  61800. ...import_middleware_retry3.NODE_RETRY_MODE_CONFIG_OPTIONS,
  61801. default: async () => (await defaultConfigProvider()).retryMode || import_util_retry2.DEFAULT_RETRY_MODE
  61802. }, config),
  61803. sha256: (config == null ? void 0 : config.sha256) ?? import_hash_node2.Hash.bind(null, "sha256"),
  61804. streamCollector: (config == null ? void 0 : config.streamCollector) ?? import_node_http_handler2.streamCollector,
  61805. useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  61806. useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, import_node_config_provider2.loadConfig)(import_config_resolver3.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  61807. userAgentAppId: (config == null ? void 0 : config.userAgentAppId) ?? (0, import_node_config_provider2.loadConfig)(import_util_user_agent_node2.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
  61808. };
  61809. };
  61810. }
  61811. });
  61812. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js
  61813. var getHttpAuthExtensionConfiguration2, resolveHttpAuthRuntimeConfig2;
  61814. var init_httpAuthExtensionConfiguration2 = __esm({
  61815. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js"() {
  61816. getHttpAuthExtensionConfiguration2 = (runtimeConfig) => {
  61817. const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
  61818. let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
  61819. let _credentials = runtimeConfig.credentials;
  61820. return {
  61821. setHttpAuthScheme(httpAuthScheme) {
  61822. const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
  61823. if (index6 === -1) {
  61824. _httpAuthSchemes.push(httpAuthScheme);
  61825. } else {
  61826. _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
  61827. }
  61828. },
  61829. httpAuthSchemes() {
  61830. return _httpAuthSchemes;
  61831. },
  61832. setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
  61833. _httpAuthSchemeProvider = httpAuthSchemeProvider;
  61834. },
  61835. httpAuthSchemeProvider() {
  61836. return _httpAuthSchemeProvider;
  61837. },
  61838. setCredentials(credentials2) {
  61839. _credentials = credentials2;
  61840. },
  61841. credentials() {
  61842. return _credentials;
  61843. }
  61844. };
  61845. };
  61846. resolveHttpAuthRuntimeConfig2 = (config) => {
  61847. return {
  61848. httpAuthSchemes: config.httpAuthSchemes(),
  61849. httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
  61850. credentials: config.credentials()
  61851. };
  61852. };
  61853. }
  61854. });
  61855. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js
  61856. var import_region_config_resolver2, import_protocol_http13, import_smithy_client17, resolveRuntimeExtensions2;
  61857. var init_runtimeExtensions2 = __esm({
  61858. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js"() {
  61859. import_region_config_resolver2 = __toESM(require_dist_cjs43());
  61860. import_protocol_http13 = __toESM(require_dist_cjs2());
  61861. import_smithy_client17 = __toESM(require_dist_cjs23());
  61862. init_httpAuthExtensionConfiguration2();
  61863. resolveRuntimeExtensions2 = (runtimeConfig, extensions) => {
  61864. const extensionConfiguration = Object.assign((0, import_region_config_resolver2.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, import_smithy_client17.getDefaultExtensionConfiguration)(runtimeConfig), (0, import_protocol_http13.getHttpHandlerExtensionConfiguration)(runtimeConfig), getHttpAuthExtensionConfiguration2(runtimeConfig));
  61865. extensions.forEach((extension) => extension.configure(extensionConfiguration));
  61866. return Object.assign(runtimeConfig, (0, import_region_config_resolver2.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, import_smithy_client17.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, import_protocol_http13.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), resolveHttpAuthRuntimeConfig2(extensionConfiguration));
  61867. };
  61868. }
  61869. });
  61870. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js
  61871. var import_middleware_host_header2, import_middleware_logger2, import_middleware_recursion_detection2, import_middleware_user_agent2, import_config_resolver4, import_middleware_content_length2, import_middleware_endpoint3, import_middleware_retry4, import_smithy_client18, STSClient;
  61872. var init_STSClient = __esm({
  61873. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js"() {
  61874. import_middleware_host_header2 = __toESM(require_dist_cjs3());
  61875. import_middleware_logger2 = __toESM(require_dist_cjs4());
  61876. import_middleware_recursion_detection2 = __toESM(require_dist_cjs5());
  61877. import_middleware_user_agent2 = __toESM(require_dist_cjs24());
  61878. import_config_resolver4 = __toESM(require_dist_cjs26());
  61879. init_dist_es();
  61880. import_middleware_content_length2 = __toESM(require_dist_cjs27());
  61881. import_middleware_endpoint3 = __toESM(require_dist_cjs32());
  61882. import_middleware_retry4 = __toESM(require_dist_cjs35());
  61883. import_smithy_client18 = __toESM(require_dist_cjs23());
  61884. init_httpAuthSchemeProvider2();
  61885. init_EndpointParameters2();
  61886. init_runtimeConfig2();
  61887. init_runtimeExtensions2();
  61888. STSClient = class extends import_smithy_client18.Client {
  61889. config;
  61890. constructor(...[configuration]) {
  61891. const _config_0 = getRuntimeConfig4(configuration || {});
  61892. super(_config_0);
  61893. this.initConfig = _config_0;
  61894. const _config_1 = resolveClientEndpointParameters2(_config_0);
  61895. const _config_2 = (0, import_middleware_user_agent2.resolveUserAgentConfig)(_config_1);
  61896. const _config_3 = (0, import_middleware_retry4.resolveRetryConfig)(_config_2);
  61897. const _config_4 = (0, import_config_resolver4.resolveRegionConfig)(_config_3);
  61898. const _config_5 = (0, import_middleware_host_header2.resolveHostHeaderConfig)(_config_4);
  61899. const _config_6 = (0, import_middleware_endpoint3.resolveEndpointConfig)(_config_5);
  61900. const _config_7 = resolveHttpAuthSchemeConfig2(_config_6);
  61901. const _config_8 = resolveRuntimeExtensions2(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
  61902. this.config = _config_8;
  61903. this.middlewareStack.use((0, import_middleware_user_agent2.getUserAgentPlugin)(this.config));
  61904. this.middlewareStack.use((0, import_middleware_retry4.getRetryPlugin)(this.config));
  61905. this.middlewareStack.use((0, import_middleware_content_length2.getContentLengthPlugin)(this.config));
  61906. this.middlewareStack.use((0, import_middleware_host_header2.getHostHeaderPlugin)(this.config));
  61907. this.middlewareStack.use((0, import_middleware_logger2.getLoggerPlugin)(this.config));
  61908. this.middlewareStack.use((0, import_middleware_recursion_detection2.getRecursionDetectionPlugin)(this.config));
  61909. this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
  61910. httpAuthSchemeParametersProvider: defaultSTSHttpAuthSchemeParametersProvider,
  61911. identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
  61912. "aws.auth#sigv4": config.credentials
  61913. })
  61914. }));
  61915. this.middlewareStack.use(getHttpSigningPlugin(this.config));
  61916. }
  61917. destroy() {
  61918. super.destroy();
  61919. }
  61920. };
  61921. }
  61922. });
  61923. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js
  61924. var import_smithy_client19, STSServiceException;
  61925. var init_STSServiceException = __esm({
  61926. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js"() {
  61927. import_smithy_client19 = __toESM(require_dist_cjs23());
  61928. STSServiceException = class _STSServiceException extends import_smithy_client19.ServiceException {
  61929. constructor(options) {
  61930. super(options);
  61931. Object.setPrototypeOf(this, _STSServiceException.prototype);
  61932. }
  61933. };
  61934. }
  61935. });
  61936. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js
  61937. var import_smithy_client20, CredentialsFilterSensitiveLog, AssumeRoleResponseFilterSensitiveLog, ExpiredTokenException2, MalformedPolicyDocumentException, PackedPolicyTooLargeException, RegionDisabledException, IDPRejectedClaimException, InvalidIdentityTokenException, AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog, IDPCommunicationErrorException;
  61938. var init_models_02 = __esm({
  61939. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js"() {
  61940. import_smithy_client20 = __toESM(require_dist_cjs23());
  61941. init_STSServiceException();
  61942. CredentialsFilterSensitiveLog = (obj) => ({
  61943. ...obj,
  61944. ...obj.SecretAccessKey && { SecretAccessKey: import_smithy_client20.SENSITIVE_STRING }
  61945. });
  61946. AssumeRoleResponseFilterSensitiveLog = (obj) => ({
  61947. ...obj,
  61948. ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
  61949. });
  61950. ExpiredTokenException2 = class _ExpiredTokenException extends STSServiceException {
  61951. name = "ExpiredTokenException";
  61952. $fault = "client";
  61953. constructor(opts) {
  61954. super({
  61955. name: "ExpiredTokenException",
  61956. $fault: "client",
  61957. ...opts
  61958. });
  61959. Object.setPrototypeOf(this, _ExpiredTokenException.prototype);
  61960. }
  61961. };
  61962. MalformedPolicyDocumentException = class _MalformedPolicyDocumentException extends STSServiceException {
  61963. name = "MalformedPolicyDocumentException";
  61964. $fault = "client";
  61965. constructor(opts) {
  61966. super({
  61967. name: "MalformedPolicyDocumentException",
  61968. $fault: "client",
  61969. ...opts
  61970. });
  61971. Object.setPrototypeOf(this, _MalformedPolicyDocumentException.prototype);
  61972. }
  61973. };
  61974. PackedPolicyTooLargeException = class _PackedPolicyTooLargeException extends STSServiceException {
  61975. name = "PackedPolicyTooLargeException";
  61976. $fault = "client";
  61977. constructor(opts) {
  61978. super({
  61979. name: "PackedPolicyTooLargeException",
  61980. $fault: "client",
  61981. ...opts
  61982. });
  61983. Object.setPrototypeOf(this, _PackedPolicyTooLargeException.prototype);
  61984. }
  61985. };
  61986. RegionDisabledException = class _RegionDisabledException extends STSServiceException {
  61987. name = "RegionDisabledException";
  61988. $fault = "client";
  61989. constructor(opts) {
  61990. super({
  61991. name: "RegionDisabledException",
  61992. $fault: "client",
  61993. ...opts
  61994. });
  61995. Object.setPrototypeOf(this, _RegionDisabledException.prototype);
  61996. }
  61997. };
  61998. IDPRejectedClaimException = class _IDPRejectedClaimException extends STSServiceException {
  61999. name = "IDPRejectedClaimException";
  62000. $fault = "client";
  62001. constructor(opts) {
  62002. super({
  62003. name: "IDPRejectedClaimException",
  62004. $fault: "client",
  62005. ...opts
  62006. });
  62007. Object.setPrototypeOf(this, _IDPRejectedClaimException.prototype);
  62008. }
  62009. };
  62010. InvalidIdentityTokenException = class _InvalidIdentityTokenException extends STSServiceException {
  62011. name = "InvalidIdentityTokenException";
  62012. $fault = "client";
  62013. constructor(opts) {
  62014. super({
  62015. name: "InvalidIdentityTokenException",
  62016. $fault: "client",
  62017. ...opts
  62018. });
  62019. Object.setPrototypeOf(this, _InvalidIdentityTokenException.prototype);
  62020. }
  62021. };
  62022. AssumeRoleWithWebIdentityRequestFilterSensitiveLog = (obj) => ({
  62023. ...obj,
  62024. ...obj.WebIdentityToken && { WebIdentityToken: import_smithy_client20.SENSITIVE_STRING }
  62025. });
  62026. AssumeRoleWithWebIdentityResponseFilterSensitiveLog = (obj) => ({
  62027. ...obj,
  62028. ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) }
  62029. });
  62030. IDPCommunicationErrorException = class _IDPCommunicationErrorException extends STSServiceException {
  62031. name = "IDPCommunicationErrorException";
  62032. $fault = "client";
  62033. constructor(opts) {
  62034. super({
  62035. name: "IDPCommunicationErrorException",
  62036. $fault: "client",
  62037. ...opts
  62038. });
  62039. Object.setPrototypeOf(this, _IDPCommunicationErrorException.prototype);
  62040. }
  62041. };
  62042. }
  62043. });
  62044. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/protocols/Aws_query.js
  62045. var import_protocol_http14, import_smithy_client21, se_AssumeRoleCommand, se_AssumeRoleWithWebIdentityCommand, de_AssumeRoleCommand, de_AssumeRoleWithWebIdentityCommand, de_CommandError2, de_ExpiredTokenExceptionRes2, de_IDPCommunicationErrorExceptionRes, de_IDPRejectedClaimExceptionRes, de_InvalidIdentityTokenExceptionRes, de_MalformedPolicyDocumentExceptionRes, de_PackedPolicyTooLargeExceptionRes, de_RegionDisabledExceptionRes, se_AssumeRoleRequest, se_AssumeRoleWithWebIdentityRequest, se_policyDescriptorListType, se_PolicyDescriptorType, se_ProvidedContext, se_ProvidedContextsListType, se_Tag, se_tagKeyListType, se_tagListType, de_AssumedRoleUser, de_AssumeRoleResponse, de_AssumeRoleWithWebIdentityResponse, de_Credentials, de_ExpiredTokenException, de_IDPCommunicationErrorException, de_IDPRejectedClaimException, de_InvalidIdentityTokenException, de_MalformedPolicyDocumentException, de_PackedPolicyTooLargeException, de_RegionDisabledException, deserializeMetadata2, throwDefaultError2, buildHttpRpcRequest, SHARED_HEADERS, _2, _A, _AKI, _AR, _ARI, _ARU, _ARWWI, _Ar, _Au, _C, _CA, _DS, _E, _EI, _K, _P, _PA, _PAr, _PC, _PI, _PPS, _Pr, _RA, _RSN, _SAK, _SFWIT, _SI, _SN, _ST, _T, _TC, _TTK, _V, _Va, _WIT, _a, _m, buildFormUrlencodedString, loadQueryErrorCode;
  62046. var init_Aws_query = __esm({
  62047. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/protocols/Aws_query.js"() {
  62048. init_dist_es2();
  62049. import_protocol_http14 = __toESM(require_dist_cjs2());
  62050. import_smithy_client21 = __toESM(require_dist_cjs23());
  62051. init_models_02();
  62052. init_STSServiceException();
  62053. se_AssumeRoleCommand = async (input, context) => {
  62054. const headers = SHARED_HEADERS;
  62055. let body;
  62056. body = buildFormUrlencodedString({
  62057. ...se_AssumeRoleRequest(input, context),
  62058. [_A]: _AR,
  62059. [_V]: _2
  62060. });
  62061. return buildHttpRpcRequest(context, headers, "/", void 0, body);
  62062. };
  62063. se_AssumeRoleWithWebIdentityCommand = async (input, context) => {
  62064. const headers = SHARED_HEADERS;
  62065. let body;
  62066. body = buildFormUrlencodedString({
  62067. ...se_AssumeRoleWithWebIdentityRequest(input, context),
  62068. [_A]: _ARWWI,
  62069. [_V]: _2
  62070. });
  62071. return buildHttpRpcRequest(context, headers, "/", void 0, body);
  62072. };
  62073. de_AssumeRoleCommand = async (output, context) => {
  62074. if (output.statusCode >= 300) {
  62075. return de_CommandError2(output, context);
  62076. }
  62077. const data = await parseXmlBody(output.body, context);
  62078. let contents = {};
  62079. contents = de_AssumeRoleResponse(data.AssumeRoleResult, context);
  62080. const response = {
  62081. $metadata: deserializeMetadata2(output),
  62082. ...contents
  62083. };
  62084. return response;
  62085. };
  62086. de_AssumeRoleWithWebIdentityCommand = async (output, context) => {
  62087. if (output.statusCode >= 300) {
  62088. return de_CommandError2(output, context);
  62089. }
  62090. const data = await parseXmlBody(output.body, context);
  62091. let contents = {};
  62092. contents = de_AssumeRoleWithWebIdentityResponse(data.AssumeRoleWithWebIdentityResult, context);
  62093. const response = {
  62094. $metadata: deserializeMetadata2(output),
  62095. ...contents
  62096. };
  62097. return response;
  62098. };
  62099. de_CommandError2 = async (output, context) => {
  62100. const parsedOutput = {
  62101. ...output,
  62102. body: await parseXmlErrorBody(output.body, context)
  62103. };
  62104. const errorCode = loadQueryErrorCode(output, parsedOutput.body);
  62105. switch (errorCode) {
  62106. case "ExpiredTokenException":
  62107. case "com.amazonaws.sts#ExpiredTokenException":
  62108. throw await de_ExpiredTokenExceptionRes2(parsedOutput, context);
  62109. case "MalformedPolicyDocument":
  62110. case "com.amazonaws.sts#MalformedPolicyDocumentException":
  62111. throw await de_MalformedPolicyDocumentExceptionRes(parsedOutput, context);
  62112. case "PackedPolicyTooLarge":
  62113. case "com.amazonaws.sts#PackedPolicyTooLargeException":
  62114. throw await de_PackedPolicyTooLargeExceptionRes(parsedOutput, context);
  62115. case "RegionDisabledException":
  62116. case "com.amazonaws.sts#RegionDisabledException":
  62117. throw await de_RegionDisabledExceptionRes(parsedOutput, context);
  62118. case "IDPCommunicationError":
  62119. case "com.amazonaws.sts#IDPCommunicationErrorException":
  62120. throw await de_IDPCommunicationErrorExceptionRes(parsedOutput, context);
  62121. case "IDPRejectedClaim":
  62122. case "com.amazonaws.sts#IDPRejectedClaimException":
  62123. throw await de_IDPRejectedClaimExceptionRes(parsedOutput, context);
  62124. case "InvalidIdentityToken":
  62125. case "com.amazonaws.sts#InvalidIdentityTokenException":
  62126. throw await de_InvalidIdentityTokenExceptionRes(parsedOutput, context);
  62127. default:
  62128. const parsedBody = parsedOutput.body;
  62129. return throwDefaultError2({
  62130. output,
  62131. parsedBody: parsedBody.Error,
  62132. errorCode
  62133. });
  62134. }
  62135. };
  62136. de_ExpiredTokenExceptionRes2 = async (parsedOutput, context) => {
  62137. const body = parsedOutput.body;
  62138. const deserialized = de_ExpiredTokenException(body.Error, context);
  62139. const exception = new ExpiredTokenException2({
  62140. $metadata: deserializeMetadata2(parsedOutput),
  62141. ...deserialized
  62142. });
  62143. return (0, import_smithy_client21.decorateServiceException)(exception, body);
  62144. };
  62145. de_IDPCommunicationErrorExceptionRes = async (parsedOutput, context) => {
  62146. const body = parsedOutput.body;
  62147. const deserialized = de_IDPCommunicationErrorException(body.Error, context);
  62148. const exception = new IDPCommunicationErrorException({
  62149. $metadata: deserializeMetadata2(parsedOutput),
  62150. ...deserialized
  62151. });
  62152. return (0, import_smithy_client21.decorateServiceException)(exception, body);
  62153. };
  62154. de_IDPRejectedClaimExceptionRes = async (parsedOutput, context) => {
  62155. const body = parsedOutput.body;
  62156. const deserialized = de_IDPRejectedClaimException(body.Error, context);
  62157. const exception = new IDPRejectedClaimException({
  62158. $metadata: deserializeMetadata2(parsedOutput),
  62159. ...deserialized
  62160. });
  62161. return (0, import_smithy_client21.decorateServiceException)(exception, body);
  62162. };
  62163. de_InvalidIdentityTokenExceptionRes = async (parsedOutput, context) => {
  62164. const body = parsedOutput.body;
  62165. const deserialized = de_InvalidIdentityTokenException(body.Error, context);
  62166. const exception = new InvalidIdentityTokenException({
  62167. $metadata: deserializeMetadata2(parsedOutput),
  62168. ...deserialized
  62169. });
  62170. return (0, import_smithy_client21.decorateServiceException)(exception, body);
  62171. };
  62172. de_MalformedPolicyDocumentExceptionRes = async (parsedOutput, context) => {
  62173. const body = parsedOutput.body;
  62174. const deserialized = de_MalformedPolicyDocumentException(body.Error, context);
  62175. const exception = new MalformedPolicyDocumentException({
  62176. $metadata: deserializeMetadata2(parsedOutput),
  62177. ...deserialized
  62178. });
  62179. return (0, import_smithy_client21.decorateServiceException)(exception, body);
  62180. };
  62181. de_PackedPolicyTooLargeExceptionRes = async (parsedOutput, context) => {
  62182. const body = parsedOutput.body;
  62183. const deserialized = de_PackedPolicyTooLargeException(body.Error, context);
  62184. const exception = new PackedPolicyTooLargeException({
  62185. $metadata: deserializeMetadata2(parsedOutput),
  62186. ...deserialized
  62187. });
  62188. return (0, import_smithy_client21.decorateServiceException)(exception, body);
  62189. };
  62190. de_RegionDisabledExceptionRes = async (parsedOutput, context) => {
  62191. const body = parsedOutput.body;
  62192. const deserialized = de_RegionDisabledException(body.Error, context);
  62193. const exception = new RegionDisabledException({
  62194. $metadata: deserializeMetadata2(parsedOutput),
  62195. ...deserialized
  62196. });
  62197. return (0, import_smithy_client21.decorateServiceException)(exception, body);
  62198. };
  62199. se_AssumeRoleRequest = (input, context) => {
  62200. var _a2, _b, _c, _d;
  62201. const entries = {};
  62202. if (input[_RA] != null) {
  62203. entries[_RA] = input[_RA];
  62204. }
  62205. if (input[_RSN] != null) {
  62206. entries[_RSN] = input[_RSN];
  62207. }
  62208. if (input[_PA] != null) {
  62209. const memberEntries = se_policyDescriptorListType(input[_PA], context);
  62210. if (((_a2 = input[_PA]) == null ? void 0 : _a2.length) === 0) {
  62211. entries.PolicyArns = [];
  62212. }
  62213. Object.entries(memberEntries).forEach(([key, value]) => {
  62214. const loc = `PolicyArns.${key}`;
  62215. entries[loc] = value;
  62216. });
  62217. }
  62218. if (input[_P] != null) {
  62219. entries[_P] = input[_P];
  62220. }
  62221. if (input[_DS] != null) {
  62222. entries[_DS] = input[_DS];
  62223. }
  62224. if (input[_T] != null) {
  62225. const memberEntries = se_tagListType(input[_T], context);
  62226. if (((_b = input[_T]) == null ? void 0 : _b.length) === 0) {
  62227. entries.Tags = [];
  62228. }
  62229. Object.entries(memberEntries).forEach(([key, value]) => {
  62230. const loc = `Tags.${key}`;
  62231. entries[loc] = value;
  62232. });
  62233. }
  62234. if (input[_TTK] != null) {
  62235. const memberEntries = se_tagKeyListType(input[_TTK], context);
  62236. if (((_c = input[_TTK]) == null ? void 0 : _c.length) === 0) {
  62237. entries.TransitiveTagKeys = [];
  62238. }
  62239. Object.entries(memberEntries).forEach(([key, value]) => {
  62240. const loc = `TransitiveTagKeys.${key}`;
  62241. entries[loc] = value;
  62242. });
  62243. }
  62244. if (input[_EI] != null) {
  62245. entries[_EI] = input[_EI];
  62246. }
  62247. if (input[_SN] != null) {
  62248. entries[_SN] = input[_SN];
  62249. }
  62250. if (input[_TC] != null) {
  62251. entries[_TC] = input[_TC];
  62252. }
  62253. if (input[_SI] != null) {
  62254. entries[_SI] = input[_SI];
  62255. }
  62256. if (input[_PC] != null) {
  62257. const memberEntries = se_ProvidedContextsListType(input[_PC], context);
  62258. if (((_d = input[_PC]) == null ? void 0 : _d.length) === 0) {
  62259. entries.ProvidedContexts = [];
  62260. }
  62261. Object.entries(memberEntries).forEach(([key, value]) => {
  62262. const loc = `ProvidedContexts.${key}`;
  62263. entries[loc] = value;
  62264. });
  62265. }
  62266. return entries;
  62267. };
  62268. se_AssumeRoleWithWebIdentityRequest = (input, context) => {
  62269. var _a2;
  62270. const entries = {};
  62271. if (input[_RA] != null) {
  62272. entries[_RA] = input[_RA];
  62273. }
  62274. if (input[_RSN] != null) {
  62275. entries[_RSN] = input[_RSN];
  62276. }
  62277. if (input[_WIT] != null) {
  62278. entries[_WIT] = input[_WIT];
  62279. }
  62280. if (input[_PI] != null) {
  62281. entries[_PI] = input[_PI];
  62282. }
  62283. if (input[_PA] != null) {
  62284. const memberEntries = se_policyDescriptorListType(input[_PA], context);
  62285. if (((_a2 = input[_PA]) == null ? void 0 : _a2.length) === 0) {
  62286. entries.PolicyArns = [];
  62287. }
  62288. Object.entries(memberEntries).forEach(([key, value]) => {
  62289. const loc = `PolicyArns.${key}`;
  62290. entries[loc] = value;
  62291. });
  62292. }
  62293. if (input[_P] != null) {
  62294. entries[_P] = input[_P];
  62295. }
  62296. if (input[_DS] != null) {
  62297. entries[_DS] = input[_DS];
  62298. }
  62299. return entries;
  62300. };
  62301. se_policyDescriptorListType = (input, context) => {
  62302. const entries = {};
  62303. let counter = 1;
  62304. for (const entry of input) {
  62305. if (entry === null) {
  62306. continue;
  62307. }
  62308. const memberEntries = se_PolicyDescriptorType(entry, context);
  62309. Object.entries(memberEntries).forEach(([key, value]) => {
  62310. entries[`member.${counter}.${key}`] = value;
  62311. });
  62312. counter++;
  62313. }
  62314. return entries;
  62315. };
  62316. se_PolicyDescriptorType = (input, context) => {
  62317. const entries = {};
  62318. if (input[_a] != null) {
  62319. entries[_a] = input[_a];
  62320. }
  62321. return entries;
  62322. };
  62323. se_ProvidedContext = (input, context) => {
  62324. const entries = {};
  62325. if (input[_PAr] != null) {
  62326. entries[_PAr] = input[_PAr];
  62327. }
  62328. if (input[_CA] != null) {
  62329. entries[_CA] = input[_CA];
  62330. }
  62331. return entries;
  62332. };
  62333. se_ProvidedContextsListType = (input, context) => {
  62334. const entries = {};
  62335. let counter = 1;
  62336. for (const entry of input) {
  62337. if (entry === null) {
  62338. continue;
  62339. }
  62340. const memberEntries = se_ProvidedContext(entry, context);
  62341. Object.entries(memberEntries).forEach(([key, value]) => {
  62342. entries[`member.${counter}.${key}`] = value;
  62343. });
  62344. counter++;
  62345. }
  62346. return entries;
  62347. };
  62348. se_Tag = (input, context) => {
  62349. const entries = {};
  62350. if (input[_K] != null) {
  62351. entries[_K] = input[_K];
  62352. }
  62353. if (input[_Va] != null) {
  62354. entries[_Va] = input[_Va];
  62355. }
  62356. return entries;
  62357. };
  62358. se_tagKeyListType = (input, context) => {
  62359. const entries = {};
  62360. let counter = 1;
  62361. for (const entry of input) {
  62362. if (entry === null) {
  62363. continue;
  62364. }
  62365. entries[`member.${counter}`] = entry;
  62366. counter++;
  62367. }
  62368. return entries;
  62369. };
  62370. se_tagListType = (input, context) => {
  62371. const entries = {};
  62372. let counter = 1;
  62373. for (const entry of input) {
  62374. if (entry === null) {
  62375. continue;
  62376. }
  62377. const memberEntries = se_Tag(entry, context);
  62378. Object.entries(memberEntries).forEach(([key, value]) => {
  62379. entries[`member.${counter}.${key}`] = value;
  62380. });
  62381. counter++;
  62382. }
  62383. return entries;
  62384. };
  62385. de_AssumedRoleUser = (output, context) => {
  62386. const contents = {};
  62387. if (output[_ARI] != null) {
  62388. contents[_ARI] = (0, import_smithy_client21.expectString)(output[_ARI]);
  62389. }
  62390. if (output[_Ar] != null) {
  62391. contents[_Ar] = (0, import_smithy_client21.expectString)(output[_Ar]);
  62392. }
  62393. return contents;
  62394. };
  62395. de_AssumeRoleResponse = (output, context) => {
  62396. const contents = {};
  62397. if (output[_C] != null) {
  62398. contents[_C] = de_Credentials(output[_C], context);
  62399. }
  62400. if (output[_ARU] != null) {
  62401. contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
  62402. }
  62403. if (output[_PPS] != null) {
  62404. contents[_PPS] = (0, import_smithy_client21.strictParseInt32)(output[_PPS]);
  62405. }
  62406. if (output[_SI] != null) {
  62407. contents[_SI] = (0, import_smithy_client21.expectString)(output[_SI]);
  62408. }
  62409. return contents;
  62410. };
  62411. de_AssumeRoleWithWebIdentityResponse = (output, context) => {
  62412. const contents = {};
  62413. if (output[_C] != null) {
  62414. contents[_C] = de_Credentials(output[_C], context);
  62415. }
  62416. if (output[_SFWIT] != null) {
  62417. contents[_SFWIT] = (0, import_smithy_client21.expectString)(output[_SFWIT]);
  62418. }
  62419. if (output[_ARU] != null) {
  62420. contents[_ARU] = de_AssumedRoleUser(output[_ARU], context);
  62421. }
  62422. if (output[_PPS] != null) {
  62423. contents[_PPS] = (0, import_smithy_client21.strictParseInt32)(output[_PPS]);
  62424. }
  62425. if (output[_Pr] != null) {
  62426. contents[_Pr] = (0, import_smithy_client21.expectString)(output[_Pr]);
  62427. }
  62428. if (output[_Au] != null) {
  62429. contents[_Au] = (0, import_smithy_client21.expectString)(output[_Au]);
  62430. }
  62431. if (output[_SI] != null) {
  62432. contents[_SI] = (0, import_smithy_client21.expectString)(output[_SI]);
  62433. }
  62434. return contents;
  62435. };
  62436. de_Credentials = (output, context) => {
  62437. const contents = {};
  62438. if (output[_AKI] != null) {
  62439. contents[_AKI] = (0, import_smithy_client21.expectString)(output[_AKI]);
  62440. }
  62441. if (output[_SAK] != null) {
  62442. contents[_SAK] = (0, import_smithy_client21.expectString)(output[_SAK]);
  62443. }
  62444. if (output[_ST] != null) {
  62445. contents[_ST] = (0, import_smithy_client21.expectString)(output[_ST]);
  62446. }
  62447. if (output[_E] != null) {
  62448. contents[_E] = (0, import_smithy_client21.expectNonNull)((0, import_smithy_client21.parseRfc3339DateTimeWithOffset)(output[_E]));
  62449. }
  62450. return contents;
  62451. };
  62452. de_ExpiredTokenException = (output, context) => {
  62453. const contents = {};
  62454. if (output[_m] != null) {
  62455. contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
  62456. }
  62457. return contents;
  62458. };
  62459. de_IDPCommunicationErrorException = (output, context) => {
  62460. const contents = {};
  62461. if (output[_m] != null) {
  62462. contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
  62463. }
  62464. return contents;
  62465. };
  62466. de_IDPRejectedClaimException = (output, context) => {
  62467. const contents = {};
  62468. if (output[_m] != null) {
  62469. contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
  62470. }
  62471. return contents;
  62472. };
  62473. de_InvalidIdentityTokenException = (output, context) => {
  62474. const contents = {};
  62475. if (output[_m] != null) {
  62476. contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
  62477. }
  62478. return contents;
  62479. };
  62480. de_MalformedPolicyDocumentException = (output, context) => {
  62481. const contents = {};
  62482. if (output[_m] != null) {
  62483. contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
  62484. }
  62485. return contents;
  62486. };
  62487. de_PackedPolicyTooLargeException = (output, context) => {
  62488. const contents = {};
  62489. if (output[_m] != null) {
  62490. contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
  62491. }
  62492. return contents;
  62493. };
  62494. de_RegionDisabledException = (output, context) => {
  62495. const contents = {};
  62496. if (output[_m] != null) {
  62497. contents[_m] = (0, import_smithy_client21.expectString)(output[_m]);
  62498. }
  62499. return contents;
  62500. };
  62501. deserializeMetadata2 = (output) => ({
  62502. httpStatusCode: output.statusCode,
  62503. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  62504. extendedRequestId: output.headers["x-amz-id-2"],
  62505. cfId: output.headers["x-amz-cf-id"]
  62506. });
  62507. throwDefaultError2 = (0, import_smithy_client21.withBaseException)(STSServiceException);
  62508. buildHttpRpcRequest = async (context, headers, path4, resolvedHostname, body) => {
  62509. const { hostname, protocol = "https", port, path: basePath } = await context.endpoint();
  62510. const contents = {
  62511. protocol,
  62512. hostname,
  62513. port,
  62514. method: "POST",
  62515. path: basePath.endsWith("/") ? basePath.slice(0, -1) + path4 : basePath + path4,
  62516. headers
  62517. };
  62518. if (resolvedHostname !== void 0) {
  62519. contents.hostname = resolvedHostname;
  62520. }
  62521. if (body !== void 0) {
  62522. contents.body = body;
  62523. }
  62524. return new import_protocol_http14.HttpRequest(contents);
  62525. };
  62526. SHARED_HEADERS = {
  62527. "content-type": "application/x-www-form-urlencoded"
  62528. };
  62529. _2 = "2011-06-15";
  62530. _A = "Action";
  62531. _AKI = "AccessKeyId";
  62532. _AR = "AssumeRole";
  62533. _ARI = "AssumedRoleId";
  62534. _ARU = "AssumedRoleUser";
  62535. _ARWWI = "AssumeRoleWithWebIdentity";
  62536. _Ar = "Arn";
  62537. _Au = "Audience";
  62538. _C = "Credentials";
  62539. _CA = "ContextAssertion";
  62540. _DS = "DurationSeconds";
  62541. _E = "Expiration";
  62542. _EI = "ExternalId";
  62543. _K = "Key";
  62544. _P = "Policy";
  62545. _PA = "PolicyArns";
  62546. _PAr = "ProviderArn";
  62547. _PC = "ProvidedContexts";
  62548. _PI = "ProviderId";
  62549. _PPS = "PackedPolicySize";
  62550. _Pr = "Provider";
  62551. _RA = "RoleArn";
  62552. _RSN = "RoleSessionName";
  62553. _SAK = "SecretAccessKey";
  62554. _SFWIT = "SubjectFromWebIdentityToken";
  62555. _SI = "SourceIdentity";
  62556. _SN = "SerialNumber";
  62557. _ST = "SessionToken";
  62558. _T = "Tags";
  62559. _TC = "TokenCode";
  62560. _TTK = "TransitiveTagKeys";
  62561. _V = "Version";
  62562. _Va = "Value";
  62563. _WIT = "WebIdentityToken";
  62564. _a = "arn";
  62565. _m = "message";
  62566. buildFormUrlencodedString = (formEntries) => Object.entries(formEntries).map(([key, value]) => (0, import_smithy_client21.extendedEncodeURIComponent)(key) + "=" + (0, import_smithy_client21.extendedEncodeURIComponent)(value)).join("&");
  62567. loadQueryErrorCode = (output, data) => {
  62568. var _a2;
  62569. if (((_a2 = data.Error) == null ? void 0 : _a2.Code) !== void 0) {
  62570. return data.Error.Code;
  62571. }
  62572. if (output.statusCode == 404) {
  62573. return "NotFound";
  62574. }
  62575. };
  62576. }
  62577. });
  62578. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js
  62579. var import_middleware_endpoint4, import_middleware_serde3, import_smithy_client22, AssumeRoleCommand;
  62580. var init_AssumeRoleCommand = __esm({
  62581. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js"() {
  62582. import_middleware_endpoint4 = __toESM(require_dist_cjs32());
  62583. import_middleware_serde3 = __toESM(require_dist_cjs7());
  62584. import_smithy_client22 = __toESM(require_dist_cjs23());
  62585. init_EndpointParameters2();
  62586. init_models_02();
  62587. init_Aws_query();
  62588. AssumeRoleCommand = class extends import_smithy_client22.Command.classBuilder().ep(commonParams2).m(function(Command, cs, config, o3) {
  62589. return [
  62590. (0, import_middleware_serde3.getSerdePlugin)(config, this.serialize, this.deserialize),
  62591. (0, import_middleware_endpoint4.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  62592. ];
  62593. }).s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}).n("STSClient", "AssumeRoleCommand").f(void 0, AssumeRoleResponseFilterSensitiveLog).ser(se_AssumeRoleCommand).de(de_AssumeRoleCommand).build() {
  62594. };
  62595. }
  62596. });
  62597. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js
  62598. var import_middleware_endpoint5, import_middleware_serde4, import_smithy_client23, AssumeRoleWithWebIdentityCommand;
  62599. var init_AssumeRoleWithWebIdentityCommand = __esm({
  62600. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js"() {
  62601. import_middleware_endpoint5 = __toESM(require_dist_cjs32());
  62602. import_middleware_serde4 = __toESM(require_dist_cjs7());
  62603. import_smithy_client23 = __toESM(require_dist_cjs23());
  62604. init_EndpointParameters2();
  62605. init_models_02();
  62606. init_Aws_query();
  62607. AssumeRoleWithWebIdentityCommand = class extends import_smithy_client23.Command.classBuilder().ep(commonParams2).m(function(Command, cs, config, o3) {
  62608. return [
  62609. (0, import_middleware_serde4.getSerdePlugin)(config, this.serialize, this.deserialize),
  62610. (0, import_middleware_endpoint5.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  62611. ];
  62612. }).s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}).n("STSClient", "AssumeRoleWithWebIdentityCommand").f(AssumeRoleWithWebIdentityRequestFilterSensitiveLog, AssumeRoleWithWebIdentityResponseFilterSensitiveLog).ser(se_AssumeRoleWithWebIdentityCommand).de(de_AssumeRoleWithWebIdentityCommand).build() {
  62613. };
  62614. }
  62615. });
  62616. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js
  62617. var import_smithy_client24, commands2, STS;
  62618. var init_STS = __esm({
  62619. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js"() {
  62620. import_smithy_client24 = __toESM(require_dist_cjs23());
  62621. init_AssumeRoleCommand();
  62622. init_AssumeRoleWithWebIdentityCommand();
  62623. init_STSClient();
  62624. commands2 = {
  62625. AssumeRoleCommand,
  62626. AssumeRoleWithWebIdentityCommand
  62627. };
  62628. STS = class extends STSClient {
  62629. };
  62630. (0, import_smithy_client24.createAggregatedClient)(commands2, STS);
  62631. }
  62632. });
  62633. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js
  62634. var init_commands2 = __esm({
  62635. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js"() {
  62636. init_AssumeRoleCommand();
  62637. init_AssumeRoleWithWebIdentityCommand();
  62638. }
  62639. });
  62640. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/index.js
  62641. var init_models2 = __esm({
  62642. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/index.js"() {
  62643. init_models_02();
  62644. }
  62645. });
  62646. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js
  62647. var ASSUME_ROLE_DEFAULT_REGION, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2;
  62648. var init_defaultStsRoleAssumers = __esm({
  62649. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js"() {
  62650. init_client();
  62651. init_AssumeRoleCommand();
  62652. init_AssumeRoleWithWebIdentityCommand();
  62653. ASSUME_ROLE_DEFAULT_REGION = "us-east-1";
  62654. getAccountIdFromAssumedRoleUser = (assumedRoleUser) => {
  62655. if (typeof (assumedRoleUser == null ? void 0 : assumedRoleUser.Arn) === "string") {
  62656. const arnComponents = assumedRoleUser.Arn.split(":");
  62657. if (arnComponents.length > 4 && arnComponents[4] !== "") {
  62658. return arnComponents[4];
  62659. }
  62660. }
  62661. return void 0;
  62662. };
  62663. resolveRegion = async (_region, _parentRegion, credentialProviderLogger) => {
  62664. var _a2;
  62665. const region = typeof _region === "function" ? await _region() : _region;
  62666. const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
  62667. (_a2 = credentialProviderLogger == null ? void 0 : credentialProviderLogger.debug) == null ? void 0 : _a2.call(credentialProviderLogger, "@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (provider)`, `${parentRegion} (parent client)`, `${ASSUME_ROLE_DEFAULT_REGION} (STS default)`);
  62668. return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION;
  62669. };
  62670. getDefaultRoleAssumer = (stsOptions, STSClient2) => {
  62671. let stsClient;
  62672. let closureSourceCreds;
  62673. return async (sourceCreds, params) => {
  62674. var _a2, _b, _c, _d;
  62675. closureSourceCreds = sourceCreds;
  62676. if (!stsClient) {
  62677. const { logger: logger3 = (_a2 = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _a2.logger, region, requestHandler = (_b = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _b.requestHandler, credentialProviderLogger } = stsOptions;
  62678. const resolvedRegion = await resolveRegion(region, (_c = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _c.region, credentialProviderLogger);
  62679. const isCompatibleRequestHandler = !isH2(requestHandler);
  62680. stsClient = new STSClient2({
  62681. profile: (_d = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _d.profile,
  62682. credentialDefaultProvider: () => async () => closureSourceCreds,
  62683. region: resolvedRegion,
  62684. requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
  62685. logger: logger3
  62686. });
  62687. }
  62688. const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params));
  62689. if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
  62690. throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`);
  62691. }
  62692. const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
  62693. const credentials2 = {
  62694. accessKeyId: Credentials.AccessKeyId,
  62695. secretAccessKey: Credentials.SecretAccessKey,
  62696. sessionToken: Credentials.SessionToken,
  62697. expiration: Credentials.Expiration,
  62698. ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
  62699. ...accountId && { accountId }
  62700. };
  62701. setCredentialFeature(credentials2, "CREDENTIALS_STS_ASSUME_ROLE", "i");
  62702. return credentials2;
  62703. };
  62704. };
  62705. getDefaultRoleAssumerWithWebIdentity = (stsOptions, STSClient2) => {
  62706. let stsClient;
  62707. return async (params) => {
  62708. var _a2, _b, _c, _d;
  62709. if (!stsClient) {
  62710. const { logger: logger3 = (_a2 = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _a2.logger, region, requestHandler = (_b = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _b.requestHandler, credentialProviderLogger } = stsOptions;
  62711. const resolvedRegion = await resolveRegion(region, (_c = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _c.region, credentialProviderLogger);
  62712. const isCompatibleRequestHandler = !isH2(requestHandler);
  62713. stsClient = new STSClient2({
  62714. profile: (_d = stsOptions == null ? void 0 : stsOptions.parentClientConfig) == null ? void 0 : _d.profile,
  62715. region: resolvedRegion,
  62716. requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
  62717. logger: logger3
  62718. });
  62719. }
  62720. const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params));
  62721. if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) {
  62722. throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`);
  62723. }
  62724. const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser);
  62725. const credentials2 = {
  62726. accessKeyId: Credentials.AccessKeyId,
  62727. secretAccessKey: Credentials.SecretAccessKey,
  62728. sessionToken: Credentials.SessionToken,
  62729. expiration: Credentials.Expiration,
  62730. ...Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope },
  62731. ...accountId && { accountId }
  62732. };
  62733. if (accountId) {
  62734. setCredentialFeature(credentials2, "RESOLVED_ACCOUNT_ID", "T");
  62735. }
  62736. setCredentialFeature(credentials2, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k");
  62737. return credentials2;
  62738. };
  62739. };
  62740. isH2 = (requestHandler) => {
  62741. var _a2;
  62742. return ((_a2 = requestHandler == null ? void 0 : requestHandler.metadata) == null ? void 0 : _a2.handlerProtocol) === "h2";
  62743. };
  62744. }
  62745. });
  62746. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js
  62747. var getCustomizableStsClientCtor, getDefaultRoleAssumer2, getDefaultRoleAssumerWithWebIdentity2, decorateDefaultCredentialProvider;
  62748. var init_defaultRoleAssumers = __esm({
  62749. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js"() {
  62750. init_defaultStsRoleAssumers();
  62751. init_STSClient();
  62752. getCustomizableStsClientCtor = (baseCtor, customizations) => {
  62753. if (!customizations)
  62754. return baseCtor;
  62755. else
  62756. return class CustomizableSTSClient extends baseCtor {
  62757. constructor(config) {
  62758. super(config);
  62759. for (const customization of customizations) {
  62760. this.middlewareStack.use(customization);
  62761. }
  62762. }
  62763. };
  62764. };
  62765. getDefaultRoleAssumer2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));
  62766. getDefaultRoleAssumerWithWebIdentity2 = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity(stsOptions, getCustomizableStsClientCtor(STSClient, stsPlugins));
  62767. decorateDefaultCredentialProvider = (provider) => (input) => provider({
  62768. roleAssumer: getDefaultRoleAssumer2(input),
  62769. roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity2(input),
  62770. ...input
  62771. });
  62772. }
  62773. });
  62774. // ../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js
  62775. var sts_exports = {};
  62776. __export(sts_exports, {
  62777. AssumeRoleCommand: () => AssumeRoleCommand,
  62778. AssumeRoleResponseFilterSensitiveLog: () => AssumeRoleResponseFilterSensitiveLog,
  62779. AssumeRoleWithWebIdentityCommand: () => AssumeRoleWithWebIdentityCommand,
  62780. AssumeRoleWithWebIdentityRequestFilterSensitiveLog: () => AssumeRoleWithWebIdentityRequestFilterSensitiveLog,
  62781. AssumeRoleWithWebIdentityResponseFilterSensitiveLog: () => AssumeRoleWithWebIdentityResponseFilterSensitiveLog,
  62782. CredentialsFilterSensitiveLog: () => CredentialsFilterSensitiveLog,
  62783. ExpiredTokenException: () => ExpiredTokenException2,
  62784. IDPCommunicationErrorException: () => IDPCommunicationErrorException,
  62785. IDPRejectedClaimException: () => IDPRejectedClaimException,
  62786. InvalidIdentityTokenException: () => InvalidIdentityTokenException,
  62787. MalformedPolicyDocumentException: () => MalformedPolicyDocumentException,
  62788. PackedPolicyTooLargeException: () => PackedPolicyTooLargeException,
  62789. RegionDisabledException: () => RegionDisabledException,
  62790. STS: () => STS,
  62791. STSClient: () => STSClient,
  62792. STSServiceException: () => STSServiceException,
  62793. __Client: () => import_smithy_client18.Client,
  62794. decorateDefaultCredentialProvider: () => decorateDefaultCredentialProvider,
  62795. getDefaultRoleAssumer: () => getDefaultRoleAssumer2,
  62796. getDefaultRoleAssumerWithWebIdentity: () => getDefaultRoleAssumerWithWebIdentity2
  62797. });
  62798. var init_sts = __esm({
  62799. "../node_modules/.pnpm/@aws-sdk+nested-clients@3.817.0/node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js"() {
  62800. init_STSClient();
  62801. init_STS();
  62802. init_commands2();
  62803. init_models2();
  62804. init_defaultRoleAssumers();
  62805. init_STSServiceException();
  62806. }
  62807. });
  62808. // ../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js
  62809. var require_dist_cjs47 = __commonJS({
  62810. "../node_modules/.pnpm/@aws-sdk+credential-provider-process@3.816.0/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js"(exports2, module2) {
  62811. "use strict";
  62812. var __defProp3 = Object.defineProperty;
  62813. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  62814. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  62815. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  62816. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  62817. var __export2 = (target, all) => {
  62818. for (var name in all)
  62819. __defProp3(target, name, { get: all[name], enumerable: true });
  62820. };
  62821. var __copyProps3 = (to, from, except, desc) => {
  62822. if (from && typeof from === "object" || typeof from === "function") {
  62823. for (let key of __getOwnPropNames3(from))
  62824. if (!__hasOwnProp3.call(to, key) && key !== except)
  62825. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  62826. }
  62827. return to;
  62828. };
  62829. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  62830. var index_exports = {};
  62831. __export2(index_exports, {
  62832. fromProcess: () => fromProcess
  62833. });
  62834. module2.exports = __toCommonJS2(index_exports);
  62835. var import_shared_ini_file_loader = require_dist_cjs28();
  62836. var import_property_provider2 = require_dist_cjs20();
  62837. var import_child_process = require("child_process");
  62838. var import_util4 = require("util");
  62839. var import_client3 = (init_client(), __toCommonJS(client_exports));
  62840. var getValidatedProcessCredentials = /* @__PURE__ */ __name((profileName, data, profiles) => {
  62841. var _a2;
  62842. if (data.Version !== 1) {
  62843. throw Error(`Profile ${profileName} credential_process did not return Version 1.`);
  62844. }
  62845. if (data.AccessKeyId === void 0 || data.SecretAccessKey === void 0) {
  62846. throw Error(`Profile ${profileName} credential_process returned invalid credentials.`);
  62847. }
  62848. if (data.Expiration) {
  62849. const currentTime = /* @__PURE__ */ new Date();
  62850. const expireTime = new Date(data.Expiration);
  62851. if (expireTime < currentTime) {
  62852. throw Error(`Profile ${profileName} credential_process returned expired credentials.`);
  62853. }
  62854. }
  62855. let accountId = data.AccountId;
  62856. if (!accountId && ((_a2 = profiles == null ? void 0 : profiles[profileName]) == null ? void 0 : _a2.aws_account_id)) {
  62857. accountId = profiles[profileName].aws_account_id;
  62858. }
  62859. const credentials2 = {
  62860. accessKeyId: data.AccessKeyId,
  62861. secretAccessKey: data.SecretAccessKey,
  62862. ...data.SessionToken && { sessionToken: data.SessionToken },
  62863. ...data.Expiration && { expiration: new Date(data.Expiration) },
  62864. ...data.CredentialScope && { credentialScope: data.CredentialScope },
  62865. ...accountId && { accountId }
  62866. };
  62867. (0, import_client3.setCredentialFeature)(credentials2, "CREDENTIALS_PROCESS", "w");
  62868. return credentials2;
  62869. }, "getValidatedProcessCredentials");
  62870. var resolveProcessCredentials = /* @__PURE__ */ __name(async (profileName, profiles, logger3) => {
  62871. const profile = profiles[profileName];
  62872. if (profiles[profileName]) {
  62873. const credentialProcess = profile["credential_process"];
  62874. if (credentialProcess !== void 0) {
  62875. const execPromise = (0, import_util4.promisify)(import_child_process.exec);
  62876. try {
  62877. const { stdout } = await execPromise(credentialProcess);
  62878. let data;
  62879. try {
  62880. data = JSON.parse(stdout.trim());
  62881. } catch {
  62882. throw Error(`Profile ${profileName} credential_process returned invalid JSON.`);
  62883. }
  62884. return getValidatedProcessCredentials(profileName, data, profiles);
  62885. } catch (error2) {
  62886. throw new import_property_provider2.CredentialsProviderError(error2.message, { logger: logger3 });
  62887. }
  62888. } else {
  62889. throw new import_property_provider2.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger: logger3 });
  62890. }
  62891. } else {
  62892. throw new import_property_provider2.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, {
  62893. logger: logger3
  62894. });
  62895. }
  62896. }, "resolveProcessCredentials");
  62897. var fromProcess = /* @__PURE__ */ __name((init2 = {}) => async ({ callerClientConfig } = {}) => {
  62898. var _a2;
  62899. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-process - fromProcess");
  62900. const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
  62901. return resolveProcessCredentials(
  62902. (0, import_shared_ini_file_loader.getProfileName)({
  62903. profile: init2.profile ?? (callerClientConfig == null ? void 0 : callerClientConfig.profile)
  62904. }),
  62905. profiles,
  62906. init2.logger
  62907. );
  62908. }, "fromProcess");
  62909. }
  62910. });
  62911. // ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js
  62912. var require_fromWebToken = __commonJS({
  62913. "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js"(exports2) {
  62914. "use strict";
  62915. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  62916. if (k22 === void 0) k22 = k3;
  62917. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  62918. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  62919. desc = { enumerable: true, get: function() {
  62920. return m4[k3];
  62921. } };
  62922. }
  62923. Object.defineProperty(o3, k22, desc);
  62924. } : function(o3, m4, k3, k22) {
  62925. if (k22 === void 0) k22 = k3;
  62926. o3[k22] = m4[k3];
  62927. });
  62928. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  62929. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  62930. } : function(o3, v6) {
  62931. o3["default"] = v6;
  62932. });
  62933. var __importStar2 = exports2 && exports2.__importStar || /* @__PURE__ */ function() {
  62934. var ownKeys2 = function(o3) {
  62935. ownKeys2 = Object.getOwnPropertyNames || function(o4) {
  62936. var ar = [];
  62937. for (var k3 in o4) if (Object.prototype.hasOwnProperty.call(o4, k3)) ar[ar.length] = k3;
  62938. return ar;
  62939. };
  62940. return ownKeys2(o3);
  62941. };
  62942. return function(mod) {
  62943. if (mod && mod.__esModule) return mod;
  62944. var result = {};
  62945. if (mod != null) {
  62946. for (var k3 = ownKeys2(mod), i4 = 0; i4 < k3.length; i4++) if (k3[i4] !== "default") __createBinding2(result, mod, k3[i4]);
  62947. }
  62948. __setModuleDefault2(result, mod);
  62949. return result;
  62950. };
  62951. }();
  62952. Object.defineProperty(exports2, "__esModule", { value: true });
  62953. exports2.fromWebToken = void 0;
  62954. var fromWebToken2 = (init2) => async (awsIdentityProperties) => {
  62955. var _a2;
  62956. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");
  62957. const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy: policy5, durationSeconds } = init2;
  62958. let { roleAssumerWithWebIdentity } = init2;
  62959. if (!roleAssumerWithWebIdentity) {
  62960. const { getDefaultRoleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity3 } = await Promise.resolve().then(() => __importStar2((init_sts(), __toCommonJS(sts_exports))));
  62961. roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity3({
  62962. ...init2.clientConfig,
  62963. credentialProviderLogger: init2.logger,
  62964. parentClientConfig: {
  62965. ...awsIdentityProperties == null ? void 0 : awsIdentityProperties.callerClientConfig,
  62966. ...init2.parentClientConfig
  62967. }
  62968. }, init2.clientPlugins);
  62969. }
  62970. return roleAssumerWithWebIdentity({
  62971. RoleArn: roleArn,
  62972. RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`,
  62973. WebIdentityToken: webIdentityToken,
  62974. ProviderId: providerId,
  62975. PolicyArns: policyArns,
  62976. Policy: policy5,
  62977. DurationSeconds: durationSeconds
  62978. });
  62979. };
  62980. exports2.fromWebToken = fromWebToken2;
  62981. }
  62982. });
  62983. // ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js
  62984. var require_fromTokenFile = __commonJS({
  62985. "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js"(exports2) {
  62986. "use strict";
  62987. Object.defineProperty(exports2, "__esModule", { value: true });
  62988. exports2.fromTokenFile = void 0;
  62989. var client_1 = (init_client(), __toCommonJS(client_exports));
  62990. var property_provider_1 = require_dist_cjs20();
  62991. var fs_1 = require("fs");
  62992. var fromWebToken_1 = require_fromWebToken();
  62993. var ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE";
  62994. var ENV_ROLE_ARN = "AWS_ROLE_ARN";
  62995. var ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME";
  62996. var fromTokenFile2 = (init2 = {}) => async () => {
  62997. var _a2;
  62998. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");
  62999. const webIdentityTokenFile = (init2 == null ? void 0 : init2.webIdentityTokenFile) ?? process.env[ENV_TOKEN_FILE];
  63000. const roleArn = (init2 == null ? void 0 : init2.roleArn) ?? process.env[ENV_ROLE_ARN];
  63001. const roleSessionName = (init2 == null ? void 0 : init2.roleSessionName) ?? process.env[ENV_ROLE_SESSION_NAME];
  63002. if (!webIdentityTokenFile || !roleArn) {
  63003. throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", {
  63004. logger: init2.logger
  63005. });
  63006. }
  63007. const credentials2 = await (0, fromWebToken_1.fromWebToken)({
  63008. ...init2,
  63009. webIdentityToken: (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }),
  63010. roleArn,
  63011. roleSessionName
  63012. })();
  63013. if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {
  63014. (0, client_1.setCredentialFeature)(credentials2, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h");
  63015. }
  63016. return credentials2;
  63017. };
  63018. exports2.fromTokenFile = fromTokenFile2;
  63019. }
  63020. });
  63021. // ../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js
  63022. var require_dist_cjs48 = __commonJS({
  63023. "../node_modules/.pnpm/@aws-sdk+credential-provider-web-identity@3.817.0/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js"(exports2, module2) {
  63024. "use strict";
  63025. var __defProp3 = Object.defineProperty;
  63026. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  63027. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  63028. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  63029. var __copyProps3 = (to, from, except, desc) => {
  63030. if (from && typeof from === "object" || typeof from === "function") {
  63031. for (let key of __getOwnPropNames3(from))
  63032. if (!__hasOwnProp3.call(to, key) && key !== except)
  63033. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  63034. }
  63035. return to;
  63036. };
  63037. var __reExport = (target, mod, secondTarget) => (__copyProps3(target, mod, "default"), secondTarget && __copyProps3(secondTarget, mod, "default"));
  63038. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  63039. var index_exports = {};
  63040. module2.exports = __toCommonJS2(index_exports);
  63041. __reExport(index_exports, require_fromTokenFile(), module2.exports);
  63042. __reExport(index_exports, require_fromWebToken(), module2.exports);
  63043. }
  63044. });
  63045. // ../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js
  63046. var require_dist_cjs49 = __commonJS({
  63047. "../node_modules/.pnpm/@aws-sdk+credential-provider-ini@3.817.0/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js"(exports2, module2) {
  63048. "use strict";
  63049. var __create3 = Object.create;
  63050. var __defProp3 = Object.defineProperty;
  63051. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  63052. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  63053. var __getProtoOf3 = Object.getPrototypeOf;
  63054. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  63055. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  63056. var __export2 = (target, all) => {
  63057. for (var name in all)
  63058. __defProp3(target, name, { get: all[name], enumerable: true });
  63059. };
  63060. var __copyProps3 = (to, from, except, desc) => {
  63061. if (from && typeof from === "object" || typeof from === "function") {
  63062. for (let key of __getOwnPropNames3(from))
  63063. if (!__hasOwnProp3.call(to, key) && key !== except)
  63064. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  63065. }
  63066. return to;
  63067. };
  63068. var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
  63069. // If the importer is in node compatibility mode or this is not an ESM
  63070. // file that has been converted to a CommonJS file using a Babel-
  63071. // compatible transform (i.e. "__esModule" has not been set), then set
  63072. // "default" to the CommonJS "module.exports" for node compatibility.
  63073. isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
  63074. mod
  63075. ));
  63076. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  63077. var index_exports = {};
  63078. __export2(index_exports, {
  63079. fromIni: () => fromIni
  63080. });
  63081. module2.exports = __toCommonJS2(index_exports);
  63082. var import_shared_ini_file_loader = require_dist_cjs28();
  63083. var import_client3 = (init_client(), __toCommonJS(client_exports));
  63084. var import_property_provider2 = require_dist_cjs20();
  63085. var resolveCredentialSource = /* @__PURE__ */ __name((credentialSource, profileName, logger3) => {
  63086. const sourceProvidersMap = {
  63087. EcsContainer: /* @__PURE__ */ __name(async (options) => {
  63088. const { fromHttp } = await Promise.resolve().then(() => __toESM3(require_dist_cjs38()));
  63089. const { fromContainerMetadata } = await Promise.resolve().then(() => __toESM3(require_dist_cjs37()));
  63090. logger3 == null ? void 0 : logger3.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer");
  63091. return async () => (0, import_property_provider2.chain)(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider);
  63092. }, "EcsContainer"),
  63093. Ec2InstanceMetadata: /* @__PURE__ */ __name(async (options) => {
  63094. logger3 == null ? void 0 : logger3.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");
  63095. const { fromInstanceMetadata } = await Promise.resolve().then(() => __toESM3(require_dist_cjs37()));
  63096. return async () => fromInstanceMetadata(options)().then(setNamedProvider);
  63097. }, "Ec2InstanceMetadata"),
  63098. Environment: /* @__PURE__ */ __name(async (options) => {
  63099. logger3 == null ? void 0 : logger3.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");
  63100. const { fromEnv } = await Promise.resolve().then(() => __toESM3(require_dist_cjs36()));
  63101. return async () => fromEnv(options)().then(setNamedProvider);
  63102. }, "Environment")
  63103. };
  63104. if (credentialSource in sourceProvidersMap) {
  63105. return sourceProvidersMap[credentialSource];
  63106. } else {
  63107. throw new import_property_provider2.CredentialsProviderError(
  63108. `Unsupported credential source in profile ${profileName}. Got ${credentialSource}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,
  63109. { logger: logger3 }
  63110. );
  63111. }
  63112. }, "resolveCredentialSource");
  63113. var setNamedProvider = /* @__PURE__ */ __name((creds) => (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"), "setNamedProvider");
  63114. var isAssumeRoleProfile = /* @__PURE__ */ __name((arg, { profile = "default", logger: logger3 } = {}) => {
  63115. return Boolean(arg) && typeof arg === "object" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && (isAssumeRoleWithSourceProfile(arg, { profile, logger: logger3 }) || isCredentialSourceProfile(arg, { profile, logger: logger3 }));
  63116. }, "isAssumeRoleProfile");
  63117. var isAssumeRoleWithSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger: logger3 }) => {
  63118. var _a2;
  63119. const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined";
  63120. if (withSourceProfile) {
  63121. (_a2 = logger3 == null ? void 0 : logger3.debug) == null ? void 0 : _a2.call(logger3, ` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`);
  63122. }
  63123. return withSourceProfile;
  63124. }, "isAssumeRoleWithSourceProfile");
  63125. var isCredentialSourceProfile = /* @__PURE__ */ __name((arg, { profile, logger: logger3 }) => {
  63126. var _a2;
  63127. const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined";
  63128. if (withProviderProfile) {
  63129. (_a2 = logger3 == null ? void 0 : logger3.debug) == null ? void 0 : _a2.call(logger3, ` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`);
  63130. }
  63131. return withProviderProfile;
  63132. }, "isCredentialSourceProfile");
  63133. var resolveAssumeRoleCredentials = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}) => {
  63134. var _a2, _b, _c;
  63135. (_a2 = options.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");
  63136. const profileData = profiles[profileName];
  63137. const { source_profile, region } = profileData;
  63138. if (!options.roleAssumer) {
  63139. const { getDefaultRoleAssumer: getDefaultRoleAssumer3 } = await Promise.resolve().then(() => __toESM3((init_sts(), __toCommonJS(sts_exports))));
  63140. options.roleAssumer = getDefaultRoleAssumer3(
  63141. {
  63142. ...options.clientConfig,
  63143. credentialProviderLogger: options.logger,
  63144. parentClientConfig: {
  63145. ...options == null ? void 0 : options.parentClientConfig,
  63146. region: region ?? ((_b = options == null ? void 0 : options.parentClientConfig) == null ? void 0 : _b.region)
  63147. }
  63148. },
  63149. options.clientPlugins
  63150. );
  63151. }
  63152. if (source_profile && source_profile in visitedProfiles) {
  63153. throw new import_property_provider2.CredentialsProviderError(
  63154. `Detected a cycle attempting to resolve credentials for profile ${(0, import_shared_ini_file_loader.getProfileName)(options)}. Profiles visited: ` + Object.keys(visitedProfiles).join(", "),
  63155. { logger: options.logger }
  63156. );
  63157. }
  63158. (_c = options.logger) == null ? void 0 : _c.debug(
  63159. `@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`
  63160. );
  63161. const sourceCredsProvider = source_profile ? resolveProfileData(
  63162. source_profile,
  63163. profiles,
  63164. options,
  63165. {
  63166. ...visitedProfiles,
  63167. [source_profile]: true
  63168. },
  63169. isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})
  63170. ) : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))();
  63171. if (isCredentialSourceWithoutRoleArn(profileData)) {
  63172. return sourceCredsProvider.then((creds) => (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o"));
  63173. } else {
  63174. const params = {
  63175. RoleArn: profileData.role_arn,
  63176. RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`,
  63177. ExternalId: profileData.external_id,
  63178. DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10)
  63179. };
  63180. const { mfa_serial } = profileData;
  63181. if (mfa_serial) {
  63182. if (!options.mfaCodeProvider) {
  63183. throw new import_property_provider2.CredentialsProviderError(
  63184. `Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`,
  63185. { logger: options.logger, tryNextLink: false }
  63186. );
  63187. }
  63188. params.SerialNumber = mfa_serial;
  63189. params.TokenCode = await options.mfaCodeProvider(mfa_serial);
  63190. }
  63191. const sourceCreds = await sourceCredsProvider;
  63192. return options.roleAssumer(sourceCreds, params).then(
  63193. (creds) => (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")
  63194. );
  63195. }
  63196. }, "resolveAssumeRoleCredentials");
  63197. var isCredentialSourceWithoutRoleArn = /* @__PURE__ */ __name((section) => {
  63198. return !section.role_arn && !!section.credential_source;
  63199. }, "isCredentialSourceWithoutRoleArn");
  63200. var isProcessProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string", "isProcessProfile");
  63201. var resolveProcessCredentials = /* @__PURE__ */ __name(async (options, profile) => Promise.resolve().then(() => __toESM3(require_dist_cjs47())).then(
  63202. ({ fromProcess }) => fromProcess({
  63203. ...options,
  63204. profile
  63205. })().then((creds) => (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_PROCESS", "v"))
  63206. ), "resolveProcessCredentials");
  63207. var resolveSsoCredentials = /* @__PURE__ */ __name(async (profile, profileData, options = {}) => {
  63208. const { fromSSO } = await Promise.resolve().then(() => __toESM3(require_dist_cjs46()));
  63209. return fromSSO({
  63210. profile,
  63211. logger: options.logger,
  63212. parentClientConfig: options.parentClientConfig,
  63213. clientConfig: options.clientConfig
  63214. })().then((creds) => {
  63215. if (profileData.sso_session) {
  63216. return (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO", "r");
  63217. } else {
  63218. return (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t");
  63219. }
  63220. });
  63221. }, "resolveSsoCredentials");
  63222. var isSsoProfile = /* @__PURE__ */ __name((arg) => arg && (typeof arg.sso_start_url === "string" || typeof arg.sso_account_id === "string" || typeof arg.sso_session === "string" || typeof arg.sso_region === "string" || typeof arg.sso_role_name === "string"), "isSsoProfile");
  63223. var isStaticCredsProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.aws_access_key_id === "string" && typeof arg.aws_secret_access_key === "string" && ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1, "isStaticCredsProfile");
  63224. var resolveStaticCredentials = /* @__PURE__ */ __name(async (profile, options) => {
  63225. var _a2;
  63226. (_a2 = options == null ? void 0 : options.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");
  63227. const credentials2 = {
  63228. accessKeyId: profile.aws_access_key_id,
  63229. secretAccessKey: profile.aws_secret_access_key,
  63230. sessionToken: profile.aws_session_token,
  63231. ...profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope },
  63232. ...profile.aws_account_id && { accountId: profile.aws_account_id }
  63233. };
  63234. return (0, import_client3.setCredentialFeature)(credentials2, "CREDENTIALS_PROFILE", "n");
  63235. }, "resolveStaticCredentials");
  63236. var isWebIdentityProfile = /* @__PURE__ */ __name((arg) => Boolean(arg) && typeof arg === "object" && typeof arg.web_identity_token_file === "string" && typeof arg.role_arn === "string" && ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1, "isWebIdentityProfile");
  63237. var resolveWebIdentityCredentials = /* @__PURE__ */ __name(async (profile, options) => Promise.resolve().then(() => __toESM3(require_dist_cjs48())).then(
  63238. ({ fromTokenFile: fromTokenFile2 }) => fromTokenFile2({
  63239. webIdentityTokenFile: profile.web_identity_token_file,
  63240. roleArn: profile.role_arn,
  63241. roleSessionName: profile.role_session_name,
  63242. roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity,
  63243. logger: options.logger,
  63244. parentClientConfig: options.parentClientConfig
  63245. })().then((creds) => (0, import_client3.setCredentialFeature)(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q"))
  63246. ), "resolveWebIdentityCredentials");
  63247. var resolveProfileData = /* @__PURE__ */ __name(async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => {
  63248. const data = profiles[profileName];
  63249. if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) {
  63250. return resolveStaticCredentials(data, options);
  63251. }
  63252. if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) {
  63253. return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles);
  63254. }
  63255. if (isStaticCredsProfile(data)) {
  63256. return resolveStaticCredentials(data, options);
  63257. }
  63258. if (isWebIdentityProfile(data)) {
  63259. return resolveWebIdentityCredentials(data, options);
  63260. }
  63261. if (isProcessProfile(data)) {
  63262. return resolveProcessCredentials(options, profileName);
  63263. }
  63264. if (isSsoProfile(data)) {
  63265. return await resolveSsoCredentials(profileName, data, options);
  63266. }
  63267. throw new import_property_provider2.CredentialsProviderError(
  63268. `Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`,
  63269. { logger: options.logger }
  63270. );
  63271. }, "resolveProfileData");
  63272. var fromIni = /* @__PURE__ */ __name((_init = {}) => async ({ callerClientConfig } = {}) => {
  63273. var _a2;
  63274. const init2 = {
  63275. ..._init,
  63276. parentClientConfig: {
  63277. ...callerClientConfig,
  63278. ..._init.parentClientConfig
  63279. }
  63280. };
  63281. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-ini - fromIni");
  63282. const profiles = await (0, import_shared_ini_file_loader.parseKnownFiles)(init2);
  63283. return resolveProfileData(
  63284. (0, import_shared_ini_file_loader.getProfileName)({
  63285. profile: _init.profile ?? (callerClientConfig == null ? void 0 : callerClientConfig.profile)
  63286. }),
  63287. profiles,
  63288. init2
  63289. );
  63290. }, "fromIni");
  63291. }
  63292. });
  63293. // ../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js
  63294. var require_dist_cjs50 = __commonJS({
  63295. "../node_modules/.pnpm/@aws-sdk+credential-provider-node@3.817.0/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js"(exports2, module2) {
  63296. "use strict";
  63297. var __create3 = Object.create;
  63298. var __defProp3 = Object.defineProperty;
  63299. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  63300. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  63301. var __getProtoOf3 = Object.getPrototypeOf;
  63302. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  63303. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  63304. var __export2 = (target, all) => {
  63305. for (var name in all)
  63306. __defProp3(target, name, { get: all[name], enumerable: true });
  63307. };
  63308. var __copyProps3 = (to, from, except, desc) => {
  63309. if (from && typeof from === "object" || typeof from === "function") {
  63310. for (let key of __getOwnPropNames3(from))
  63311. if (!__hasOwnProp3.call(to, key) && key !== except)
  63312. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  63313. }
  63314. return to;
  63315. };
  63316. var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create3(__getProtoOf3(mod)) : {}, __copyProps3(
  63317. // If the importer is in node compatibility mode or this is not an ESM
  63318. // file that has been converted to a CommonJS file using a Babel-
  63319. // compatible transform (i.e. "__esModule" has not been set), then set
  63320. // "default" to the CommonJS "module.exports" for node compatibility.
  63321. isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
  63322. mod
  63323. ));
  63324. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  63325. var index_exports = {};
  63326. __export2(index_exports, {
  63327. credentialsTreatedAsExpired: () => credentialsTreatedAsExpired,
  63328. credentialsWillNeedRefresh: () => credentialsWillNeedRefresh,
  63329. defaultProvider: () => defaultProvider
  63330. });
  63331. module2.exports = __toCommonJS2(index_exports);
  63332. var import_credential_provider_env = require_dist_cjs36();
  63333. var import_shared_ini_file_loader = require_dist_cjs28();
  63334. var import_property_provider2 = require_dist_cjs20();
  63335. var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";
  63336. var remoteProvider = /* @__PURE__ */ __name(async (init2) => {
  63337. var _a2, _b;
  63338. const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await Promise.resolve().then(() => __toESM3(require_dist_cjs37()));
  63339. if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) {
  63340. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata");
  63341. const { fromHttp } = await Promise.resolve().then(() => __toESM3(require_dist_cjs38()));
  63342. return (0, import_property_provider2.chain)(fromHttp(init2), fromContainerMetadata(init2));
  63343. }
  63344. if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") {
  63345. return async () => {
  63346. throw new import_property_provider2.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init2.logger });
  63347. };
  63348. }
  63349. (_b = init2.logger) == null ? void 0 : _b.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata");
  63350. return fromInstanceMetadata(init2);
  63351. }, "remoteProvider");
  63352. var multipleCredentialSourceWarningEmitted = false;
  63353. var defaultProvider = /* @__PURE__ */ __name((init2 = {}) => (0, import_property_provider2.memoize)(
  63354. (0, import_property_provider2.chain)(
  63355. async () => {
  63356. var _a2, _b, _c, _d;
  63357. const profile = init2.profile ?? process.env[import_shared_ini_file_loader.ENV_PROFILE];
  63358. if (profile) {
  63359. const envStaticCredentialsAreSet = process.env[import_credential_provider_env.ENV_KEY] && process.env[import_credential_provider_env.ENV_SECRET];
  63360. if (envStaticCredentialsAreSet) {
  63361. if (!multipleCredentialSourceWarningEmitted) {
  63362. const warnFn = ((_a2 = init2.logger) == null ? void 0 : _a2.warn) && ((_c = (_b = init2.logger) == null ? void 0 : _b.constructor) == null ? void 0 : _c.name) !== "NoOpLogger" ? init2.logger.warn : console.warn;
  63363. warnFn(
  63364. `@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
  63365. Multiple credential sources detected:
  63366. Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
  63367. This SDK will proceed with the AWS_PROFILE value.
  63368. However, a future version may change this behavior to prefer the ENV static credentials.
  63369. Please ensure that your environment only sets either the AWS_PROFILE or the
  63370. AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
  63371. `
  63372. );
  63373. multipleCredentialSourceWarningEmitted = true;
  63374. }
  63375. }
  63376. throw new import_property_provider2.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", {
  63377. logger: init2.logger,
  63378. tryNextLink: true
  63379. });
  63380. }
  63381. (_d = init2.logger) == null ? void 0 : _d.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv");
  63382. return (0, import_credential_provider_env.fromEnv)(init2)();
  63383. },
  63384. async () => {
  63385. var _a2;
  63386. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");
  63387. const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init2;
  63388. if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
  63389. throw new import_property_provider2.CredentialsProviderError(
  63390. "Skipping SSO provider in default chain (inputs do not include SSO fields).",
  63391. { logger: init2.logger }
  63392. );
  63393. }
  63394. const { fromSSO } = await Promise.resolve().then(() => __toESM3(require_dist_cjs46()));
  63395. return fromSSO(init2)();
  63396. },
  63397. async () => {
  63398. var _a2;
  63399. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");
  63400. const { fromIni } = await Promise.resolve().then(() => __toESM3(require_dist_cjs49()));
  63401. return fromIni(init2)();
  63402. },
  63403. async () => {
  63404. var _a2;
  63405. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");
  63406. const { fromProcess } = await Promise.resolve().then(() => __toESM3(require_dist_cjs47()));
  63407. return fromProcess(init2)();
  63408. },
  63409. async () => {
  63410. var _a2;
  63411. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");
  63412. const { fromTokenFile: fromTokenFile2 } = await Promise.resolve().then(() => __toESM3(require_dist_cjs48()));
  63413. return fromTokenFile2(init2)();
  63414. },
  63415. async () => {
  63416. var _a2;
  63417. (_a2 = init2.logger) == null ? void 0 : _a2.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider");
  63418. return (await remoteProvider(init2))();
  63419. },
  63420. async () => {
  63421. throw new import_property_provider2.CredentialsProviderError("Could not load credentials from any providers", {
  63422. tryNextLink: false,
  63423. logger: init2.logger
  63424. });
  63425. }
  63426. ),
  63427. credentialsTreatedAsExpired,
  63428. credentialsWillNeedRefresh
  63429. ), "defaultProvider");
  63430. var credentialsWillNeedRefresh = /* @__PURE__ */ __name((credentials2) => (credentials2 == null ? void 0 : credentials2.expiration) !== void 0, "credentialsWillNeedRefresh");
  63431. var credentialsTreatedAsExpired = /* @__PURE__ */ __name((credentials2) => (credentials2 == null ? void 0 : credentials2.expiration) !== void 0 && credentials2.expiration.getTime() - Date.now() < 3e5, "credentialsTreatedAsExpired");
  63432. }
  63433. });
  63434. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/ruleset.js
  63435. var require_ruleset2 = __commonJS({
  63436. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/ruleset.js"(exports2) {
  63437. "use strict";
  63438. Object.defineProperty(exports2, "__esModule", { value: true });
  63439. exports2.ruleSet = void 0;
  63440. var s4 = "required";
  63441. var t4 = "fn";
  63442. var u3 = "argv";
  63443. var v6 = "ref";
  63444. var a3 = true;
  63445. var b3 = "isSet";
  63446. var c3 = "booleanEquals";
  63447. var d3 = "error";
  63448. var e4 = "endpoint";
  63449. var f5 = "tree";
  63450. var g3 = "PartitionResult";
  63451. var h4 = { [s4]: false, "type": "String" };
  63452. var i4 = { [s4]: true, "default": false, "type": "Boolean" };
  63453. var j3 = { [v6]: "Endpoint" };
  63454. var k3 = { [t4]: c3, [u3]: [{ [v6]: "UseFIPS" }, true] };
  63455. var l3 = { [t4]: c3, [u3]: [{ [v6]: "UseDualStack" }, true] };
  63456. var m4 = {};
  63457. var n3 = { [t4]: "getAttr", [u3]: [{ [v6]: g3 }, "supportsFIPS"] };
  63458. var o3 = { [t4]: c3, [u3]: [true, { [t4]: "getAttr", [u3]: [{ [v6]: g3 }, "supportsDualStack"] }] };
  63459. var p3 = [k3];
  63460. var q3 = [l3];
  63461. var r4 = [{ [v6]: "Region" }];
  63462. var _data3 = { version: "1.0", parameters: { Region: h4, UseDualStack: i4, UseFIPS: i4, Endpoint: h4 }, rules: [{ conditions: [{ [t4]: b3, [u3]: [j3] }], rules: [{ conditions: p3, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d3 }, { conditions: q3, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d3 }, { endpoint: { url: j3, properties: m4, headers: m4 }, type: e4 }], type: f5 }, { conditions: [{ [t4]: b3, [u3]: r4 }], rules: [{ conditions: [{ [t4]: "aws.partition", [u3]: r4, assign: g3 }], rules: [{ conditions: [k3, l3], rules: [{ conditions: [{ [t4]: c3, [u3]: [a3, n3] }, o3], rules: [{ endpoint: { url: "https://rds-data-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m4, headers: m4 }, type: e4 }], type: f5 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d3 }], type: f5 }, { conditions: p3, rules: [{ conditions: [{ [t4]: c3, [u3]: [n3, a3] }], rules: [{ endpoint: { url: "https://rds-data-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m4, headers: m4 }, type: e4 }], type: f5 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d3 }], type: f5 }, { conditions: q3, rules: [{ conditions: [o3], rules: [{ endpoint: { url: "https://rds-data.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m4, headers: m4 }, type: e4 }], type: f5 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d3 }], type: f5 }, { endpoint: { url: "https://rds-data.{Region}.{PartitionResult#dnsSuffix}", properties: m4, headers: m4 }, type: e4 }], type: f5 }], type: f5 }, { error: "Invalid Configuration: Missing Region", type: d3 }] };
  63463. exports2.ruleSet = _data3;
  63464. }
  63465. });
  63466. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/endpointResolver.js
  63467. var require_endpointResolver2 = __commonJS({
  63468. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/endpoint/endpointResolver.js"(exports2) {
  63469. "use strict";
  63470. Object.defineProperty(exports2, "__esModule", { value: true });
  63471. exports2.defaultEndpointResolver = void 0;
  63472. var util_endpoints_1 = require_dist_cjs19();
  63473. var util_endpoints_2 = require_dist_cjs18();
  63474. var ruleset_1 = require_ruleset2();
  63475. var cache3 = new util_endpoints_2.EndpointCache({
  63476. size: 50,
  63477. params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
  63478. });
  63479. var defaultEndpointResolver3 = (endpointParams, context = {}) => {
  63480. return cache3.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
  63481. endpointParams,
  63482. logger: context.logger
  63483. }));
  63484. };
  63485. exports2.defaultEndpointResolver = defaultEndpointResolver3;
  63486. util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;
  63487. }
  63488. });
  63489. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.shared.js
  63490. var require_runtimeConfig_shared2 = __commonJS({
  63491. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.shared.js"(exports2) {
  63492. "use strict";
  63493. Object.defineProperty(exports2, "__esModule", { value: true });
  63494. exports2.getRuntimeConfig = void 0;
  63495. var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
  63496. var smithy_client_1 = require_dist_cjs23();
  63497. var url_parser_1 = require_dist_cjs31();
  63498. var util_base64_1 = require_dist_cjs11();
  63499. var util_utf8_1 = require_dist_cjs10();
  63500. var httpAuthSchemeProvider_1 = require_httpAuthSchemeProvider();
  63501. var endpointResolver_1 = require_endpointResolver2();
  63502. var getRuntimeConfig5 = (config) => {
  63503. return {
  63504. apiVersion: "2018-08-01",
  63505. base64Decoder: (config == null ? void 0 : config.base64Decoder) ?? util_base64_1.fromBase64,
  63506. base64Encoder: (config == null ? void 0 : config.base64Encoder) ?? util_base64_1.toBase64,
  63507. disableHostPrefix: (config == null ? void 0 : config.disableHostPrefix) ?? false,
  63508. endpointProvider: (config == null ? void 0 : config.endpointProvider) ?? endpointResolver_1.defaultEndpointResolver,
  63509. extensions: (config == null ? void 0 : config.extensions) ?? [],
  63510. httpAuthSchemeProvider: (config == null ? void 0 : config.httpAuthSchemeProvider) ?? httpAuthSchemeProvider_1.defaultRDSDataHttpAuthSchemeProvider,
  63511. httpAuthSchemes: (config == null ? void 0 : config.httpAuthSchemes) ?? [
  63512. {
  63513. schemeId: "aws.auth#sigv4",
  63514. identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
  63515. signer: new core_1.AwsSdkSigV4Signer()
  63516. }
  63517. ],
  63518. logger: (config == null ? void 0 : config.logger) ?? new smithy_client_1.NoOpLogger(),
  63519. serviceId: (config == null ? void 0 : config.serviceId) ?? "RDS Data",
  63520. urlParser: (config == null ? void 0 : config.urlParser) ?? url_parser_1.parseUrl,
  63521. utf8Decoder: (config == null ? void 0 : config.utf8Decoder) ?? util_utf8_1.fromUtf8,
  63522. utf8Encoder: (config == null ? void 0 : config.utf8Encoder) ?? util_utf8_1.toUtf8
  63523. };
  63524. };
  63525. exports2.getRuntimeConfig = getRuntimeConfig5;
  63526. }
  63527. });
  63528. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.js
  63529. var require_runtimeConfig2 = __commonJS({
  63530. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/runtimeConfig.js"(exports2) {
  63531. "use strict";
  63532. Object.defineProperty(exports2, "__esModule", { value: true });
  63533. exports2.getRuntimeConfig = void 0;
  63534. var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
  63535. var package_json_1 = tslib_1.__importDefault(require_package2());
  63536. var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
  63537. var credential_provider_node_1 = require_dist_cjs50();
  63538. var util_user_agent_node_1 = require_dist_cjs39();
  63539. var config_resolver_1 = require_dist_cjs26();
  63540. var hash_node_1 = require_dist_cjs40();
  63541. var middleware_retry_1 = require_dist_cjs35();
  63542. var node_config_provider_1 = require_dist_cjs29();
  63543. var node_http_handler_1 = require_dist_cjs14();
  63544. var util_body_length_node_1 = require_dist_cjs41();
  63545. var util_retry_1 = require_dist_cjs34();
  63546. var runtimeConfig_shared_1 = require_runtimeConfig_shared2();
  63547. var smithy_client_1 = require_dist_cjs23();
  63548. var util_defaults_mode_node_1 = require_dist_cjs42();
  63549. var smithy_client_2 = require_dist_cjs23();
  63550. var getRuntimeConfig5 = (config) => {
  63551. (0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version);
  63552. const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config);
  63553. const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
  63554. const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config);
  63555. (0, core_1.emitWarningIfUnsupportedVersion)(process.version);
  63556. const loaderConfig = {
  63557. profile: config == null ? void 0 : config.profile,
  63558. logger: clientSharedValues.logger
  63559. };
  63560. return {
  63561. ...clientSharedValues,
  63562. ...config,
  63563. runtime: "node",
  63564. defaultsMode,
  63565. authSchemePreference: (config == null ? void 0 : config.authSchemePreference) ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
  63566. bodyLengthChecker: (config == null ? void 0 : config.bodyLengthChecker) ?? util_body_length_node_1.calculateBodyLength,
  63567. credentialDefaultProvider: (config == null ? void 0 : config.credentialDefaultProvider) ?? credential_provider_node_1.defaultProvider,
  63568. defaultUserAgentProvider: (config == null ? void 0 : config.defaultUserAgentProvider) ?? (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
  63569. maxAttempts: (config == null ? void 0 : config.maxAttempts) ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
  63570. region: (config == null ? void 0 : config.region) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
  63571. requestHandler: node_http_handler_1.NodeHttpHandler.create((config == null ? void 0 : config.requestHandler) ?? defaultConfigProvider),
  63572. retryMode: (config == null ? void 0 : config.retryMode) ?? (0, node_config_provider_1.loadConfig)({
  63573. ...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
  63574. default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE
  63575. }, config),
  63576. sha256: (config == null ? void 0 : config.sha256) ?? hash_node_1.Hash.bind(null, "sha256"),
  63577. streamCollector: (config == null ? void 0 : config.streamCollector) ?? node_http_handler_1.streamCollector,
  63578. useDualstackEndpoint: (config == null ? void 0 : config.useDualstackEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  63579. useFipsEndpoint: (config == null ? void 0 : config.useFipsEndpoint) ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
  63580. userAgentAppId: (config == null ? void 0 : config.userAgentAppId) ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig)
  63581. };
  63582. };
  63583. exports2.getRuntimeConfig = getRuntimeConfig5;
  63584. }
  63585. });
  63586. // ../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/index.js
  63587. var require_dist_cjs51 = __commonJS({
  63588. "../node_modules/.pnpm/@aws-sdk+client-rds-data@3.817.0/node_modules/@aws-sdk/client-rds-data/dist-cjs/index.js"(exports2, module2) {
  63589. "use strict";
  63590. var __defProp3 = Object.defineProperty;
  63591. var __getOwnPropDesc3 = Object.getOwnPropertyDescriptor;
  63592. var __getOwnPropNames3 = Object.getOwnPropertyNames;
  63593. var __hasOwnProp3 = Object.prototype.hasOwnProperty;
  63594. var __name = (target, value) => __defProp3(target, "name", { value, configurable: true });
  63595. var __export2 = (target, all) => {
  63596. for (var name in all)
  63597. __defProp3(target, name, { get: all[name], enumerable: true });
  63598. };
  63599. var __copyProps3 = (to, from, except, desc) => {
  63600. if (from && typeof from === "object" || typeof from === "function") {
  63601. for (let key of __getOwnPropNames3(from))
  63602. if (!__hasOwnProp3.call(to, key) && key !== except)
  63603. __defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc3(from, key)) || desc.enumerable });
  63604. }
  63605. return to;
  63606. };
  63607. var __toCommonJS2 = (mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod);
  63608. var index_exports = {};
  63609. __export2(index_exports, {
  63610. AccessDeniedException: () => AccessDeniedException2,
  63611. ArrayValue: () => ArrayValue,
  63612. BadRequestException: () => BadRequestException,
  63613. BatchExecuteStatementCommand: () => BatchExecuteStatementCommand,
  63614. BeginTransactionCommand: () => BeginTransactionCommand,
  63615. CommitTransactionCommand: () => CommitTransactionCommand,
  63616. DatabaseErrorException: () => DatabaseErrorException,
  63617. DatabaseNotFoundException: () => DatabaseNotFoundException,
  63618. DatabaseResumingException: () => DatabaseResumingException,
  63619. DatabaseUnavailableException: () => DatabaseUnavailableException,
  63620. DecimalReturnType: () => DecimalReturnType,
  63621. ExecuteSqlCommand: () => ExecuteSqlCommand,
  63622. ExecuteStatementCommand: () => ExecuteStatementCommand,
  63623. Field: () => Field,
  63624. ForbiddenException: () => ForbiddenException,
  63625. HttpEndpointNotEnabledException: () => HttpEndpointNotEnabledException,
  63626. InternalServerErrorException: () => InternalServerErrorException,
  63627. InvalidResourceStateException: () => InvalidResourceStateException,
  63628. InvalidSecretException: () => InvalidSecretException,
  63629. LongReturnType: () => LongReturnType,
  63630. NotFoundException: () => NotFoundException,
  63631. RDSData: () => RDSData,
  63632. RDSDataClient: () => RDSDataClient,
  63633. RDSDataServiceException: () => RDSDataServiceException,
  63634. RecordsFormatType: () => RecordsFormatType,
  63635. RollbackTransactionCommand: () => RollbackTransactionCommand,
  63636. SecretsErrorException: () => SecretsErrorException,
  63637. ServiceUnavailableError: () => ServiceUnavailableError,
  63638. StatementTimeoutException: () => StatementTimeoutException,
  63639. TransactionNotFoundException: () => TransactionNotFoundException,
  63640. TypeHint: () => TypeHint,
  63641. UnsupportedResultException: () => UnsupportedResultException,
  63642. Value: () => Value,
  63643. __Client: () => import_smithy_client25.Client
  63644. });
  63645. module2.exports = __toCommonJS2(index_exports);
  63646. var import_middleware_host_header3 = require_dist_cjs3();
  63647. var import_middleware_logger3 = require_dist_cjs4();
  63648. var import_middleware_recursion_detection3 = require_dist_cjs5();
  63649. var import_middleware_user_agent3 = require_dist_cjs24();
  63650. var import_config_resolver5 = require_dist_cjs26();
  63651. var import_core17 = (init_dist_es(), __toCommonJS(dist_es_exports));
  63652. var import_middleware_content_length3 = require_dist_cjs27();
  63653. var import_middleware_endpoint6 = require_dist_cjs32();
  63654. var import_middleware_retry5 = require_dist_cjs35();
  63655. var import_httpAuthSchemeProvider5 = require_httpAuthSchemeProvider();
  63656. var resolveClientEndpointParameters3 = /* @__PURE__ */ __name((options) => {
  63657. return Object.assign(options, {
  63658. useDualstackEndpoint: options.useDualstackEndpoint ?? false,
  63659. useFipsEndpoint: options.useFipsEndpoint ?? false,
  63660. defaultSigningName: "rds-data"
  63661. });
  63662. }, "resolveClientEndpointParameters");
  63663. var commonParams3 = {
  63664. UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
  63665. Endpoint: { type: "builtInParams", name: "endpoint" },
  63666. Region: { type: "builtInParams", name: "region" },
  63667. UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
  63668. };
  63669. var import_runtimeConfig5 = require_runtimeConfig2();
  63670. var import_region_config_resolver3 = require_dist_cjs43();
  63671. var import_protocol_http15 = require_dist_cjs2();
  63672. var import_smithy_client25 = require_dist_cjs23();
  63673. var getHttpAuthExtensionConfiguration3 = /* @__PURE__ */ __name((runtimeConfig) => {
  63674. const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
  63675. let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
  63676. let _credentials = runtimeConfig.credentials;
  63677. return {
  63678. setHttpAuthScheme(httpAuthScheme) {
  63679. const index6 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId);
  63680. if (index6 === -1) {
  63681. _httpAuthSchemes.push(httpAuthScheme);
  63682. } else {
  63683. _httpAuthSchemes.splice(index6, 1, httpAuthScheme);
  63684. }
  63685. },
  63686. httpAuthSchemes() {
  63687. return _httpAuthSchemes;
  63688. },
  63689. setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
  63690. _httpAuthSchemeProvider = httpAuthSchemeProvider;
  63691. },
  63692. httpAuthSchemeProvider() {
  63693. return _httpAuthSchemeProvider;
  63694. },
  63695. setCredentials(credentials2) {
  63696. _credentials = credentials2;
  63697. },
  63698. credentials() {
  63699. return _credentials;
  63700. }
  63701. };
  63702. }, "getHttpAuthExtensionConfiguration");
  63703. var resolveHttpAuthRuntimeConfig3 = /* @__PURE__ */ __name((config) => {
  63704. return {
  63705. httpAuthSchemes: config.httpAuthSchemes(),
  63706. httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
  63707. credentials: config.credentials()
  63708. };
  63709. }, "resolveHttpAuthRuntimeConfig");
  63710. var resolveRuntimeExtensions3 = /* @__PURE__ */ __name((runtimeConfig, extensions) => {
  63711. const extensionConfiguration = Object.assign(
  63712. (0, import_region_config_resolver3.getAwsRegionExtensionConfiguration)(runtimeConfig),
  63713. (0, import_smithy_client25.getDefaultExtensionConfiguration)(runtimeConfig),
  63714. (0, import_protocol_http15.getHttpHandlerExtensionConfiguration)(runtimeConfig),
  63715. getHttpAuthExtensionConfiguration3(runtimeConfig)
  63716. );
  63717. extensions.forEach((extension) => extension.configure(extensionConfiguration));
  63718. return Object.assign(
  63719. runtimeConfig,
  63720. (0, import_region_config_resolver3.resolveAwsRegionExtensionConfiguration)(extensionConfiguration),
  63721. (0, import_smithy_client25.resolveDefaultRuntimeConfig)(extensionConfiguration),
  63722. (0, import_protocol_http15.resolveHttpHandlerRuntimeConfig)(extensionConfiguration),
  63723. resolveHttpAuthRuntimeConfig3(extensionConfiguration)
  63724. );
  63725. }, "resolveRuntimeExtensions");
  63726. var _a2;
  63727. var RDSDataClient = (_a2 = class extends import_smithy_client25.Client {
  63728. /**
  63729. * The resolved configuration of RDSDataClient class. This is resolved and normalized from the {@link RDSDataClientConfig | constructor configuration interface}.
  63730. */
  63731. config;
  63732. constructor(...[configuration]) {
  63733. const _config_0 = (0, import_runtimeConfig5.getRuntimeConfig)(configuration || {});
  63734. super(_config_0);
  63735. this.initConfig = _config_0;
  63736. const _config_1 = resolveClientEndpointParameters3(_config_0);
  63737. const _config_2 = (0, import_middleware_user_agent3.resolveUserAgentConfig)(_config_1);
  63738. const _config_3 = (0, import_middleware_retry5.resolveRetryConfig)(_config_2);
  63739. const _config_4 = (0, import_config_resolver5.resolveRegionConfig)(_config_3);
  63740. const _config_5 = (0, import_middleware_host_header3.resolveHostHeaderConfig)(_config_4);
  63741. const _config_6 = (0, import_middleware_endpoint6.resolveEndpointConfig)(_config_5);
  63742. const _config_7 = (0, import_httpAuthSchemeProvider5.resolveHttpAuthSchemeConfig)(_config_6);
  63743. const _config_8 = resolveRuntimeExtensions3(_config_7, (configuration == null ? void 0 : configuration.extensions) || []);
  63744. this.config = _config_8;
  63745. this.middlewareStack.use((0, import_middleware_user_agent3.getUserAgentPlugin)(this.config));
  63746. this.middlewareStack.use((0, import_middleware_retry5.getRetryPlugin)(this.config));
  63747. this.middlewareStack.use((0, import_middleware_content_length3.getContentLengthPlugin)(this.config));
  63748. this.middlewareStack.use((0, import_middleware_host_header3.getHostHeaderPlugin)(this.config));
  63749. this.middlewareStack.use((0, import_middleware_logger3.getLoggerPlugin)(this.config));
  63750. this.middlewareStack.use((0, import_middleware_recursion_detection3.getRecursionDetectionPlugin)(this.config));
  63751. this.middlewareStack.use(
  63752. (0, import_core17.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, {
  63753. httpAuthSchemeParametersProvider: import_httpAuthSchemeProvider5.defaultRDSDataHttpAuthSchemeParametersProvider,
  63754. identityProviderConfigProvider: /* @__PURE__ */ __name(async (config) => new import_core17.DefaultIdentityProviderConfig({
  63755. "aws.auth#sigv4": config.credentials
  63756. }), "identityProviderConfigProvider")
  63757. })
  63758. );
  63759. this.middlewareStack.use((0, import_core17.getHttpSigningPlugin)(this.config));
  63760. }
  63761. /**
  63762. * Destroy underlying resources, like sockets. It's usually not necessary to do this.
  63763. * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
  63764. * Otherwise, sockets might stay open for quite a long time before the server terminates them.
  63765. */
  63766. destroy() {
  63767. super.destroy();
  63768. }
  63769. }, __name(_a2, "RDSDataClient"), _a2);
  63770. var import_middleware_serde5 = require_dist_cjs7();
  63771. var import_core22 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
  63772. var _a3;
  63773. var RDSDataServiceException = (_a3 = class extends import_smithy_client25.ServiceException {
  63774. /**
  63775. * @internal
  63776. */
  63777. constructor(options) {
  63778. super(options);
  63779. Object.setPrototypeOf(this, _a3.prototype);
  63780. }
  63781. }, __name(_a3, "RDSDataServiceException"), _a3);
  63782. var _a4;
  63783. var AccessDeniedException2 = (_a4 = class extends RDSDataServiceException {
  63784. name = "AccessDeniedException";
  63785. $fault = "client";
  63786. /**
  63787. * @internal
  63788. */
  63789. constructor(opts) {
  63790. super({
  63791. name: "AccessDeniedException",
  63792. $fault: "client",
  63793. ...opts
  63794. });
  63795. Object.setPrototypeOf(this, _a4.prototype);
  63796. }
  63797. }, __name(_a4, "AccessDeniedException"), _a4);
  63798. var _a5;
  63799. var BadRequestException = (_a5 = class extends RDSDataServiceException {
  63800. name = "BadRequestException";
  63801. $fault = "client";
  63802. /**
  63803. * @internal
  63804. */
  63805. constructor(opts) {
  63806. super({
  63807. name: "BadRequestException",
  63808. $fault: "client",
  63809. ...opts
  63810. });
  63811. Object.setPrototypeOf(this, _a5.prototype);
  63812. }
  63813. }, __name(_a5, "BadRequestException"), _a5);
  63814. var TypeHint = {
  63815. DATE: "DATE",
  63816. DECIMAL: "DECIMAL",
  63817. JSON: "JSON",
  63818. TIME: "TIME",
  63819. TIMESTAMP: "TIMESTAMP",
  63820. UUID: "UUID"
  63821. };
  63822. var _a6;
  63823. var DatabaseErrorException = (_a6 = class extends RDSDataServiceException {
  63824. name = "DatabaseErrorException";
  63825. $fault = "client";
  63826. /**
  63827. * @internal
  63828. */
  63829. constructor(opts) {
  63830. super({
  63831. name: "DatabaseErrorException",
  63832. $fault: "client",
  63833. ...opts
  63834. });
  63835. Object.setPrototypeOf(this, _a6.prototype);
  63836. }
  63837. }, __name(_a6, "DatabaseErrorException"), _a6);
  63838. var _a7;
  63839. var DatabaseNotFoundException = (_a7 = class extends RDSDataServiceException {
  63840. name = "DatabaseNotFoundException";
  63841. $fault = "client";
  63842. /**
  63843. * @internal
  63844. */
  63845. constructor(opts) {
  63846. super({
  63847. name: "DatabaseNotFoundException",
  63848. $fault: "client",
  63849. ...opts
  63850. });
  63851. Object.setPrototypeOf(this, _a7.prototype);
  63852. }
  63853. }, __name(_a7, "DatabaseNotFoundException"), _a7);
  63854. var _a8;
  63855. var DatabaseResumingException = (_a8 = class extends RDSDataServiceException {
  63856. name = "DatabaseResumingException";
  63857. $fault = "client";
  63858. /**
  63859. * @internal
  63860. */
  63861. constructor(opts) {
  63862. super({
  63863. name: "DatabaseResumingException",
  63864. $fault: "client",
  63865. ...opts
  63866. });
  63867. Object.setPrototypeOf(this, _a8.prototype);
  63868. }
  63869. }, __name(_a8, "DatabaseResumingException"), _a8);
  63870. var _a9;
  63871. var DatabaseUnavailableException = (_a9 = class extends RDSDataServiceException {
  63872. name = "DatabaseUnavailableException";
  63873. $fault = "server";
  63874. /**
  63875. * @internal
  63876. */
  63877. constructor(opts) {
  63878. super({
  63879. name: "DatabaseUnavailableException",
  63880. $fault: "server",
  63881. ...opts
  63882. });
  63883. Object.setPrototypeOf(this, _a9.prototype);
  63884. }
  63885. }, __name(_a9, "DatabaseUnavailableException"), _a9);
  63886. var _a10;
  63887. var ForbiddenException = (_a10 = class extends RDSDataServiceException {
  63888. name = "ForbiddenException";
  63889. $fault = "client";
  63890. /**
  63891. * @internal
  63892. */
  63893. constructor(opts) {
  63894. super({
  63895. name: "ForbiddenException",
  63896. $fault: "client",
  63897. ...opts
  63898. });
  63899. Object.setPrototypeOf(this, _a10.prototype);
  63900. }
  63901. }, __name(_a10, "ForbiddenException"), _a10);
  63902. var _a11;
  63903. var HttpEndpointNotEnabledException = (_a11 = class extends RDSDataServiceException {
  63904. name = "HttpEndpointNotEnabledException";
  63905. $fault = "client";
  63906. /**
  63907. * @internal
  63908. */
  63909. constructor(opts) {
  63910. super({
  63911. name: "HttpEndpointNotEnabledException",
  63912. $fault: "client",
  63913. ...opts
  63914. });
  63915. Object.setPrototypeOf(this, _a11.prototype);
  63916. }
  63917. }, __name(_a11, "HttpEndpointNotEnabledException"), _a11);
  63918. var _a12;
  63919. var InternalServerErrorException = (_a12 = class extends RDSDataServiceException {
  63920. name = "InternalServerErrorException";
  63921. $fault = "server";
  63922. /**
  63923. * @internal
  63924. */
  63925. constructor(opts) {
  63926. super({
  63927. name: "InternalServerErrorException",
  63928. $fault: "server",
  63929. ...opts
  63930. });
  63931. Object.setPrototypeOf(this, _a12.prototype);
  63932. }
  63933. }, __name(_a12, "InternalServerErrorException"), _a12);
  63934. var _a13;
  63935. var InvalidResourceStateException = (_a13 = class extends RDSDataServiceException {
  63936. name = "InvalidResourceStateException";
  63937. $fault = "client";
  63938. /**
  63939. * @internal
  63940. */
  63941. constructor(opts) {
  63942. super({
  63943. name: "InvalidResourceStateException",
  63944. $fault: "client",
  63945. ...opts
  63946. });
  63947. Object.setPrototypeOf(this, _a13.prototype);
  63948. }
  63949. }, __name(_a13, "InvalidResourceStateException"), _a13);
  63950. var _a14;
  63951. var InvalidSecretException = (_a14 = class extends RDSDataServiceException {
  63952. name = "InvalidSecretException";
  63953. $fault = "client";
  63954. /**
  63955. * @internal
  63956. */
  63957. constructor(opts) {
  63958. super({
  63959. name: "InvalidSecretException",
  63960. $fault: "client",
  63961. ...opts
  63962. });
  63963. Object.setPrototypeOf(this, _a14.prototype);
  63964. }
  63965. }, __name(_a14, "InvalidSecretException"), _a14);
  63966. var _a15;
  63967. var SecretsErrorException = (_a15 = class extends RDSDataServiceException {
  63968. name = "SecretsErrorException";
  63969. $fault = "client";
  63970. /**
  63971. * @internal
  63972. */
  63973. constructor(opts) {
  63974. super({
  63975. name: "SecretsErrorException",
  63976. $fault: "client",
  63977. ...opts
  63978. });
  63979. Object.setPrototypeOf(this, _a15.prototype);
  63980. }
  63981. }, __name(_a15, "SecretsErrorException"), _a15);
  63982. var _a16;
  63983. var ServiceUnavailableError = (_a16 = class extends RDSDataServiceException {
  63984. name = "ServiceUnavailableError";
  63985. $fault = "server";
  63986. /**
  63987. * @internal
  63988. */
  63989. constructor(opts) {
  63990. super({
  63991. name: "ServiceUnavailableError",
  63992. $fault: "server",
  63993. ...opts
  63994. });
  63995. Object.setPrototypeOf(this, _a16.prototype);
  63996. }
  63997. }, __name(_a16, "ServiceUnavailableError"), _a16);
  63998. var _a17;
  63999. var StatementTimeoutException = (_a17 = class extends RDSDataServiceException {
  64000. name = "StatementTimeoutException";
  64001. $fault = "client";
  64002. /**
  64003. * <p>The database connection ID that executed the SQL statement.</p>
  64004. * @public
  64005. */
  64006. dbConnectionId;
  64007. /**
  64008. * @internal
  64009. */
  64010. constructor(opts) {
  64011. super({
  64012. name: "StatementTimeoutException",
  64013. $fault: "client",
  64014. ...opts
  64015. });
  64016. Object.setPrototypeOf(this, _a17.prototype);
  64017. this.dbConnectionId = opts.dbConnectionId;
  64018. }
  64019. }, __name(_a17, "StatementTimeoutException"), _a17);
  64020. var _a18;
  64021. var TransactionNotFoundException = (_a18 = class extends RDSDataServiceException {
  64022. name = "TransactionNotFoundException";
  64023. $fault = "client";
  64024. /**
  64025. * @internal
  64026. */
  64027. constructor(opts) {
  64028. super({
  64029. name: "TransactionNotFoundException",
  64030. $fault: "client",
  64031. ...opts
  64032. });
  64033. Object.setPrototypeOf(this, _a18.prototype);
  64034. }
  64035. }, __name(_a18, "TransactionNotFoundException"), _a18);
  64036. var _a19;
  64037. var NotFoundException = (_a19 = class extends RDSDataServiceException {
  64038. name = "NotFoundException";
  64039. $fault = "client";
  64040. /**
  64041. * @internal
  64042. */
  64043. constructor(opts) {
  64044. super({
  64045. name: "NotFoundException",
  64046. $fault: "client",
  64047. ...opts
  64048. });
  64049. Object.setPrototypeOf(this, _a19.prototype);
  64050. }
  64051. }, __name(_a19, "NotFoundException"), _a19);
  64052. var DecimalReturnType = {
  64053. DOUBLE_OR_LONG: "DOUBLE_OR_LONG",
  64054. STRING: "STRING"
  64055. };
  64056. var RecordsFormatType = {
  64057. JSON: "JSON",
  64058. NONE: "NONE"
  64059. };
  64060. var LongReturnType = {
  64061. LONG: "LONG",
  64062. STRING: "STRING"
  64063. };
  64064. var _a20;
  64065. var UnsupportedResultException = (_a20 = class extends RDSDataServiceException {
  64066. name = "UnsupportedResultException";
  64067. $fault = "client";
  64068. /**
  64069. * @internal
  64070. */
  64071. constructor(opts) {
  64072. super({
  64073. name: "UnsupportedResultException",
  64074. $fault: "client",
  64075. ...opts
  64076. });
  64077. Object.setPrototypeOf(this, _a20.prototype);
  64078. }
  64079. }, __name(_a20, "UnsupportedResultException"), _a20);
  64080. var ArrayValue;
  64081. ((ArrayValue2) => {
  64082. ArrayValue2.visit = /* @__PURE__ */ __name((value, visitor) => {
  64083. if (value.booleanValues !== void 0) return visitor.booleanValues(value.booleanValues);
  64084. if (value.longValues !== void 0) return visitor.longValues(value.longValues);
  64085. if (value.doubleValues !== void 0) return visitor.doubleValues(value.doubleValues);
  64086. if (value.stringValues !== void 0) return visitor.stringValues(value.stringValues);
  64087. if (value.arrayValues !== void 0) return visitor.arrayValues(value.arrayValues);
  64088. return visitor._(value.$unknown[0], value.$unknown[1]);
  64089. }, "visit");
  64090. })(ArrayValue || (ArrayValue = {}));
  64091. var Field;
  64092. ((Field2) => {
  64093. Field2.visit = /* @__PURE__ */ __name((value, visitor) => {
  64094. if (value.isNull !== void 0) return visitor.isNull(value.isNull);
  64095. if (value.booleanValue !== void 0) return visitor.booleanValue(value.booleanValue);
  64096. if (value.longValue !== void 0) return visitor.longValue(value.longValue);
  64097. if (value.doubleValue !== void 0) return visitor.doubleValue(value.doubleValue);
  64098. if (value.stringValue !== void 0) return visitor.stringValue(value.stringValue);
  64099. if (value.blobValue !== void 0) return visitor.blobValue(value.blobValue);
  64100. if (value.arrayValue !== void 0) return visitor.arrayValue(value.arrayValue);
  64101. return visitor._(value.$unknown[0], value.$unknown[1]);
  64102. }, "visit");
  64103. })(Field || (Field = {}));
  64104. var Value;
  64105. ((Value3) => {
  64106. Value3.visit = /* @__PURE__ */ __name((value, visitor) => {
  64107. if (value.isNull !== void 0) return visitor.isNull(value.isNull);
  64108. if (value.bitValue !== void 0) return visitor.bitValue(value.bitValue);
  64109. if (value.bigIntValue !== void 0) return visitor.bigIntValue(value.bigIntValue);
  64110. if (value.intValue !== void 0) return visitor.intValue(value.intValue);
  64111. if (value.doubleValue !== void 0) return visitor.doubleValue(value.doubleValue);
  64112. if (value.realValue !== void 0) return visitor.realValue(value.realValue);
  64113. if (value.stringValue !== void 0) return visitor.stringValue(value.stringValue);
  64114. if (value.blobValue !== void 0) return visitor.blobValue(value.blobValue);
  64115. if (value.arrayValues !== void 0) return visitor.arrayValues(value.arrayValues);
  64116. if (value.structValue !== void 0) return visitor.structValue(value.structValue);
  64117. return visitor._(value.$unknown[0], value.$unknown[1]);
  64118. }, "visit");
  64119. })(Value || (Value = {}));
  64120. var se_BatchExecuteStatementCommand = /* @__PURE__ */ __name(async (input, context) => {
  64121. const b3 = (0, import_core17.requestBuilder)(input, context);
  64122. const headers = {
  64123. "content-type": "application/json"
  64124. };
  64125. b3.bp("/BatchExecute");
  64126. let body;
  64127. body = JSON.stringify(
  64128. (0, import_smithy_client25.take)(input, {
  64129. database: [],
  64130. parameterSets: /* @__PURE__ */ __name((_3) => se_SqlParameterSets(_3, context), "parameterSets"),
  64131. resourceArn: [],
  64132. schema: [],
  64133. secretArn: [],
  64134. sql: [],
  64135. transactionId: []
  64136. })
  64137. );
  64138. b3.m("POST").h(headers).b(body);
  64139. return b3.build();
  64140. }, "se_BatchExecuteStatementCommand");
  64141. var se_BeginTransactionCommand = /* @__PURE__ */ __name(async (input, context) => {
  64142. const b3 = (0, import_core17.requestBuilder)(input, context);
  64143. const headers = {
  64144. "content-type": "application/json"
  64145. };
  64146. b3.bp("/BeginTransaction");
  64147. let body;
  64148. body = JSON.stringify(
  64149. (0, import_smithy_client25.take)(input, {
  64150. database: [],
  64151. resourceArn: [],
  64152. schema: [],
  64153. secretArn: []
  64154. })
  64155. );
  64156. b3.m("POST").h(headers).b(body);
  64157. return b3.build();
  64158. }, "se_BeginTransactionCommand");
  64159. var se_CommitTransactionCommand = /* @__PURE__ */ __name(async (input, context) => {
  64160. const b3 = (0, import_core17.requestBuilder)(input, context);
  64161. const headers = {
  64162. "content-type": "application/json"
  64163. };
  64164. b3.bp("/CommitTransaction");
  64165. let body;
  64166. body = JSON.stringify(
  64167. (0, import_smithy_client25.take)(input, {
  64168. resourceArn: [],
  64169. secretArn: [],
  64170. transactionId: []
  64171. })
  64172. );
  64173. b3.m("POST").h(headers).b(body);
  64174. return b3.build();
  64175. }, "se_CommitTransactionCommand");
  64176. var se_ExecuteSqlCommand = /* @__PURE__ */ __name(async (input, context) => {
  64177. const b3 = (0, import_core17.requestBuilder)(input, context);
  64178. const headers = {
  64179. "content-type": "application/json"
  64180. };
  64181. b3.bp("/ExecuteSql");
  64182. let body;
  64183. body = JSON.stringify(
  64184. (0, import_smithy_client25.take)(input, {
  64185. awsSecretStoreArn: [],
  64186. database: [],
  64187. dbClusterOrInstanceArn: [],
  64188. schema: [],
  64189. sqlStatements: []
  64190. })
  64191. );
  64192. b3.m("POST").h(headers).b(body);
  64193. return b3.build();
  64194. }, "se_ExecuteSqlCommand");
  64195. var se_ExecuteStatementCommand = /* @__PURE__ */ __name(async (input, context) => {
  64196. const b3 = (0, import_core17.requestBuilder)(input, context);
  64197. const headers = {
  64198. "content-type": "application/json"
  64199. };
  64200. b3.bp("/Execute");
  64201. let body;
  64202. body = JSON.stringify(
  64203. (0, import_smithy_client25.take)(input, {
  64204. continueAfterTimeout: [],
  64205. database: [],
  64206. formatRecordsAs: [],
  64207. includeResultMetadata: [],
  64208. parameters: /* @__PURE__ */ __name((_3) => se_SqlParametersList(_3, context), "parameters"),
  64209. resourceArn: [],
  64210. resultSetOptions: /* @__PURE__ */ __name((_3) => (0, import_smithy_client25._json)(_3), "resultSetOptions"),
  64211. schema: [],
  64212. secretArn: [],
  64213. sql: [],
  64214. transactionId: []
  64215. })
  64216. );
  64217. b3.m("POST").h(headers).b(body);
  64218. return b3.build();
  64219. }, "se_ExecuteStatementCommand");
  64220. var se_RollbackTransactionCommand = /* @__PURE__ */ __name(async (input, context) => {
  64221. const b3 = (0, import_core17.requestBuilder)(input, context);
  64222. const headers = {
  64223. "content-type": "application/json"
  64224. };
  64225. b3.bp("/RollbackTransaction");
  64226. let body;
  64227. body = JSON.stringify(
  64228. (0, import_smithy_client25.take)(input, {
  64229. resourceArn: [],
  64230. secretArn: [],
  64231. transactionId: []
  64232. })
  64233. );
  64234. b3.m("POST").h(headers).b(body);
  64235. return b3.build();
  64236. }, "se_RollbackTransactionCommand");
  64237. var de_BatchExecuteStatementCommand = /* @__PURE__ */ __name(async (output, context) => {
  64238. if (output.statusCode !== 200 && output.statusCode >= 300) {
  64239. return de_CommandError3(output, context);
  64240. }
  64241. const contents = (0, import_smithy_client25.map)({
  64242. $metadata: deserializeMetadata3(output)
  64243. });
  64244. const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
  64245. const doc = (0, import_smithy_client25.take)(data, {
  64246. updateResults: /* @__PURE__ */ __name((_3) => de_UpdateResults(_3, context), "updateResults")
  64247. });
  64248. Object.assign(contents, doc);
  64249. return contents;
  64250. }, "de_BatchExecuteStatementCommand");
  64251. var de_BeginTransactionCommand = /* @__PURE__ */ __name(async (output, context) => {
  64252. if (output.statusCode !== 200 && output.statusCode >= 300) {
  64253. return de_CommandError3(output, context);
  64254. }
  64255. const contents = (0, import_smithy_client25.map)({
  64256. $metadata: deserializeMetadata3(output)
  64257. });
  64258. const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
  64259. const doc = (0, import_smithy_client25.take)(data, {
  64260. transactionId: import_smithy_client25.expectString
  64261. });
  64262. Object.assign(contents, doc);
  64263. return contents;
  64264. }, "de_BeginTransactionCommand");
  64265. var de_CommitTransactionCommand = /* @__PURE__ */ __name(async (output, context) => {
  64266. if (output.statusCode !== 200 && output.statusCode >= 300) {
  64267. return de_CommandError3(output, context);
  64268. }
  64269. const contents = (0, import_smithy_client25.map)({
  64270. $metadata: deserializeMetadata3(output)
  64271. });
  64272. const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
  64273. const doc = (0, import_smithy_client25.take)(data, {
  64274. transactionStatus: import_smithy_client25.expectString
  64275. });
  64276. Object.assign(contents, doc);
  64277. return contents;
  64278. }, "de_CommitTransactionCommand");
  64279. var de_ExecuteSqlCommand = /* @__PURE__ */ __name(async (output, context) => {
  64280. if (output.statusCode !== 200 && output.statusCode >= 300) {
  64281. return de_CommandError3(output, context);
  64282. }
  64283. const contents = (0, import_smithy_client25.map)({
  64284. $metadata: deserializeMetadata3(output)
  64285. });
  64286. const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
  64287. const doc = (0, import_smithy_client25.take)(data, {
  64288. sqlStatementResults: /* @__PURE__ */ __name((_3) => de_SqlStatementResults(_3, context), "sqlStatementResults")
  64289. });
  64290. Object.assign(contents, doc);
  64291. return contents;
  64292. }, "de_ExecuteSqlCommand");
  64293. var de_ExecuteStatementCommand = /* @__PURE__ */ __name(async (output, context) => {
  64294. if (output.statusCode !== 200 && output.statusCode >= 300) {
  64295. return de_CommandError3(output, context);
  64296. }
  64297. const contents = (0, import_smithy_client25.map)({
  64298. $metadata: deserializeMetadata3(output)
  64299. });
  64300. const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
  64301. const doc = (0, import_smithy_client25.take)(data, {
  64302. columnMetadata: import_smithy_client25._json,
  64303. formattedRecords: import_smithy_client25.expectString,
  64304. generatedFields: /* @__PURE__ */ __name((_3) => de_FieldList(_3, context), "generatedFields"),
  64305. numberOfRecordsUpdated: import_smithy_client25.expectLong,
  64306. records: /* @__PURE__ */ __name((_3) => de_SqlRecords(_3, context), "records")
  64307. });
  64308. Object.assign(contents, doc);
  64309. return contents;
  64310. }, "de_ExecuteStatementCommand");
  64311. var de_RollbackTransactionCommand = /* @__PURE__ */ __name(async (output, context) => {
  64312. if (output.statusCode !== 200 && output.statusCode >= 300) {
  64313. return de_CommandError3(output, context);
  64314. }
  64315. const contents = (0, import_smithy_client25.map)({
  64316. $metadata: deserializeMetadata3(output)
  64317. });
  64318. const data = (0, import_smithy_client25.expectNonNull)((0, import_smithy_client25.expectObject)(await (0, import_core22.parseJsonBody)(output.body, context)), "body");
  64319. const doc = (0, import_smithy_client25.take)(data, {
  64320. transactionStatus: import_smithy_client25.expectString
  64321. });
  64322. Object.assign(contents, doc);
  64323. return contents;
  64324. }, "de_RollbackTransactionCommand");
  64325. var de_CommandError3 = /* @__PURE__ */ __name(async (output, context) => {
  64326. const parsedOutput = {
  64327. ...output,
  64328. body: await (0, import_core22.parseJsonErrorBody)(output.body, context)
  64329. };
  64330. const errorCode = (0, import_core22.loadRestJsonErrorCode)(output, parsedOutput.body);
  64331. switch (errorCode) {
  64332. case "AccessDeniedException":
  64333. case "com.amazonaws.rdsdata#AccessDeniedException":
  64334. throw await de_AccessDeniedExceptionRes2(parsedOutput, context);
  64335. case "BadRequestException":
  64336. case "com.amazonaws.rdsdata#BadRequestException":
  64337. throw await de_BadRequestExceptionRes(parsedOutput, context);
  64338. case "DatabaseErrorException":
  64339. case "com.amazonaws.rdsdata#DatabaseErrorException":
  64340. throw await de_DatabaseErrorExceptionRes(parsedOutput, context);
  64341. case "DatabaseNotFoundException":
  64342. case "com.amazonaws.rdsdata#DatabaseNotFoundException":
  64343. throw await de_DatabaseNotFoundExceptionRes(parsedOutput, context);
  64344. case "DatabaseResumingException":
  64345. case "com.amazonaws.rdsdata#DatabaseResumingException":
  64346. throw await de_DatabaseResumingExceptionRes(parsedOutput, context);
  64347. case "DatabaseUnavailableException":
  64348. case "com.amazonaws.rdsdata#DatabaseUnavailableException":
  64349. throw await de_DatabaseUnavailableExceptionRes(parsedOutput, context);
  64350. case "ForbiddenException":
  64351. case "com.amazonaws.rdsdata#ForbiddenException":
  64352. throw await de_ForbiddenExceptionRes(parsedOutput, context);
  64353. case "HttpEndpointNotEnabledException":
  64354. case "com.amazonaws.rdsdata#HttpEndpointNotEnabledException":
  64355. throw await de_HttpEndpointNotEnabledExceptionRes(parsedOutput, context);
  64356. case "InternalServerErrorException":
  64357. case "com.amazonaws.rdsdata#InternalServerErrorException":
  64358. throw await de_InternalServerErrorExceptionRes(parsedOutput, context);
  64359. case "InvalidResourceStateException":
  64360. case "com.amazonaws.rdsdata#InvalidResourceStateException":
  64361. throw await de_InvalidResourceStateExceptionRes(parsedOutput, context);
  64362. case "InvalidSecretException":
  64363. case "com.amazonaws.rdsdata#InvalidSecretException":
  64364. throw await de_InvalidSecretExceptionRes(parsedOutput, context);
  64365. case "SecretsErrorException":
  64366. case "com.amazonaws.rdsdata#SecretsErrorException":
  64367. throw await de_SecretsErrorExceptionRes(parsedOutput, context);
  64368. case "ServiceUnavailableError":
  64369. case "com.amazonaws.rdsdata#ServiceUnavailableError":
  64370. throw await de_ServiceUnavailableErrorRes(parsedOutput, context);
  64371. case "StatementTimeoutException":
  64372. case "com.amazonaws.rdsdata#StatementTimeoutException":
  64373. throw await de_StatementTimeoutExceptionRes(parsedOutput, context);
  64374. case "TransactionNotFoundException":
  64375. case "com.amazonaws.rdsdata#TransactionNotFoundException":
  64376. throw await de_TransactionNotFoundExceptionRes(parsedOutput, context);
  64377. case "NotFoundException":
  64378. case "com.amazonaws.rdsdata#NotFoundException":
  64379. throw await de_NotFoundExceptionRes(parsedOutput, context);
  64380. case "UnsupportedResultException":
  64381. case "com.amazonaws.rdsdata#UnsupportedResultException":
  64382. throw await de_UnsupportedResultExceptionRes(parsedOutput, context);
  64383. default:
  64384. const parsedBody = parsedOutput.body;
  64385. return throwDefaultError3({
  64386. output,
  64387. parsedBody,
  64388. errorCode
  64389. });
  64390. }
  64391. }, "de_CommandError");
  64392. var throwDefaultError3 = (0, import_smithy_client25.withBaseException)(RDSDataServiceException);
  64393. var de_AccessDeniedExceptionRes2 = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64394. const contents = (0, import_smithy_client25.map)({});
  64395. const data = parsedOutput.body;
  64396. const doc = (0, import_smithy_client25.take)(data, {
  64397. message: import_smithy_client25.expectString
  64398. });
  64399. Object.assign(contents, doc);
  64400. const exception = new AccessDeniedException2({
  64401. $metadata: deserializeMetadata3(parsedOutput),
  64402. ...contents
  64403. });
  64404. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64405. }, "de_AccessDeniedExceptionRes");
  64406. var de_BadRequestExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64407. const contents = (0, import_smithy_client25.map)({});
  64408. const data = parsedOutput.body;
  64409. const doc = (0, import_smithy_client25.take)(data, {
  64410. message: import_smithy_client25.expectString
  64411. });
  64412. Object.assign(contents, doc);
  64413. const exception = new BadRequestException({
  64414. $metadata: deserializeMetadata3(parsedOutput),
  64415. ...contents
  64416. });
  64417. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64418. }, "de_BadRequestExceptionRes");
  64419. var de_DatabaseErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64420. const contents = (0, import_smithy_client25.map)({});
  64421. const data = parsedOutput.body;
  64422. const doc = (0, import_smithy_client25.take)(data, {
  64423. message: import_smithy_client25.expectString
  64424. });
  64425. Object.assign(contents, doc);
  64426. const exception = new DatabaseErrorException({
  64427. $metadata: deserializeMetadata3(parsedOutput),
  64428. ...contents
  64429. });
  64430. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64431. }, "de_DatabaseErrorExceptionRes");
  64432. var de_DatabaseNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64433. const contents = (0, import_smithy_client25.map)({});
  64434. const data = parsedOutput.body;
  64435. const doc = (0, import_smithy_client25.take)(data, {
  64436. message: import_smithy_client25.expectString
  64437. });
  64438. Object.assign(contents, doc);
  64439. const exception = new DatabaseNotFoundException({
  64440. $metadata: deserializeMetadata3(parsedOutput),
  64441. ...contents
  64442. });
  64443. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64444. }, "de_DatabaseNotFoundExceptionRes");
  64445. var de_DatabaseResumingExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64446. const contents = (0, import_smithy_client25.map)({});
  64447. const data = parsedOutput.body;
  64448. const doc = (0, import_smithy_client25.take)(data, {
  64449. message: import_smithy_client25.expectString
  64450. });
  64451. Object.assign(contents, doc);
  64452. const exception = new DatabaseResumingException({
  64453. $metadata: deserializeMetadata3(parsedOutput),
  64454. ...contents
  64455. });
  64456. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64457. }, "de_DatabaseResumingExceptionRes");
  64458. var de_DatabaseUnavailableExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64459. const contents = (0, import_smithy_client25.map)({});
  64460. const data = parsedOutput.body;
  64461. const doc = (0, import_smithy_client25.take)(data, {});
  64462. Object.assign(contents, doc);
  64463. const exception = new DatabaseUnavailableException({
  64464. $metadata: deserializeMetadata3(parsedOutput),
  64465. ...contents
  64466. });
  64467. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64468. }, "de_DatabaseUnavailableExceptionRes");
  64469. var de_ForbiddenExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64470. const contents = (0, import_smithy_client25.map)({});
  64471. const data = parsedOutput.body;
  64472. const doc = (0, import_smithy_client25.take)(data, {
  64473. message: import_smithy_client25.expectString
  64474. });
  64475. Object.assign(contents, doc);
  64476. const exception = new ForbiddenException({
  64477. $metadata: deserializeMetadata3(parsedOutput),
  64478. ...contents
  64479. });
  64480. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64481. }, "de_ForbiddenExceptionRes");
  64482. var de_HttpEndpointNotEnabledExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64483. const contents = (0, import_smithy_client25.map)({});
  64484. const data = parsedOutput.body;
  64485. const doc = (0, import_smithy_client25.take)(data, {
  64486. message: import_smithy_client25.expectString
  64487. });
  64488. Object.assign(contents, doc);
  64489. const exception = new HttpEndpointNotEnabledException({
  64490. $metadata: deserializeMetadata3(parsedOutput),
  64491. ...contents
  64492. });
  64493. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64494. }, "de_HttpEndpointNotEnabledExceptionRes");
  64495. var de_InternalServerErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64496. const contents = (0, import_smithy_client25.map)({});
  64497. const data = parsedOutput.body;
  64498. const doc = (0, import_smithy_client25.take)(data, {});
  64499. Object.assign(contents, doc);
  64500. const exception = new InternalServerErrorException({
  64501. $metadata: deserializeMetadata3(parsedOutput),
  64502. ...contents
  64503. });
  64504. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64505. }, "de_InternalServerErrorExceptionRes");
  64506. var de_InvalidResourceStateExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64507. const contents = (0, import_smithy_client25.map)({});
  64508. const data = parsedOutput.body;
  64509. const doc = (0, import_smithy_client25.take)(data, {
  64510. message: import_smithy_client25.expectString
  64511. });
  64512. Object.assign(contents, doc);
  64513. const exception = new InvalidResourceStateException({
  64514. $metadata: deserializeMetadata3(parsedOutput),
  64515. ...contents
  64516. });
  64517. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64518. }, "de_InvalidResourceStateExceptionRes");
  64519. var de_InvalidSecretExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64520. const contents = (0, import_smithy_client25.map)({});
  64521. const data = parsedOutput.body;
  64522. const doc = (0, import_smithy_client25.take)(data, {
  64523. message: import_smithy_client25.expectString
  64524. });
  64525. Object.assign(contents, doc);
  64526. const exception = new InvalidSecretException({
  64527. $metadata: deserializeMetadata3(parsedOutput),
  64528. ...contents
  64529. });
  64530. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64531. }, "de_InvalidSecretExceptionRes");
  64532. var de_NotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64533. const contents = (0, import_smithy_client25.map)({});
  64534. const data = parsedOutput.body;
  64535. const doc = (0, import_smithy_client25.take)(data, {
  64536. message: import_smithy_client25.expectString
  64537. });
  64538. Object.assign(contents, doc);
  64539. const exception = new NotFoundException({
  64540. $metadata: deserializeMetadata3(parsedOutput),
  64541. ...contents
  64542. });
  64543. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64544. }, "de_NotFoundExceptionRes");
  64545. var de_SecretsErrorExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64546. const contents = (0, import_smithy_client25.map)({});
  64547. const data = parsedOutput.body;
  64548. const doc = (0, import_smithy_client25.take)(data, {
  64549. message: import_smithy_client25.expectString
  64550. });
  64551. Object.assign(contents, doc);
  64552. const exception = new SecretsErrorException({
  64553. $metadata: deserializeMetadata3(parsedOutput),
  64554. ...contents
  64555. });
  64556. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64557. }, "de_SecretsErrorExceptionRes");
  64558. var de_ServiceUnavailableErrorRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64559. const contents = (0, import_smithy_client25.map)({});
  64560. const data = parsedOutput.body;
  64561. const doc = (0, import_smithy_client25.take)(data, {});
  64562. Object.assign(contents, doc);
  64563. const exception = new ServiceUnavailableError({
  64564. $metadata: deserializeMetadata3(parsedOutput),
  64565. ...contents
  64566. });
  64567. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64568. }, "de_ServiceUnavailableErrorRes");
  64569. var de_StatementTimeoutExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64570. const contents = (0, import_smithy_client25.map)({});
  64571. const data = parsedOutput.body;
  64572. const doc = (0, import_smithy_client25.take)(data, {
  64573. dbConnectionId: import_smithy_client25.expectLong,
  64574. message: import_smithy_client25.expectString
  64575. });
  64576. Object.assign(contents, doc);
  64577. const exception = new StatementTimeoutException({
  64578. $metadata: deserializeMetadata3(parsedOutput),
  64579. ...contents
  64580. });
  64581. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64582. }, "de_StatementTimeoutExceptionRes");
  64583. var de_TransactionNotFoundExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64584. const contents = (0, import_smithy_client25.map)({});
  64585. const data = parsedOutput.body;
  64586. const doc = (0, import_smithy_client25.take)(data, {
  64587. message: import_smithy_client25.expectString
  64588. });
  64589. Object.assign(contents, doc);
  64590. const exception = new TransactionNotFoundException({
  64591. $metadata: deserializeMetadata3(parsedOutput),
  64592. ...contents
  64593. });
  64594. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64595. }, "de_TransactionNotFoundExceptionRes");
  64596. var de_UnsupportedResultExceptionRes = /* @__PURE__ */ __name(async (parsedOutput, context) => {
  64597. const contents = (0, import_smithy_client25.map)({});
  64598. const data = parsedOutput.body;
  64599. const doc = (0, import_smithy_client25.take)(data, {
  64600. message: import_smithy_client25.expectString
  64601. });
  64602. Object.assign(contents, doc);
  64603. const exception = new UnsupportedResultException({
  64604. $metadata: deserializeMetadata3(parsedOutput),
  64605. ...contents
  64606. });
  64607. return (0, import_smithy_client25.decorateServiceException)(exception, parsedOutput.body);
  64608. }, "de_UnsupportedResultExceptionRes");
  64609. var se_ArrayOfArray = /* @__PURE__ */ __name((input, context) => {
  64610. return input.filter((e4) => e4 != null).map((entry) => {
  64611. return se_ArrayValue(entry, context);
  64612. });
  64613. }, "se_ArrayOfArray");
  64614. var se_ArrayValue = /* @__PURE__ */ __name((input, context) => {
  64615. return ArrayValue.visit(input, {
  64616. arrayValues: /* @__PURE__ */ __name((value) => ({ arrayValues: se_ArrayOfArray(value, context) }), "arrayValues"),
  64617. booleanValues: /* @__PURE__ */ __name((value) => ({ booleanValues: (0, import_smithy_client25._json)(value) }), "booleanValues"),
  64618. doubleValues: /* @__PURE__ */ __name((value) => ({ doubleValues: se_DoubleArray(value, context) }), "doubleValues"),
  64619. longValues: /* @__PURE__ */ __name((value) => ({ longValues: (0, import_smithy_client25._json)(value) }), "longValues"),
  64620. stringValues: /* @__PURE__ */ __name((value) => ({ stringValues: (0, import_smithy_client25._json)(value) }), "stringValues"),
  64621. _: /* @__PURE__ */ __name((name, value) => ({ [name]: value }), "_")
  64622. });
  64623. }, "se_ArrayValue");
  64624. var se_DoubleArray = /* @__PURE__ */ __name((input, context) => {
  64625. return input.filter((e4) => e4 != null).map((entry) => {
  64626. return (0, import_smithy_client25.serializeFloat)(entry);
  64627. });
  64628. }, "se_DoubleArray");
  64629. var se_Field = /* @__PURE__ */ __name((input, context) => {
  64630. return Field.visit(input, {
  64631. arrayValue: /* @__PURE__ */ __name((value) => ({ arrayValue: se_ArrayValue(value, context) }), "arrayValue"),
  64632. blobValue: /* @__PURE__ */ __name((value) => ({ blobValue: context.base64Encoder(value) }), "blobValue"),
  64633. booleanValue: /* @__PURE__ */ __name((value) => ({ booleanValue: value }), "booleanValue"),
  64634. doubleValue: /* @__PURE__ */ __name((value) => ({ doubleValue: (0, import_smithy_client25.serializeFloat)(value) }), "doubleValue"),
  64635. isNull: /* @__PURE__ */ __name((value) => ({ isNull: value }), "isNull"),
  64636. longValue: /* @__PURE__ */ __name((value) => ({ longValue: value }), "longValue"),
  64637. stringValue: /* @__PURE__ */ __name((value) => ({ stringValue: value }), "stringValue"),
  64638. _: /* @__PURE__ */ __name((name, value) => ({ [name]: value }), "_")
  64639. });
  64640. }, "se_Field");
  64641. var se_SqlParameter = /* @__PURE__ */ __name((input, context) => {
  64642. return (0, import_smithy_client25.take)(input, {
  64643. name: [],
  64644. typeHint: [],
  64645. value: /* @__PURE__ */ __name((_3) => se_Field(_3, context), "value")
  64646. });
  64647. }, "se_SqlParameter");
  64648. var se_SqlParameterSets = /* @__PURE__ */ __name((input, context) => {
  64649. return input.filter((e4) => e4 != null).map((entry) => {
  64650. return se_SqlParametersList(entry, context);
  64651. });
  64652. }, "se_SqlParameterSets");
  64653. var se_SqlParametersList = /* @__PURE__ */ __name((input, context) => {
  64654. return input.filter((e4) => e4 != null).map((entry) => {
  64655. return se_SqlParameter(entry, context);
  64656. });
  64657. }, "se_SqlParametersList");
  64658. var de_ArrayOfArray = /* @__PURE__ */ __name((output, context) => {
  64659. const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
  64660. return de_ArrayValue((0, import_core22.awsExpectUnion)(entry), context);
  64661. });
  64662. return retVal;
  64663. }, "de_ArrayOfArray");
  64664. var de_ArrayValue = /* @__PURE__ */ __name((output, context) => {
  64665. if (output.arrayValues != null) {
  64666. return {
  64667. arrayValues: de_ArrayOfArray(output.arrayValues, context)
  64668. };
  64669. }
  64670. if (output.booleanValues != null) {
  64671. return {
  64672. booleanValues: (0, import_smithy_client25._json)(output.booleanValues)
  64673. };
  64674. }
  64675. if (output.doubleValues != null) {
  64676. return {
  64677. doubleValues: de_DoubleArray(output.doubleValues, context)
  64678. };
  64679. }
  64680. if (output.longValues != null) {
  64681. return {
  64682. longValues: (0, import_smithy_client25._json)(output.longValues)
  64683. };
  64684. }
  64685. if (output.stringValues != null) {
  64686. return {
  64687. stringValues: (0, import_smithy_client25._json)(output.stringValues)
  64688. };
  64689. }
  64690. return { $unknown: Object.entries(output)[0] };
  64691. }, "de_ArrayValue");
  64692. var de_ArrayValueList = /* @__PURE__ */ __name((output, context) => {
  64693. const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
  64694. return de_Value((0, import_core22.awsExpectUnion)(entry), context);
  64695. });
  64696. return retVal;
  64697. }, "de_ArrayValueList");
  64698. var de_DoubleArray = /* @__PURE__ */ __name((output, context) => {
  64699. const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
  64700. return (0, import_smithy_client25.limitedParseDouble)(entry);
  64701. });
  64702. return retVal;
  64703. }, "de_DoubleArray");
  64704. var de_Field = /* @__PURE__ */ __name((output, context) => {
  64705. if (output.arrayValue != null) {
  64706. return {
  64707. arrayValue: de_ArrayValue((0, import_core22.awsExpectUnion)(output.arrayValue), context)
  64708. };
  64709. }
  64710. if (output.blobValue != null) {
  64711. return {
  64712. blobValue: context.base64Decoder(output.blobValue)
  64713. };
  64714. }
  64715. if ((0, import_smithy_client25.expectBoolean)(output.booleanValue) !== void 0) {
  64716. return { booleanValue: (0, import_smithy_client25.expectBoolean)(output.booleanValue) };
  64717. }
  64718. if ((0, import_smithy_client25.limitedParseDouble)(output.doubleValue) !== void 0) {
  64719. return { doubleValue: (0, import_smithy_client25.limitedParseDouble)(output.doubleValue) };
  64720. }
  64721. if ((0, import_smithy_client25.expectBoolean)(output.isNull) !== void 0) {
  64722. return { isNull: (0, import_smithy_client25.expectBoolean)(output.isNull) };
  64723. }
  64724. if ((0, import_smithy_client25.expectLong)(output.longValue) !== void 0) {
  64725. return { longValue: (0, import_smithy_client25.expectLong)(output.longValue) };
  64726. }
  64727. if ((0, import_smithy_client25.expectString)(output.stringValue) !== void 0) {
  64728. return { stringValue: (0, import_smithy_client25.expectString)(output.stringValue) };
  64729. }
  64730. return { $unknown: Object.entries(output)[0] };
  64731. }, "de_Field");
  64732. var de_FieldList = /* @__PURE__ */ __name((output, context) => {
  64733. const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
  64734. return de_Field((0, import_core22.awsExpectUnion)(entry), context);
  64735. });
  64736. return retVal;
  64737. }, "de_FieldList");
  64738. var de__Record = /* @__PURE__ */ __name((output, context) => {
  64739. return (0, import_smithy_client25.take)(output, {
  64740. values: /* @__PURE__ */ __name((_3) => de_Row(_3, context), "values")
  64741. });
  64742. }, "de__Record");
  64743. var de_Records = /* @__PURE__ */ __name((output, context) => {
  64744. const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
  64745. return de__Record(entry, context);
  64746. });
  64747. return retVal;
  64748. }, "de_Records");
  64749. var de_ResultFrame = /* @__PURE__ */ __name((output, context) => {
  64750. return (0, import_smithy_client25.take)(output, {
  64751. records: /* @__PURE__ */ __name((_3) => de_Records(_3, context), "records"),
  64752. resultSetMetadata: import_smithy_client25._json
  64753. });
  64754. }, "de_ResultFrame");
  64755. var de_Row = /* @__PURE__ */ __name((output, context) => {
  64756. const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
  64757. return de_Value((0, import_core22.awsExpectUnion)(entry), context);
  64758. });
  64759. return retVal;
  64760. }, "de_Row");
  64761. var de_SqlRecords = /* @__PURE__ */ __name((output, context) => {
  64762. const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
  64763. return de_FieldList(entry, context);
  64764. });
  64765. return retVal;
  64766. }, "de_SqlRecords");
  64767. var de_SqlStatementResult = /* @__PURE__ */ __name((output, context) => {
  64768. return (0, import_smithy_client25.take)(output, {
  64769. numberOfRecordsUpdated: import_smithy_client25.expectLong,
  64770. resultFrame: /* @__PURE__ */ __name((_3) => de_ResultFrame(_3, context), "resultFrame")
  64771. });
  64772. }, "de_SqlStatementResult");
  64773. var de_SqlStatementResults = /* @__PURE__ */ __name((output, context) => {
  64774. const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
  64775. return de_SqlStatementResult(entry, context);
  64776. });
  64777. return retVal;
  64778. }, "de_SqlStatementResults");
  64779. var de_StructValue = /* @__PURE__ */ __name((output, context) => {
  64780. return (0, import_smithy_client25.take)(output, {
  64781. attributes: /* @__PURE__ */ __name((_3) => de_ArrayValueList(_3, context), "attributes")
  64782. });
  64783. }, "de_StructValue");
  64784. var de_UpdateResult = /* @__PURE__ */ __name((output, context) => {
  64785. return (0, import_smithy_client25.take)(output, {
  64786. generatedFields: /* @__PURE__ */ __name((_3) => de_FieldList(_3, context), "generatedFields")
  64787. });
  64788. }, "de_UpdateResult");
  64789. var de_UpdateResults = /* @__PURE__ */ __name((output, context) => {
  64790. const retVal = (output || []).filter((e4) => e4 != null).map((entry) => {
  64791. return de_UpdateResult(entry, context);
  64792. });
  64793. return retVal;
  64794. }, "de_UpdateResults");
  64795. var de_Value = /* @__PURE__ */ __name((output, context) => {
  64796. if (output.arrayValues != null) {
  64797. return {
  64798. arrayValues: de_ArrayValueList(output.arrayValues, context)
  64799. };
  64800. }
  64801. if ((0, import_smithy_client25.expectLong)(output.bigIntValue) !== void 0) {
  64802. return { bigIntValue: (0, import_smithy_client25.expectLong)(output.bigIntValue) };
  64803. }
  64804. if ((0, import_smithy_client25.expectBoolean)(output.bitValue) !== void 0) {
  64805. return { bitValue: (0, import_smithy_client25.expectBoolean)(output.bitValue) };
  64806. }
  64807. if (output.blobValue != null) {
  64808. return {
  64809. blobValue: context.base64Decoder(output.blobValue)
  64810. };
  64811. }
  64812. if ((0, import_smithy_client25.limitedParseDouble)(output.doubleValue) !== void 0) {
  64813. return { doubleValue: (0, import_smithy_client25.limitedParseDouble)(output.doubleValue) };
  64814. }
  64815. if ((0, import_smithy_client25.expectInt32)(output.intValue) !== void 0) {
  64816. return { intValue: (0, import_smithy_client25.expectInt32)(output.intValue) };
  64817. }
  64818. if ((0, import_smithy_client25.expectBoolean)(output.isNull) !== void 0) {
  64819. return { isNull: (0, import_smithy_client25.expectBoolean)(output.isNull) };
  64820. }
  64821. if ((0, import_smithy_client25.limitedParseFloat32)(output.realValue) !== void 0) {
  64822. return { realValue: (0, import_smithy_client25.limitedParseFloat32)(output.realValue) };
  64823. }
  64824. if ((0, import_smithy_client25.expectString)(output.stringValue) !== void 0) {
  64825. return { stringValue: (0, import_smithy_client25.expectString)(output.stringValue) };
  64826. }
  64827. if (output.structValue != null) {
  64828. return {
  64829. structValue: de_StructValue(output.structValue, context)
  64830. };
  64831. }
  64832. return { $unknown: Object.entries(output)[0] };
  64833. }, "de_Value");
  64834. var deserializeMetadata3 = /* @__PURE__ */ __name((output) => ({
  64835. httpStatusCode: output.statusCode,
  64836. requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
  64837. extendedRequestId: output.headers["x-amz-id-2"],
  64838. cfId: output.headers["x-amz-cf-id"]
  64839. }), "deserializeMetadata");
  64840. var _a21;
  64841. var BatchExecuteStatementCommand = (_a21 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
  64842. return [
  64843. (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
  64844. (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  64845. ];
  64846. }).s("RdsDataService", "BatchExecuteStatement", {}).n("RDSDataClient", "BatchExecuteStatementCommand").f(void 0, void 0).ser(se_BatchExecuteStatementCommand).de(de_BatchExecuteStatementCommand).build() {
  64847. }, __name(_a21, "BatchExecuteStatementCommand"), _a21);
  64848. var _a22;
  64849. var BeginTransactionCommand = (_a22 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
  64850. return [
  64851. (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
  64852. (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  64853. ];
  64854. }).s("RdsDataService", "BeginTransaction", {}).n("RDSDataClient", "BeginTransactionCommand").f(void 0, void 0).ser(se_BeginTransactionCommand).de(de_BeginTransactionCommand).build() {
  64855. }, __name(_a22, "BeginTransactionCommand"), _a22);
  64856. var _a23;
  64857. var CommitTransactionCommand = (_a23 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
  64858. return [
  64859. (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
  64860. (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  64861. ];
  64862. }).s("RdsDataService", "CommitTransaction", {}).n("RDSDataClient", "CommitTransactionCommand").f(void 0, void 0).ser(se_CommitTransactionCommand).de(de_CommitTransactionCommand).build() {
  64863. }, __name(_a23, "CommitTransactionCommand"), _a23);
  64864. var _a24;
  64865. var ExecuteSqlCommand = (_a24 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
  64866. return [
  64867. (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
  64868. (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  64869. ];
  64870. }).s("RdsDataService", "ExecuteSql", {}).n("RDSDataClient", "ExecuteSqlCommand").f(void 0, void 0).ser(se_ExecuteSqlCommand).de(de_ExecuteSqlCommand).build() {
  64871. }, __name(_a24, "ExecuteSqlCommand"), _a24);
  64872. var _a25;
  64873. var ExecuteStatementCommand = (_a25 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
  64874. return [
  64875. (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
  64876. (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  64877. ];
  64878. }).s("RdsDataService", "ExecuteStatement", {}).n("RDSDataClient", "ExecuteStatementCommand").f(void 0, void 0).ser(se_ExecuteStatementCommand).de(de_ExecuteStatementCommand).build() {
  64879. }, __name(_a25, "ExecuteStatementCommand"), _a25);
  64880. var _a26;
  64881. var RollbackTransactionCommand = (_a26 = class extends import_smithy_client25.Command.classBuilder().ep(commonParams3).m(function(Command, cs, config, o3) {
  64882. return [
  64883. (0, import_middleware_serde5.getSerdePlugin)(config, this.serialize, this.deserialize),
  64884. (0, import_middleware_endpoint6.getEndpointPlugin)(config, Command.getEndpointParameterInstructions())
  64885. ];
  64886. }).s("RdsDataService", "RollbackTransaction", {}).n("RDSDataClient", "RollbackTransactionCommand").f(void 0, void 0).ser(se_RollbackTransactionCommand).de(de_RollbackTransactionCommand).build() {
  64887. }, __name(_a26, "RollbackTransactionCommand"), _a26);
  64888. var commands3 = {
  64889. BatchExecuteStatementCommand,
  64890. BeginTransactionCommand,
  64891. CommitTransactionCommand,
  64892. ExecuteSqlCommand,
  64893. ExecuteStatementCommand,
  64894. RollbackTransactionCommand
  64895. };
  64896. var _a27;
  64897. var RDSData = (_a27 = class extends RDSDataClient {
  64898. }, __name(_a27, "RDSData"), _a27);
  64899. (0, import_smithy_client25.createAggregatedClient)(commands3, RDSData);
  64900. }
  64901. });
  64902. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/chars.js
  64903. var require_chars = __commonJS({
  64904. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/chars.js"(exports2) {
  64905. "use strict";
  64906. Object.defineProperty(exports2, "__esModule", { value: true });
  64907. exports2.$v = exports2.$s = exports2.$r = exports2.$p = exports2.$o = exports2.$n = exports2.$m = exports2.$j = exports2.$b = exports2.$Z = exports2.$Y = exports2.$X = exports2.$V = exports2.$T = exports2.$S = exports2.$R = exports2.$Q = exports2.$P = exports2.$O = exports2.$M = exports2.$L = exports2.$K = exports2.$I = exports2.$H = exports2.$E = exports2.$D = exports2.$C = exports2.$A = exports2.$1 = exports2.$0 = void 0;
  64908. exports2.ord = ord;
  64909. exports2.chr = chr;
  64910. exports2.$0 = ord("0");
  64911. exports2.$1 = ord("1");
  64912. exports2.$A = ord("A");
  64913. exports2.$C = ord("C");
  64914. exports2.$D = ord("D");
  64915. exports2.$E = ord("E");
  64916. exports2.$H = ord("H");
  64917. exports2.$I = ord("I");
  64918. exports2.$K = ord("K");
  64919. exports2.$L = ord("L");
  64920. exports2.$M = ord("M");
  64921. exports2.$O = ord("O");
  64922. exports2.$P = ord("P");
  64923. exports2.$Q = ord("Q");
  64924. exports2.$R = ord("R");
  64925. exports2.$S = ord("S");
  64926. exports2.$T = ord("T");
  64927. exports2.$V = ord("V");
  64928. exports2.$X = ord("X");
  64929. exports2.$Y = ord("Y");
  64930. exports2.$Z = ord("Z");
  64931. exports2.$b = ord("b");
  64932. exports2.$j = ord("j");
  64933. exports2.$m = ord("m");
  64934. exports2.$n = ord("n");
  64935. exports2.$o = ord("o");
  64936. exports2.$p = ord("p");
  64937. exports2.$r = ord("r");
  64938. exports2.$s = ord("s");
  64939. exports2.$v = ord("v");
  64940. function ord(str) {
  64941. const ch = str.charCodeAt(0);
  64942. if (ch <= 0 || ch >= 255) {
  64943. throw new TypeError(`char "${ch}" is outside ASCII`);
  64944. }
  64945. return ch & 255;
  64946. }
  64947. function chr(ch) {
  64948. if (ch <= 0 || ch >= 255) {
  64949. throw new TypeError(`char "${ch}" is outside ASCII`);
  64950. }
  64951. return String.fromCharCode(ch);
  64952. }
  64953. }
  64954. });
  64955. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/buffer.js
  64956. var require_buffer = __commonJS({
  64957. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/buffer.js"(exports2) {
  64958. "use strict";
  64959. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  64960. if (k22 === void 0) k22 = k3;
  64961. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  64962. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  64963. desc = { enumerable: true, get: function() {
  64964. return m4[k3];
  64965. } };
  64966. }
  64967. Object.defineProperty(o3, k22, desc);
  64968. } : function(o3, m4, k3, k22) {
  64969. if (k22 === void 0) k22 = k3;
  64970. o3[k22] = m4[k3];
  64971. });
  64972. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  64973. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  64974. } : function(o3, v6) {
  64975. o3["default"] = v6;
  64976. });
  64977. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  64978. if (mod && mod.__esModule) return mod;
  64979. var result = {};
  64980. if (mod != null) {
  64981. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  64982. }
  64983. __setModuleDefault2(result, mod);
  64984. return result;
  64985. };
  64986. Object.defineProperty(exports2, "__esModule", { value: true });
  64987. exports2.ReadBuffer = exports2.ReadMessageBuffer = exports2.WriteMessageBuffer = exports2.WriteBuffer = exports2.BufferError = exports2.encodeB64 = exports2.decodeB64 = exports2.utf8Decoder = exports2.utf8Encoder = void 0;
  64988. exports2.uuidToBuffer = uuidToBuffer;
  64989. var chars = __importStar2(require_chars());
  64990. exports2.utf8Encoder = new TextEncoder();
  64991. exports2.utf8Decoder = new TextDecoder("utf8");
  64992. var decodeB64;
  64993. var encodeB64;
  64994. if (typeof Buffer === "function") {
  64995. exports2.decodeB64 = decodeB64 = (b64) => {
  64996. return Buffer.from(b64, "base64");
  64997. };
  64998. exports2.encodeB64 = encodeB64 = (data) => {
  64999. const buf = !Buffer.isBuffer(data) ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : data;
  65000. return buf.toString("base64");
  65001. };
  65002. } else {
  65003. exports2.decodeB64 = decodeB64 = (b64) => {
  65004. const binaryString = atob(b64);
  65005. const size = binaryString.length;
  65006. const bytes = new Uint8Array(size);
  65007. for (let i4 = 0; i4 < size; i4++) {
  65008. bytes[i4] = binaryString.charCodeAt(i4);
  65009. }
  65010. return bytes;
  65011. };
  65012. exports2.encodeB64 = encodeB64 = (data) => {
  65013. const binaryString = String.fromCharCode(...data);
  65014. return btoa(binaryString);
  65015. };
  65016. }
  65017. var BUFFER_INC_SIZE = 4096;
  65018. var EMPTY_BUFFER = new Uint8Array(0);
  65019. var BufferError = class extends Error {
  65020. };
  65021. exports2.BufferError = BufferError;
  65022. var WriteBuffer = class {
  65023. _rawBuffer;
  65024. buffer;
  65025. size;
  65026. pos;
  65027. constructor() {
  65028. this.size = BUFFER_INC_SIZE;
  65029. this.pos = 0;
  65030. this._rawBuffer = new Uint8Array(this.size);
  65031. this.buffer = new DataView(this._rawBuffer.buffer);
  65032. }
  65033. get position() {
  65034. return this.pos;
  65035. }
  65036. reset() {
  65037. this.pos = 0;
  65038. }
  65039. ensureAlloced(extraLength) {
  65040. const newSize = this.pos + extraLength;
  65041. if (newSize > this.size) {
  65042. this.__realloc(newSize);
  65043. }
  65044. }
  65045. __realloc(newSize) {
  65046. newSize += BUFFER_INC_SIZE;
  65047. const newBuffer = new Uint8Array(newSize);
  65048. newBuffer.set(this._rawBuffer);
  65049. this._rawBuffer = newBuffer;
  65050. this.buffer = new DataView(this._rawBuffer.buffer);
  65051. this.size = newSize;
  65052. }
  65053. writeChar(ch) {
  65054. this.ensureAlloced(1);
  65055. this.buffer.setUint8(this.pos, ch);
  65056. this.pos++;
  65057. return this;
  65058. }
  65059. writeString(s4) {
  65060. return this.writeBytes(exports2.utf8Encoder.encode(s4));
  65061. }
  65062. writeBytes(buf) {
  65063. this.ensureAlloced(buf.length + 4);
  65064. this.buffer.setInt32(this.pos, buf.length);
  65065. this.pos += 4;
  65066. this._rawBuffer.set(buf, this.pos);
  65067. this.pos += buf.length;
  65068. return this;
  65069. }
  65070. writeInt16(i4) {
  65071. this.ensureAlloced(2);
  65072. this.buffer.setInt16(this.pos, i4);
  65073. this.pos += 2;
  65074. return this;
  65075. }
  65076. writeInt32(i4) {
  65077. this.ensureAlloced(4);
  65078. this.buffer.setInt32(this.pos, i4);
  65079. this.pos += 4;
  65080. return this;
  65081. }
  65082. writeFloat32(i4) {
  65083. this.ensureAlloced(4);
  65084. this.buffer.setFloat32(this.pos, i4);
  65085. this.pos += 4;
  65086. return this;
  65087. }
  65088. writeFloat64(i4) {
  65089. this.ensureAlloced(8);
  65090. this.buffer.setFloat64(this.pos, i4);
  65091. this.pos += 8;
  65092. return this;
  65093. }
  65094. writeUInt8(i4) {
  65095. this.ensureAlloced(1);
  65096. this.buffer.setUint8(this.pos, i4);
  65097. this.pos += 1;
  65098. return this;
  65099. }
  65100. writeUInt16(i4) {
  65101. this.ensureAlloced(2);
  65102. this.buffer.setUint16(this.pos, i4);
  65103. this.pos += 2;
  65104. return this;
  65105. }
  65106. writeUInt32(i4) {
  65107. this.ensureAlloced(4);
  65108. this.buffer.setUint32(this.pos, i4);
  65109. this.pos += 4;
  65110. return this;
  65111. }
  65112. writeInt64(i4) {
  65113. this.ensureAlloced(8);
  65114. const hi = Math.floor(i4 / 4294967296);
  65115. const lo = i4 - hi * 4294967296;
  65116. this.buffer.setInt32(this.pos, hi);
  65117. this.buffer.setUint32(this.pos + 4, lo);
  65118. this.pos += 8;
  65119. return this;
  65120. }
  65121. writeBigInt64(i4) {
  65122. let ii = i4;
  65123. if (ii < 0n) {
  65124. ii = 18446744073709551616n + i4;
  65125. }
  65126. const hi = ii >> 32n;
  65127. const lo = ii & 0xffffffffn;
  65128. this.writeUInt32(Number(hi));
  65129. this.writeUInt32(Number(lo));
  65130. return this;
  65131. }
  65132. writeBuffer(buf) {
  65133. const len = buf.length;
  65134. this.ensureAlloced(len);
  65135. this._rawBuffer.set(buf, this.pos);
  65136. this.pos += len;
  65137. return this;
  65138. }
  65139. writeDeferredSize() {
  65140. const startPos = this.pos;
  65141. this.writeInt32(0);
  65142. return () => {
  65143. this.buffer.setInt32(startPos, this.pos - (startPos + 4));
  65144. };
  65145. }
  65146. unwrap() {
  65147. return this._rawBuffer.subarray(0, this.pos);
  65148. }
  65149. };
  65150. exports2.WriteBuffer = WriteBuffer;
  65151. var WriteMessageBuffer = class {
  65152. buffer;
  65153. messagePos;
  65154. constructor() {
  65155. this.messagePos = -1;
  65156. this.buffer = new WriteBuffer();
  65157. }
  65158. reset() {
  65159. this.messagePos = -1;
  65160. this.buffer.reset();
  65161. return this;
  65162. }
  65163. beginMessage(mtype) {
  65164. if (this.messagePos >= 0) {
  65165. throw new BufferError("cannot begin a new message: the previous message is not finished");
  65166. }
  65167. this.messagePos = this.buffer.position;
  65168. this.buffer.writeChar(mtype);
  65169. this.buffer.writeInt32(0);
  65170. return this;
  65171. }
  65172. endMessage() {
  65173. if (this.messagePos < 0) {
  65174. throw new BufferError("cannot end the message: no current message");
  65175. }
  65176. this.buffer.buffer.setInt32(this.messagePos + 1, this.buffer.position - this.messagePos - 1);
  65177. this.messagePos = -1;
  65178. return this;
  65179. }
  65180. writeChar(ch) {
  65181. if (this.messagePos < 0) {
  65182. throw new BufferError("cannot writeChar: no current message");
  65183. }
  65184. this.buffer.writeChar(ch);
  65185. return this;
  65186. }
  65187. writeString(s4) {
  65188. if (this.messagePos < 0) {
  65189. throw new BufferError("cannot writeString: no current message");
  65190. }
  65191. this.buffer.writeString(s4);
  65192. return this;
  65193. }
  65194. writeBytes(val2) {
  65195. if (this.messagePos < 0) {
  65196. throw new BufferError("cannot writeBytes: no current message");
  65197. }
  65198. this.buffer.writeBytes(val2);
  65199. return this;
  65200. }
  65201. writeInt16(i4) {
  65202. if (this.messagePos < 0) {
  65203. throw new BufferError("cannot writeInt16: no current message");
  65204. }
  65205. this.buffer.writeInt16(i4);
  65206. return this;
  65207. }
  65208. writeInt32(i4) {
  65209. if (this.messagePos < 0) {
  65210. throw new BufferError("cannot writeInt32: no current message");
  65211. }
  65212. this.buffer.writeInt32(i4);
  65213. return this;
  65214. }
  65215. writeUInt16(i4) {
  65216. if (this.messagePos < 0) {
  65217. throw new BufferError("cannot writeInt16: no current message");
  65218. }
  65219. this.buffer.writeUInt16(i4);
  65220. return this;
  65221. }
  65222. writeUInt32(i4) {
  65223. if (this.messagePos < 0) {
  65224. throw new BufferError("cannot writeInt32: no current message");
  65225. }
  65226. this.buffer.writeUInt32(i4);
  65227. return this;
  65228. }
  65229. writeBigInt64(i4) {
  65230. if (this.messagePos < 0) {
  65231. throw new BufferError("cannot writeChar: no current message");
  65232. }
  65233. this.buffer.writeBigInt64(i4);
  65234. return this;
  65235. }
  65236. writeFlags(h4, l3) {
  65237. if (this.messagePos < 0) {
  65238. throw new BufferError("cannot writeChar: no current message");
  65239. }
  65240. this.buffer.writeUInt32(h4);
  65241. this.buffer.writeUInt32(l3);
  65242. return this;
  65243. }
  65244. writeBuffer(buf) {
  65245. if (this.messagePos < 0) {
  65246. throw new BufferError("cannot writeBuffer: no current message");
  65247. }
  65248. this.buffer.writeBuffer(buf);
  65249. return this;
  65250. }
  65251. writeSync() {
  65252. if (this.messagePos >= 0) {
  65253. throw new BufferError("cannot writeSync: the previous message is not finished");
  65254. }
  65255. this.buffer.writeBuffer(SYNC_MESSAGE);
  65256. return this;
  65257. }
  65258. writeFlush() {
  65259. if (this.messagePos >= 0) {
  65260. throw new BufferError("cannot writeFlush: the previous message is not finished");
  65261. }
  65262. this.buffer.writeBuffer(FLUSH_MESSAGE);
  65263. return this;
  65264. }
  65265. unwrap() {
  65266. if (this.messagePos >= 0) {
  65267. throw new BufferError("cannot unwrap: an unfinished message is in the buffer");
  65268. }
  65269. return this.buffer.unwrap();
  65270. }
  65271. };
  65272. exports2.WriteMessageBuffer = WriteMessageBuffer;
  65273. var SYNC_MESSAGE = new WriteMessageBuffer().beginMessage(chars.$S).endMessage().unwrap();
  65274. var FLUSH_MESSAGE = new WriteMessageBuffer().beginMessage(chars.$H).endMessage().unwrap();
  65275. var byteToHex2 = [];
  65276. for (let i4 = 0; i4 < 256; ++i4) {
  65277. byteToHex2.push((i4 + 256).toString(16).slice(1));
  65278. }
  65279. function uuidToBuffer(uuid) {
  65280. const buf = new Uint8Array(16);
  65281. for (let i4 = 0; i4 < 16; i4++) {
  65282. buf[i4] = parseInt(uuid.slice(i4 * 2, i4 * 2 + 2), 16);
  65283. }
  65284. return buf;
  65285. }
  65286. var ReadMessageBuffer = class {
  65287. bufs;
  65288. len;
  65289. buf0;
  65290. pos0;
  65291. len0;
  65292. curMessageType;
  65293. curMessageLen;
  65294. curMessageLenUnread;
  65295. curMessageReady;
  65296. constructor() {
  65297. this.bufs = [];
  65298. this.buf0 = null;
  65299. this.pos0 = 0;
  65300. this.len0 = 0;
  65301. this.len = 0;
  65302. this.curMessageType = 0;
  65303. this.curMessageLen = 0;
  65304. this.curMessageLenUnread = 0;
  65305. this.curMessageReady = false;
  65306. }
  65307. get length() {
  65308. return this.len;
  65309. }
  65310. feed(buf) {
  65311. if (this.buf0 == null || this.pos0 === this.len0 && this.bufs.length === 0) {
  65312. this.buf0 = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
  65313. this.len0 = buf.byteLength;
  65314. this.pos0 = 0;
  65315. this.len = this.len0;
  65316. } else {
  65317. this.feedEnqueue(buf);
  65318. }
  65319. }
  65320. feedEnqueue(buf) {
  65321. this.bufs.push(buf);
  65322. this.len += buf.byteLength;
  65323. }
  65324. ensureFirstBuf() {
  65325. if (this.pos0 === this.len0) {
  65326. this.__nextBuf();
  65327. }
  65328. const buf0 = this.buf0;
  65329. if (buf0 == null || buf0.byteLength < 1) {
  65330. throw new BufferError("empty buffer");
  65331. }
  65332. return buf0;
  65333. }
  65334. checkOverread(size) {
  65335. if (this.curMessageLenUnread < size || size > this.len) {
  65336. throw new BufferError("buffer overread");
  65337. }
  65338. }
  65339. __nextBuf() {
  65340. const nextBuf = this.bufs.shift();
  65341. if (nextBuf == null) {
  65342. throw new BufferError("buffer overread");
  65343. }
  65344. this.buf0 = new DataView(nextBuf.buffer, nextBuf.byteOffset, nextBuf.byteLength);
  65345. this.pos0 = 0;
  65346. this.len0 = nextBuf.byteLength;
  65347. }
  65348. discardBuffer(size) {
  65349. this.ensureFirstBuf();
  65350. while (true) {
  65351. if (this.pos0 + size > this.len0) {
  65352. const nread = this.len0 - this.pos0;
  65353. this.pos0 = this.len0;
  65354. this.len -= nread;
  65355. size -= nread;
  65356. this.ensureFirstBuf();
  65357. } else {
  65358. this.pos0 += size;
  65359. this.len -= size;
  65360. break;
  65361. }
  65362. }
  65363. }
  65364. _finishMessage() {
  65365. this.curMessageLen = 0;
  65366. this.curMessageLenUnread = 0;
  65367. this.curMessageReady = false;
  65368. this.curMessageType = 0;
  65369. }
  65370. __readBufferCopy(buf0, size) {
  65371. const ret = new Uint8Array(size);
  65372. let retPos = 0;
  65373. while (true) {
  65374. if (this.pos0 + size > this.len0) {
  65375. const nread = this.len0 - this.pos0;
  65376. ret.set(new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, nread), retPos);
  65377. retPos += nread;
  65378. this.pos0 = this.len0;
  65379. this.len -= nread;
  65380. size -= nread;
  65381. buf0 = this.ensureFirstBuf();
  65382. } else {
  65383. ret.set(new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, size), retPos);
  65384. this.pos0 += size;
  65385. this.len -= size;
  65386. break;
  65387. }
  65388. }
  65389. return ret;
  65390. }
  65391. _readBuffer(size) {
  65392. if (size === 0) {
  65393. return EMPTY_BUFFER;
  65394. }
  65395. const buf0 = this.ensureFirstBuf();
  65396. if (this.pos0 + size <= this.len0) {
  65397. const ret = new Uint8Array(buf0.buffer, buf0.byteOffset + this.pos0, size);
  65398. this.pos0 += size;
  65399. this.len -= size;
  65400. return ret;
  65401. }
  65402. return this.__readBufferCopy(buf0, size);
  65403. }
  65404. readBuffer(size) {
  65405. this.checkOverread(size);
  65406. const buf = this._readBuffer(size);
  65407. this.curMessageLenUnread -= size;
  65408. return buf;
  65409. }
  65410. readUUID() {
  65411. const buf = this.readBuffer(16);
  65412. return byteToHex2[buf[0]] + byteToHex2[buf[1]] + byteToHex2[buf[2]] + byteToHex2[buf[3]] + byteToHex2[buf[4]] + byteToHex2[buf[5]] + byteToHex2[buf[6]] + byteToHex2[buf[7]] + byteToHex2[buf[8]] + byteToHex2[buf[9]] + byteToHex2[buf[10]] + byteToHex2[buf[11]] + byteToHex2[buf[12]] + byteToHex2[buf[13]] + byteToHex2[buf[14]] + byteToHex2[buf[15]];
  65413. }
  65414. readChar() {
  65415. this.checkOverread(1);
  65416. const buf0 = this.ensureFirstBuf();
  65417. const ret = buf0.getUint8(this.pos0);
  65418. this.pos0++;
  65419. this.curMessageLenUnread--;
  65420. this.len--;
  65421. return ret;
  65422. }
  65423. readInt16() {
  65424. this.checkOverread(2);
  65425. const buf0 = this.ensureFirstBuf();
  65426. if (this.pos0 + 2 <= this.len0) {
  65427. const ret = buf0.getInt16(this.pos0);
  65428. this.pos0 += 2;
  65429. this.curMessageLenUnread -= 2;
  65430. this.len -= 2;
  65431. return ret;
  65432. }
  65433. const buf = this._readBuffer(2);
  65434. this.curMessageLenUnread -= 2;
  65435. return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt16(0);
  65436. }
  65437. readInt32() {
  65438. this.checkOverread(4);
  65439. const buf0 = this.ensureFirstBuf();
  65440. if (this.pos0 + 4 <= this.len0) {
  65441. const ret = buf0.getInt32(this.pos0);
  65442. this.pos0 += 4;
  65443. this.curMessageLenUnread -= 4;
  65444. this.len -= 4;
  65445. return ret;
  65446. }
  65447. const buf = this._readBuffer(4);
  65448. this.curMessageLenUnread -= 4;
  65449. return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt32(0);
  65450. }
  65451. readUInt16() {
  65452. this.checkOverread(2);
  65453. const buf0 = this.ensureFirstBuf();
  65454. if (this.pos0 + 2 <= this.len0) {
  65455. const ret = buf0.getUint16(this.pos0);
  65456. this.pos0 += 2;
  65457. this.curMessageLenUnread -= 2;
  65458. this.len -= 2;
  65459. return ret;
  65460. }
  65461. const buf = this._readBuffer(2);
  65462. this.curMessageLenUnread -= 2;
  65463. return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getUint16(0);
  65464. }
  65465. readUInt32() {
  65466. this.checkOverread(4);
  65467. const buf0 = this.ensureFirstBuf();
  65468. if (this.pos0 + 4 <= this.len0) {
  65469. const ret = buf0.getUint32(this.pos0);
  65470. this.pos0 += 4;
  65471. this.curMessageLenUnread -= 4;
  65472. this.len -= 4;
  65473. return ret;
  65474. }
  65475. const buf = this._readBuffer(4);
  65476. this.curMessageLenUnread -= 4;
  65477. return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getUint32(0);
  65478. }
  65479. readBigInt64() {
  65480. this.checkOverread(8);
  65481. const buf0 = this.ensureFirstBuf();
  65482. if (this.pos0 + 8 <= this.len0) {
  65483. const ret = buf0.getBigInt64(this.pos0);
  65484. this.pos0 += 8;
  65485. this.curMessageLenUnread -= 8;
  65486. this.len -= 8;
  65487. return ret;
  65488. }
  65489. const buf = this._readBuffer(8);
  65490. this.curMessageLenUnread -= 8;
  65491. return new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getBigInt64(0);
  65492. }
  65493. readString() {
  65494. const len = this.readInt32();
  65495. const buf = this.readBuffer(len);
  65496. return exports2.utf8Decoder.decode(buf);
  65497. }
  65498. readLenPrefixedBuffer() {
  65499. const len = this.readInt32();
  65500. return this.readBuffer(len);
  65501. }
  65502. takeMessage() {
  65503. if (this.curMessageReady) {
  65504. return true;
  65505. }
  65506. if (this.curMessageType === 0) {
  65507. if (this.len < 1) {
  65508. return false;
  65509. }
  65510. const buf0 = this.ensureFirstBuf();
  65511. this.curMessageType = buf0.getUint8(this.pos0);
  65512. this.pos0++;
  65513. this.len--;
  65514. }
  65515. if (this.curMessageLen === 0) {
  65516. if (this.len < 4) {
  65517. return false;
  65518. }
  65519. const buf0 = this.ensureFirstBuf();
  65520. if (this.pos0 + 4 <= this.len0) {
  65521. this.curMessageLen = buf0.getInt32(this.pos0);
  65522. this.pos0 += 4;
  65523. this.len -= 4;
  65524. } else {
  65525. const buf = this._readBuffer(4);
  65526. this.curMessageLen = new DataView(buf.buffer, buf.byteOffset, buf.byteLength).getInt32(0);
  65527. }
  65528. this.curMessageLenUnread = this.curMessageLen - 4;
  65529. }
  65530. if (this.len < this.curMessageLenUnread) {
  65531. return false;
  65532. }
  65533. this.curMessageReady = true;
  65534. return true;
  65535. }
  65536. getMessageType() {
  65537. return this.curMessageType;
  65538. }
  65539. takeMessageType(mtype) {
  65540. if (this.curMessageReady) {
  65541. return this.curMessageType === mtype;
  65542. }
  65543. if (this.len >= 1) {
  65544. const buf0 = this.ensureFirstBuf();
  65545. const unreadMessageType = buf0.getUint8(this.pos0);
  65546. return mtype === unreadMessageType && this.takeMessage();
  65547. }
  65548. return false;
  65549. }
  65550. putMessage() {
  65551. if (!this.curMessageReady) {
  65552. throw new BufferError("cannot put message: no message taken");
  65553. }
  65554. if (this.curMessageLenUnread !== this.curMessageLen - 4) {
  65555. throw new BufferError("cannot put message: message is partially read");
  65556. }
  65557. this.curMessageReady = false;
  65558. }
  65559. discardMessage() {
  65560. if (!this.curMessageReady) {
  65561. throw new BufferError("no message to discard");
  65562. }
  65563. if (this.curMessageLenUnread > 0) {
  65564. this.discardBuffer(this.curMessageLenUnread);
  65565. }
  65566. this._finishMessage();
  65567. }
  65568. consumeMessage() {
  65569. if (!this.curMessageReady) {
  65570. throw new BufferError("no message to consume");
  65571. }
  65572. let buf;
  65573. if (this.curMessageLenUnread > 0) {
  65574. buf = this._readBuffer(this.curMessageLenUnread);
  65575. this.curMessageLenUnread = 0;
  65576. } else {
  65577. buf = EMPTY_BUFFER;
  65578. }
  65579. this._finishMessage();
  65580. return buf;
  65581. }
  65582. consumeMessageInto(frb) {
  65583. if (!this.curMessageReady) {
  65584. throw new BufferError("no message to consume");
  65585. }
  65586. if (this.curMessageLenUnread > 0) {
  65587. if (this.pos0 + this.curMessageLenUnread <= this.len0) {
  65588. ReadBuffer.init(frb, new Uint8Array(this.buf0.buffer, this.buf0.byteOffset + this.pos0, this.curMessageLenUnread));
  65589. this.pos0 += this.curMessageLenUnread;
  65590. this.len -= this.curMessageLenUnread;
  65591. } else {
  65592. const buf = this._readBuffer(this.curMessageLenUnread);
  65593. ReadBuffer.init(frb, buf);
  65594. }
  65595. this.curMessageLenUnread = 0;
  65596. } else {
  65597. ReadBuffer.init(frb, EMPTY_BUFFER);
  65598. }
  65599. this._finishMessage();
  65600. }
  65601. finishMessage() {
  65602. if (this.curMessageType === 0 || !this.curMessageReady) {
  65603. return;
  65604. }
  65605. if (this.curMessageLenUnread) {
  65606. throw new BufferError(`cannot finishMessage: unread data in message "${chars.chr(this.curMessageType)}"`);
  65607. }
  65608. this._finishMessage();
  65609. }
  65610. };
  65611. exports2.ReadMessageBuffer = ReadMessageBuffer;
  65612. var ReadBuffer = class {
  65613. _rawBuffer;
  65614. buffer;
  65615. pos;
  65616. len;
  65617. constructor(buf) {
  65618. this._rawBuffer = buf;
  65619. this.buffer = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
  65620. this.len = buf.length;
  65621. this.pos = 0;
  65622. }
  65623. get position() {
  65624. return this.pos;
  65625. }
  65626. get length() {
  65627. return this.len - this.pos;
  65628. }
  65629. finish(message) {
  65630. if (this.len !== this.pos) {
  65631. throw new BufferError(message ?? "unexpected trailing data in buffer");
  65632. }
  65633. }
  65634. discard(size) {
  65635. if (this.pos + size > this.len) {
  65636. throw new BufferError("buffer overread");
  65637. }
  65638. this.pos += size;
  65639. }
  65640. readUInt8() {
  65641. if (this.pos + 1 > this.len) {
  65642. throw new BufferError("buffer overread");
  65643. }
  65644. const num = this.buffer.getUint8(this.pos);
  65645. this.pos++;
  65646. return num;
  65647. }
  65648. readUInt16() {
  65649. if (this.pos + 2 > this.len) {
  65650. throw new BufferError("buffer overread");
  65651. }
  65652. const num = this.buffer.getUint16(this.pos);
  65653. this.pos += 2;
  65654. return num;
  65655. }
  65656. readInt8() {
  65657. if (this.pos + 1 > this.len) {
  65658. throw new BufferError("buffer overread");
  65659. }
  65660. const num = this.buffer.getInt8(this.pos);
  65661. this.pos++;
  65662. return num;
  65663. }
  65664. readInt16() {
  65665. if (this.pos + 2 > this.len) {
  65666. throw new BufferError("buffer overread");
  65667. }
  65668. const num = this.buffer.getInt16(this.pos);
  65669. this.pos += 2;
  65670. return num;
  65671. }
  65672. readInt32() {
  65673. if (this.pos + 4 > this.len) {
  65674. throw new BufferError("buffer overread");
  65675. }
  65676. const num = this.buffer.getInt32(this.pos);
  65677. this.pos += 4;
  65678. return num;
  65679. }
  65680. readFloat32() {
  65681. if (this.pos + 4 > this.len) {
  65682. throw new BufferError("buffer overread");
  65683. }
  65684. const num = this.buffer.getFloat32(this.pos);
  65685. this.pos += 4;
  65686. return num;
  65687. }
  65688. readFloat64(le) {
  65689. if (this.pos + 8 > this.len) {
  65690. throw new BufferError("buffer overread");
  65691. }
  65692. const num = this.buffer.getFloat64(this.pos, le);
  65693. this.pos += 8;
  65694. return num;
  65695. }
  65696. readUInt32(le) {
  65697. if (this.pos + 4 > this.len) {
  65698. throw new BufferError("buffer overread");
  65699. }
  65700. const num = this.buffer.getUint32(this.pos, le);
  65701. this.pos += 4;
  65702. return num;
  65703. }
  65704. reportInt64Overflow(hi, lo) {
  65705. const bhi = BigInt(hi);
  65706. const blo = BigInt(lo >>> 0);
  65707. const num = bhi * BigInt(4294967296) + blo;
  65708. throw new BufferError(`integer overflow: cannot unpack <std::int64>'${num.toString()}' into JavaScript Number type without losing precision`);
  65709. }
  65710. readInt64() {
  65711. if (this.pos + 8 > this.len) {
  65712. throw new BufferError("buffer overread");
  65713. }
  65714. const hi = this.buffer.getInt32(this.pos);
  65715. const lo = this.buffer.getInt32(this.pos + 4);
  65716. this.pos += 8;
  65717. if (hi === 0) {
  65718. return lo >>> 0;
  65719. } else if (hi >= -2097152 && hi < 2097152) {
  65720. return hi * 4294967296 + (lo >>> 0);
  65721. }
  65722. return this.reportInt64Overflow(hi, lo);
  65723. }
  65724. readBigInt64() {
  65725. if (this.pos + 8 > this.len) {
  65726. throw new BufferError("buffer overread");
  65727. }
  65728. const ret = this.buffer.getBigInt64(this.pos);
  65729. this.pos += 8;
  65730. return ret;
  65731. }
  65732. readBoolean() {
  65733. return this.readUInt8() !== 0;
  65734. }
  65735. readBuffer(size) {
  65736. if (this.pos + size > this.len) {
  65737. throw new BufferError("buffer overread");
  65738. }
  65739. const buf = this._rawBuffer.subarray(this.pos, this.pos + size);
  65740. this.pos += size;
  65741. return buf;
  65742. }
  65743. readUUIDBytes() {
  65744. return this.readBuffer(16);
  65745. }
  65746. readUUID(dash = "") {
  65747. if (this.pos + 16 > this.len) {
  65748. throw new BufferError("buffer overread");
  65749. }
  65750. const buf = this._rawBuffer;
  65751. const pos = this.pos;
  65752. const uuid = byteToHex2[buf[pos + 0]] + byteToHex2[buf[pos + 1]] + byteToHex2[buf[pos + 2]] + byteToHex2[buf[pos + 3]] + dash + byteToHex2[buf[pos + 4]] + byteToHex2[buf[pos + 5]] + dash + byteToHex2[buf[pos + 6]] + byteToHex2[buf[pos + 7]] + dash + byteToHex2[buf[pos + 8]] + byteToHex2[buf[pos + 9]] + dash + byteToHex2[buf[pos + 10]] + byteToHex2[buf[pos + 11]] + byteToHex2[buf[pos + 12]] + byteToHex2[buf[pos + 13]] + byteToHex2[buf[pos + 14]] + byteToHex2[buf[pos + 15]];
  65753. this.pos += 16;
  65754. return uuid;
  65755. }
  65756. readString() {
  65757. const len = this.readUInt32();
  65758. const buf = this.readBuffer(len);
  65759. return exports2.utf8Decoder.decode(buf);
  65760. }
  65761. consumeAsString() {
  65762. if (this.pos === this.len) {
  65763. return "";
  65764. }
  65765. const res = exports2.utf8Decoder.decode(this._rawBuffer.subarray(this.pos, this.len));
  65766. this.pos = this.len;
  65767. return res;
  65768. }
  65769. consumeAsBuffer() {
  65770. const res = this._rawBuffer.subarray(this.pos, this.len);
  65771. this.pos = this.len;
  65772. return res;
  65773. }
  65774. sliceInto(frb, size) {
  65775. if (this.pos + size > this.len) {
  65776. throw new BufferError("buffer overread");
  65777. }
  65778. frb._rawBuffer = this._rawBuffer;
  65779. frb.buffer = this.buffer;
  65780. frb.pos = this.pos;
  65781. frb.len = this.pos + size;
  65782. this.pos += size;
  65783. }
  65784. static init(frb, buffer) {
  65785. frb._rawBuffer = buffer;
  65786. frb.buffer = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  65787. frb.pos = 0;
  65788. frb.len = buffer.byteLength;
  65789. }
  65790. static alloc() {
  65791. return new this(EMPTY_BUFFER);
  65792. }
  65793. };
  65794. exports2.ReadBuffer = ReadBuffer;
  65795. }
  65796. });
  65797. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/base.js
  65798. var require_base = __commonJS({
  65799. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/base.js"(exports2) {
  65800. "use strict";
  65801. Object.defineProperty(exports2, "__esModule", { value: true });
  65802. exports2.ErrorAttr = exports2.GelError = void 0;
  65803. exports2.prettyPrintError = prettyPrintError;
  65804. var buffer_1 = require_buffer();
  65805. var GelError = class extends Error {
  65806. static tags = {};
  65807. _message;
  65808. _query;
  65809. _attrs;
  65810. constructor(message, options) {
  65811. super(void 0, options);
  65812. Object.defineProperties(this, {
  65813. _message: { writable: true, enumerable: false },
  65814. _query: { writable: true, enumerable: false },
  65815. _attrs: { writable: true, enumerable: false }
  65816. });
  65817. this._message = message ?? "";
  65818. }
  65819. get message() {
  65820. return this._message + (this._query && this._attrs ? prettyPrintError(this._attrs, this._query) : "");
  65821. }
  65822. get name() {
  65823. return this.constructor.name;
  65824. }
  65825. hasTag(tag) {
  65826. const error_type = this.constructor;
  65827. return error_type.tags[tag] ?? false;
  65828. }
  65829. };
  65830. exports2.GelError = GelError;
  65831. var ErrorAttr;
  65832. (function(ErrorAttr2) {
  65833. ErrorAttr2[ErrorAttr2["hint"] = 1] = "hint";
  65834. ErrorAttr2[ErrorAttr2["details"] = 2] = "details";
  65835. ErrorAttr2[ErrorAttr2["serverTraceback"] = 257] = "serverTraceback";
  65836. ErrorAttr2[ErrorAttr2["positionStart"] = -15] = "positionStart";
  65837. ErrorAttr2[ErrorAttr2["positionEnd"] = -14] = "positionEnd";
  65838. ErrorAttr2[ErrorAttr2["lineStart"] = -13] = "lineStart";
  65839. ErrorAttr2[ErrorAttr2["columnStart"] = -12] = "columnStart";
  65840. ErrorAttr2[ErrorAttr2["utf16ColumnStart"] = -11] = "utf16ColumnStart";
  65841. ErrorAttr2[ErrorAttr2["lineEnd"] = -10] = "lineEnd";
  65842. ErrorAttr2[ErrorAttr2["columnEnd"] = -9] = "columnEnd";
  65843. ErrorAttr2[ErrorAttr2["utf16ColumnEnd"] = -8] = "utf16ColumnEnd";
  65844. ErrorAttr2[ErrorAttr2["characterStart"] = -7] = "characterStart";
  65845. ErrorAttr2[ErrorAttr2["characterEnd"] = -6] = "characterEnd";
  65846. })(ErrorAttr || (exports2.ErrorAttr = ErrorAttr = {}));
  65847. function tryParseInt(val2) {
  65848. if (val2 == null)
  65849. return null;
  65850. try {
  65851. return parseInt(val2 instanceof Uint8Array ? buffer_1.utf8Decoder.decode(val2) : val2, 10);
  65852. } catch {
  65853. return null;
  65854. }
  65855. }
  65856. function readAttrStr(val2) {
  65857. return val2 instanceof Uint8Array ? buffer_1.utf8Decoder.decode(val2) : val2 ?? "";
  65858. }
  65859. function prettyPrintError(attrs, query) {
  65860. let errMessage = "\n";
  65861. const lineStart = tryParseInt(attrs.get(ErrorAttr.lineStart));
  65862. const lineEnd = tryParseInt(attrs.get(ErrorAttr.lineEnd));
  65863. const colStart = tryParseInt(attrs.get(ErrorAttr.utf16ColumnStart));
  65864. const colEnd = tryParseInt(attrs.get(ErrorAttr.utf16ColumnEnd));
  65865. if (lineStart != null && lineEnd != null && colStart != null && colEnd != null) {
  65866. const queryLines = query.split("\n");
  65867. const lineNoWidth = lineEnd.toString().length;
  65868. errMessage += "|".padStart(lineNoWidth + 3) + "\n";
  65869. for (let i4 = lineStart; i4 < lineEnd + 1; i4++) {
  65870. const line = queryLines[i4 - 1];
  65871. const start = i4 === lineStart ? colStart : 0;
  65872. const end = i4 === lineEnd ? colEnd : line.length;
  65873. errMessage += ` ${i4.toString().padStart(lineNoWidth)} | ${line}
  65874. `;
  65875. errMessage += `${"|".padStart(lineNoWidth + 3)} ${"".padStart(end - start, "^").padStart(end)}
  65876. `;
  65877. }
  65878. }
  65879. if (attrs.has(ErrorAttr.details)) {
  65880. errMessage += `Details: ${readAttrStr(attrs.get(ErrorAttr.details))}
  65881. `;
  65882. }
  65883. if (attrs.has(ErrorAttr.hint)) {
  65884. errMessage += `Hint: ${readAttrStr(attrs.get(ErrorAttr.hint))}
  65885. `;
  65886. }
  65887. return errMessage;
  65888. }
  65889. }
  65890. });
  65891. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/tags.js
  65892. var require_tags = __commonJS({
  65893. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/tags.js"(exports2) {
  65894. "use strict";
  65895. Object.defineProperty(exports2, "__esModule", { value: true });
  65896. exports2.SHOULD_RETRY = exports2.SHOULD_RECONNECT = void 0;
  65897. exports2.SHOULD_RECONNECT = Symbol("SHOULD_RECONNECT");
  65898. exports2.SHOULD_RETRY = Symbol("SHOULD_RETRY");
  65899. }
  65900. });
  65901. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/index.js
  65902. var require_errors = __commonJS({
  65903. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/index.js"(exports2) {
  65904. "use strict";
  65905. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  65906. if (k22 === void 0) k22 = k3;
  65907. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  65908. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  65909. desc = { enumerable: true, get: function() {
  65910. return m4[k3];
  65911. } };
  65912. }
  65913. Object.defineProperty(o3, k22, desc);
  65914. } : function(o3, m4, k3, k22) {
  65915. if (k22 === void 0) k22 = k3;
  65916. o3[k22] = m4[k3];
  65917. });
  65918. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  65919. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  65920. } : function(o3, v6) {
  65921. o3["default"] = v6;
  65922. });
  65923. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  65924. if (mod && mod.__esModule) return mod;
  65925. var result = {};
  65926. if (mod != null) {
  65927. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  65928. }
  65929. __setModuleDefault2(result, mod);
  65930. return result;
  65931. };
  65932. var __exportStar2 = exports2 && exports2.__exportStar || function(m4, exports3) {
  65933. for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) __createBinding2(exports3, m4, p3);
  65934. };
  65935. Object.defineProperty(exports2, "__esModule", { value: true });
  65936. exports2.DuplicatePropertyDefinitionError = exports2.DuplicateLinkDefinitionError = exports2.DuplicateModuleDefinitionError = exports2.DuplicateDefinitionError = exports2.InvalidCastDefinitionError = exports2.InvalidConstraintDefinitionError = exports2.InvalidFunctionDefinitionError = exports2.InvalidAliasDefinitionError = exports2.InvalidOperatorDefinitionError = exports2.InvalidDatabaseDefinitionError = exports2.InvalidUserDefinitionError = exports2.InvalidPropertyDefinitionError = exports2.InvalidLinkDefinitionError = exports2.InvalidModuleDefinitionError = exports2.InvalidDefinitionError = exports2.SchemaDefinitionError = exports2.SchemaError = exports2.DeprecatedScopingError = exports2.UnknownParameterError = exports2.UnknownDatabaseError = exports2.UnknownUserError = exports2.UnknownPropertyError = exports2.UnknownLinkError = exports2.UnknownModuleError = exports2.InvalidReferenceError = exports2.InvalidPropertyTargetError = exports2.InvalidLinkTargetError = exports2.InvalidTargetError = exports2.InvalidTypeError = exports2.GraphQLSyntaxError = exports2.SchemaSyntaxError = exports2.EdgeQLSyntaxError = exports2.InvalidSyntaxError = exports2.QueryError = exports2.UnsafeIsolationLevelError = exports2.DisabledCapabilityError = exports2.UnsupportedCapabilityError = exports2.CapabilityError = exports2.ResultCardinalityMismatchError = exports2.StateMismatchError = exports2.ParameterTypeMismatchError = exports2.InputDataError = exports2.UnexpectedMessageError = exports2.TypeSpecNotFoundError = exports2.UnsupportedProtocolVersionError = exports2.BinaryProtocolError = exports2.ProtocolError = exports2.UnsupportedFeatureError = exports2.InternalServerError = exports2.GelError = void 0;
  65937. exports2.QueryArgumentError = exports2.InterfaceError = exports2.ClientConnectionClosedError = exports2.ClientConnectionTimeoutError = exports2.ClientConnectionFailedTemporarilyError = exports2.ClientConnectionFailedError = exports2.ClientConnectionError = exports2.ClientError = exports2.MigrationStatusMessage = exports2.StatusMessage = exports2.WarningMessage = exports2.LogMessage = exports2.UnsupportedBackendFeatureError = exports2.BackendError = exports2.ServerBlockedError = exports2.UnknownTenantError = exports2.ServerOfflineError = exports2.BackendUnavailableError = exports2.AvailabilityError = exports2.AuthenticationError = exports2.AccessError = exports2.ConfigurationError = exports2.WatchError = exports2.TransactionDeadlockError = exports2.TransactionSerializationError = exports2.TransactionConflictError = exports2.TransactionError = exports2.MissingRequiredError = exports2.CardinalityViolationError = exports2.ConstraintViolationError = exports2.IntegrityError = exports2.QueryAssertionError = exports2.AccessPolicyError = exports2.NumericOutOfRangeError = exports2.DivisionByZeroError = exports2.InvalidValueError = exports2.ExecutionError = exports2.IdleTransactionTimeoutError = exports2.TransactionTimeoutError = exports2.QueryTimeoutError = exports2.IdleSessionTimeoutError = exports2.SessionTimeoutError = exports2.DuplicateMigrationError = exports2.DuplicateCastDefinitionError = exports2.DuplicateConstraintDefinitionError = exports2.DuplicateFunctionDefinitionError = exports2.DuplicateViewDefinitionError = exports2.DuplicateOperatorDefinitionError = exports2.DuplicateDatabaseDefinitionError = exports2.DuplicateUserDefinitionError = void 0;
  65938. exports2.InternalClientError = exports2.NoDataError = exports2.InvalidArgumentError = exports2.UnknownArgumentError = exports2.MissingArgumentError = void 0;
  65939. var base_1 = require_base();
  65940. var tags = __importStar2(require_tags());
  65941. var base_2 = require_base();
  65942. Object.defineProperty(exports2, "GelError", { enumerable: true, get: function() {
  65943. return base_2.GelError;
  65944. } });
  65945. __exportStar2(require_tags(), exports2);
  65946. var InternalServerError = class extends base_1.GelError {
  65947. get code() {
  65948. return 16777216;
  65949. }
  65950. };
  65951. exports2.InternalServerError = InternalServerError;
  65952. var UnsupportedFeatureError = class extends base_1.GelError {
  65953. get code() {
  65954. return 33554432;
  65955. }
  65956. };
  65957. exports2.UnsupportedFeatureError = UnsupportedFeatureError;
  65958. var ProtocolError = class extends base_1.GelError {
  65959. get code() {
  65960. return 50331648;
  65961. }
  65962. };
  65963. exports2.ProtocolError = ProtocolError;
  65964. var BinaryProtocolError = class extends ProtocolError {
  65965. get code() {
  65966. return 50397184;
  65967. }
  65968. };
  65969. exports2.BinaryProtocolError = BinaryProtocolError;
  65970. var UnsupportedProtocolVersionError = class extends BinaryProtocolError {
  65971. get code() {
  65972. return 50397185;
  65973. }
  65974. };
  65975. exports2.UnsupportedProtocolVersionError = UnsupportedProtocolVersionError;
  65976. var TypeSpecNotFoundError = class extends BinaryProtocolError {
  65977. get code() {
  65978. return 50397186;
  65979. }
  65980. };
  65981. exports2.TypeSpecNotFoundError = TypeSpecNotFoundError;
  65982. var UnexpectedMessageError = class extends BinaryProtocolError {
  65983. get code() {
  65984. return 50397187;
  65985. }
  65986. };
  65987. exports2.UnexpectedMessageError = UnexpectedMessageError;
  65988. var InputDataError = class extends ProtocolError {
  65989. get code() {
  65990. return 50462720;
  65991. }
  65992. };
  65993. exports2.InputDataError = InputDataError;
  65994. var ParameterTypeMismatchError = class extends InputDataError {
  65995. get code() {
  65996. return 50462976;
  65997. }
  65998. };
  65999. exports2.ParameterTypeMismatchError = ParameterTypeMismatchError;
  66000. var StateMismatchError = class extends InputDataError {
  66001. static tags = { [tags.SHOULD_RETRY]: true };
  66002. get code() {
  66003. return 50463232;
  66004. }
  66005. };
  66006. exports2.StateMismatchError = StateMismatchError;
  66007. var ResultCardinalityMismatchError = class extends ProtocolError {
  66008. get code() {
  66009. return 50528256;
  66010. }
  66011. };
  66012. exports2.ResultCardinalityMismatchError = ResultCardinalityMismatchError;
  66013. var CapabilityError = class extends ProtocolError {
  66014. get code() {
  66015. return 50593792;
  66016. }
  66017. };
  66018. exports2.CapabilityError = CapabilityError;
  66019. var UnsupportedCapabilityError = class extends CapabilityError {
  66020. get code() {
  66021. return 50594048;
  66022. }
  66023. };
  66024. exports2.UnsupportedCapabilityError = UnsupportedCapabilityError;
  66025. var DisabledCapabilityError = class extends CapabilityError {
  66026. get code() {
  66027. return 50594304;
  66028. }
  66029. };
  66030. exports2.DisabledCapabilityError = DisabledCapabilityError;
  66031. var UnsafeIsolationLevelError = class extends CapabilityError {
  66032. get code() {
  66033. return 50594560;
  66034. }
  66035. };
  66036. exports2.UnsafeIsolationLevelError = UnsafeIsolationLevelError;
  66037. var QueryError = class extends base_1.GelError {
  66038. get code() {
  66039. return 67108864;
  66040. }
  66041. };
  66042. exports2.QueryError = QueryError;
  66043. var InvalidSyntaxError = class extends QueryError {
  66044. get code() {
  66045. return 67174400;
  66046. }
  66047. };
  66048. exports2.InvalidSyntaxError = InvalidSyntaxError;
  66049. var EdgeQLSyntaxError = class extends InvalidSyntaxError {
  66050. get code() {
  66051. return 67174656;
  66052. }
  66053. };
  66054. exports2.EdgeQLSyntaxError = EdgeQLSyntaxError;
  66055. var SchemaSyntaxError = class extends InvalidSyntaxError {
  66056. get code() {
  66057. return 67174912;
  66058. }
  66059. };
  66060. exports2.SchemaSyntaxError = SchemaSyntaxError;
  66061. var GraphQLSyntaxError = class extends InvalidSyntaxError {
  66062. get code() {
  66063. return 67175168;
  66064. }
  66065. };
  66066. exports2.GraphQLSyntaxError = GraphQLSyntaxError;
  66067. var InvalidTypeError = class extends QueryError {
  66068. get code() {
  66069. return 67239936;
  66070. }
  66071. };
  66072. exports2.InvalidTypeError = InvalidTypeError;
  66073. var InvalidTargetError = class extends InvalidTypeError {
  66074. get code() {
  66075. return 67240192;
  66076. }
  66077. };
  66078. exports2.InvalidTargetError = InvalidTargetError;
  66079. var InvalidLinkTargetError = class extends InvalidTargetError {
  66080. get code() {
  66081. return 67240193;
  66082. }
  66083. };
  66084. exports2.InvalidLinkTargetError = InvalidLinkTargetError;
  66085. var InvalidPropertyTargetError = class extends InvalidTargetError {
  66086. get code() {
  66087. return 67240194;
  66088. }
  66089. };
  66090. exports2.InvalidPropertyTargetError = InvalidPropertyTargetError;
  66091. var InvalidReferenceError = class extends QueryError {
  66092. get code() {
  66093. return 67305472;
  66094. }
  66095. };
  66096. exports2.InvalidReferenceError = InvalidReferenceError;
  66097. var UnknownModuleError = class extends InvalidReferenceError {
  66098. get code() {
  66099. return 67305473;
  66100. }
  66101. };
  66102. exports2.UnknownModuleError = UnknownModuleError;
  66103. var UnknownLinkError = class extends InvalidReferenceError {
  66104. get code() {
  66105. return 67305474;
  66106. }
  66107. };
  66108. exports2.UnknownLinkError = UnknownLinkError;
  66109. var UnknownPropertyError = class extends InvalidReferenceError {
  66110. get code() {
  66111. return 67305475;
  66112. }
  66113. };
  66114. exports2.UnknownPropertyError = UnknownPropertyError;
  66115. var UnknownUserError = class extends InvalidReferenceError {
  66116. get code() {
  66117. return 67305476;
  66118. }
  66119. };
  66120. exports2.UnknownUserError = UnknownUserError;
  66121. var UnknownDatabaseError = class extends InvalidReferenceError {
  66122. get code() {
  66123. return 67305477;
  66124. }
  66125. };
  66126. exports2.UnknownDatabaseError = UnknownDatabaseError;
  66127. var UnknownParameterError = class extends InvalidReferenceError {
  66128. get code() {
  66129. return 67305478;
  66130. }
  66131. };
  66132. exports2.UnknownParameterError = UnknownParameterError;
  66133. var DeprecatedScopingError = class extends InvalidReferenceError {
  66134. get code() {
  66135. return 67305479;
  66136. }
  66137. };
  66138. exports2.DeprecatedScopingError = DeprecatedScopingError;
  66139. var SchemaError = class extends QueryError {
  66140. get code() {
  66141. return 67371008;
  66142. }
  66143. };
  66144. exports2.SchemaError = SchemaError;
  66145. var SchemaDefinitionError = class extends QueryError {
  66146. get code() {
  66147. return 67436544;
  66148. }
  66149. };
  66150. exports2.SchemaDefinitionError = SchemaDefinitionError;
  66151. var InvalidDefinitionError = class extends SchemaDefinitionError {
  66152. get code() {
  66153. return 67436800;
  66154. }
  66155. };
  66156. exports2.InvalidDefinitionError = InvalidDefinitionError;
  66157. var InvalidModuleDefinitionError = class extends InvalidDefinitionError {
  66158. get code() {
  66159. return 67436801;
  66160. }
  66161. };
  66162. exports2.InvalidModuleDefinitionError = InvalidModuleDefinitionError;
  66163. var InvalidLinkDefinitionError = class extends InvalidDefinitionError {
  66164. get code() {
  66165. return 67436802;
  66166. }
  66167. };
  66168. exports2.InvalidLinkDefinitionError = InvalidLinkDefinitionError;
  66169. var InvalidPropertyDefinitionError = class extends InvalidDefinitionError {
  66170. get code() {
  66171. return 67436803;
  66172. }
  66173. };
  66174. exports2.InvalidPropertyDefinitionError = InvalidPropertyDefinitionError;
  66175. var InvalidUserDefinitionError = class extends InvalidDefinitionError {
  66176. get code() {
  66177. return 67436804;
  66178. }
  66179. };
  66180. exports2.InvalidUserDefinitionError = InvalidUserDefinitionError;
  66181. var InvalidDatabaseDefinitionError = class extends InvalidDefinitionError {
  66182. get code() {
  66183. return 67436805;
  66184. }
  66185. };
  66186. exports2.InvalidDatabaseDefinitionError = InvalidDatabaseDefinitionError;
  66187. var InvalidOperatorDefinitionError = class extends InvalidDefinitionError {
  66188. get code() {
  66189. return 67436806;
  66190. }
  66191. };
  66192. exports2.InvalidOperatorDefinitionError = InvalidOperatorDefinitionError;
  66193. var InvalidAliasDefinitionError = class extends InvalidDefinitionError {
  66194. get code() {
  66195. return 67436807;
  66196. }
  66197. };
  66198. exports2.InvalidAliasDefinitionError = InvalidAliasDefinitionError;
  66199. var InvalidFunctionDefinitionError = class extends InvalidDefinitionError {
  66200. get code() {
  66201. return 67436808;
  66202. }
  66203. };
  66204. exports2.InvalidFunctionDefinitionError = InvalidFunctionDefinitionError;
  66205. var InvalidConstraintDefinitionError = class extends InvalidDefinitionError {
  66206. get code() {
  66207. return 67436809;
  66208. }
  66209. };
  66210. exports2.InvalidConstraintDefinitionError = InvalidConstraintDefinitionError;
  66211. var InvalidCastDefinitionError = class extends InvalidDefinitionError {
  66212. get code() {
  66213. return 67436810;
  66214. }
  66215. };
  66216. exports2.InvalidCastDefinitionError = InvalidCastDefinitionError;
  66217. var DuplicateDefinitionError = class extends SchemaDefinitionError {
  66218. get code() {
  66219. return 67437056;
  66220. }
  66221. };
  66222. exports2.DuplicateDefinitionError = DuplicateDefinitionError;
  66223. var DuplicateModuleDefinitionError = class extends DuplicateDefinitionError {
  66224. get code() {
  66225. return 67437057;
  66226. }
  66227. };
  66228. exports2.DuplicateModuleDefinitionError = DuplicateModuleDefinitionError;
  66229. var DuplicateLinkDefinitionError = class extends DuplicateDefinitionError {
  66230. get code() {
  66231. return 67437058;
  66232. }
  66233. };
  66234. exports2.DuplicateLinkDefinitionError = DuplicateLinkDefinitionError;
  66235. var DuplicatePropertyDefinitionError = class extends DuplicateDefinitionError {
  66236. get code() {
  66237. return 67437059;
  66238. }
  66239. };
  66240. exports2.DuplicatePropertyDefinitionError = DuplicatePropertyDefinitionError;
  66241. var DuplicateUserDefinitionError = class extends DuplicateDefinitionError {
  66242. get code() {
  66243. return 67437060;
  66244. }
  66245. };
  66246. exports2.DuplicateUserDefinitionError = DuplicateUserDefinitionError;
  66247. var DuplicateDatabaseDefinitionError = class extends DuplicateDefinitionError {
  66248. get code() {
  66249. return 67437061;
  66250. }
  66251. };
  66252. exports2.DuplicateDatabaseDefinitionError = DuplicateDatabaseDefinitionError;
  66253. var DuplicateOperatorDefinitionError = class extends DuplicateDefinitionError {
  66254. get code() {
  66255. return 67437062;
  66256. }
  66257. };
  66258. exports2.DuplicateOperatorDefinitionError = DuplicateOperatorDefinitionError;
  66259. var DuplicateViewDefinitionError = class extends DuplicateDefinitionError {
  66260. get code() {
  66261. return 67437063;
  66262. }
  66263. };
  66264. exports2.DuplicateViewDefinitionError = DuplicateViewDefinitionError;
  66265. var DuplicateFunctionDefinitionError = class extends DuplicateDefinitionError {
  66266. get code() {
  66267. return 67437064;
  66268. }
  66269. };
  66270. exports2.DuplicateFunctionDefinitionError = DuplicateFunctionDefinitionError;
  66271. var DuplicateConstraintDefinitionError = class extends DuplicateDefinitionError {
  66272. get code() {
  66273. return 67437065;
  66274. }
  66275. };
  66276. exports2.DuplicateConstraintDefinitionError = DuplicateConstraintDefinitionError;
  66277. var DuplicateCastDefinitionError = class extends DuplicateDefinitionError {
  66278. get code() {
  66279. return 67437066;
  66280. }
  66281. };
  66282. exports2.DuplicateCastDefinitionError = DuplicateCastDefinitionError;
  66283. var DuplicateMigrationError = class extends DuplicateDefinitionError {
  66284. get code() {
  66285. return 67437067;
  66286. }
  66287. };
  66288. exports2.DuplicateMigrationError = DuplicateMigrationError;
  66289. var SessionTimeoutError = class extends QueryError {
  66290. get code() {
  66291. return 67502080;
  66292. }
  66293. };
  66294. exports2.SessionTimeoutError = SessionTimeoutError;
  66295. var IdleSessionTimeoutError = class extends SessionTimeoutError {
  66296. static tags = { [tags.SHOULD_RETRY]: true };
  66297. get code() {
  66298. return 67502336;
  66299. }
  66300. };
  66301. exports2.IdleSessionTimeoutError = IdleSessionTimeoutError;
  66302. var QueryTimeoutError = class extends SessionTimeoutError {
  66303. get code() {
  66304. return 67502592;
  66305. }
  66306. };
  66307. exports2.QueryTimeoutError = QueryTimeoutError;
  66308. var TransactionTimeoutError = class extends SessionTimeoutError {
  66309. get code() {
  66310. return 67504640;
  66311. }
  66312. };
  66313. exports2.TransactionTimeoutError = TransactionTimeoutError;
  66314. var IdleTransactionTimeoutError = class extends TransactionTimeoutError {
  66315. get code() {
  66316. return 67504641;
  66317. }
  66318. };
  66319. exports2.IdleTransactionTimeoutError = IdleTransactionTimeoutError;
  66320. var ExecutionError = class extends base_1.GelError {
  66321. get code() {
  66322. return 83886080;
  66323. }
  66324. };
  66325. exports2.ExecutionError = ExecutionError;
  66326. var InvalidValueError = class extends ExecutionError {
  66327. get code() {
  66328. return 83951616;
  66329. }
  66330. };
  66331. exports2.InvalidValueError = InvalidValueError;
  66332. var DivisionByZeroError = class extends InvalidValueError {
  66333. get code() {
  66334. return 83951617;
  66335. }
  66336. };
  66337. exports2.DivisionByZeroError = DivisionByZeroError;
  66338. var NumericOutOfRangeError = class extends InvalidValueError {
  66339. get code() {
  66340. return 83951618;
  66341. }
  66342. };
  66343. exports2.NumericOutOfRangeError = NumericOutOfRangeError;
  66344. var AccessPolicyError = class extends InvalidValueError {
  66345. get code() {
  66346. return 83951619;
  66347. }
  66348. };
  66349. exports2.AccessPolicyError = AccessPolicyError;
  66350. var QueryAssertionError = class extends InvalidValueError {
  66351. get code() {
  66352. return 83951620;
  66353. }
  66354. };
  66355. exports2.QueryAssertionError = QueryAssertionError;
  66356. var IntegrityError = class extends ExecutionError {
  66357. get code() {
  66358. return 84017152;
  66359. }
  66360. };
  66361. exports2.IntegrityError = IntegrityError;
  66362. var ConstraintViolationError = class extends IntegrityError {
  66363. get code() {
  66364. return 84017153;
  66365. }
  66366. };
  66367. exports2.ConstraintViolationError = ConstraintViolationError;
  66368. var CardinalityViolationError = class extends IntegrityError {
  66369. get code() {
  66370. return 84017154;
  66371. }
  66372. };
  66373. exports2.CardinalityViolationError = CardinalityViolationError;
  66374. var MissingRequiredError = class extends IntegrityError {
  66375. get code() {
  66376. return 84017155;
  66377. }
  66378. };
  66379. exports2.MissingRequiredError = MissingRequiredError;
  66380. var TransactionError = class extends ExecutionError {
  66381. get code() {
  66382. return 84082688;
  66383. }
  66384. };
  66385. exports2.TransactionError = TransactionError;
  66386. var TransactionConflictError = class extends TransactionError {
  66387. static tags = { [tags.SHOULD_RETRY]: true };
  66388. get code() {
  66389. return 84082944;
  66390. }
  66391. };
  66392. exports2.TransactionConflictError = TransactionConflictError;
  66393. var TransactionSerializationError = class extends TransactionConflictError {
  66394. static tags = { [tags.SHOULD_RETRY]: true };
  66395. get code() {
  66396. return 84082945;
  66397. }
  66398. };
  66399. exports2.TransactionSerializationError = TransactionSerializationError;
  66400. var TransactionDeadlockError = class extends TransactionConflictError {
  66401. static tags = { [tags.SHOULD_RETRY]: true };
  66402. get code() {
  66403. return 84082946;
  66404. }
  66405. };
  66406. exports2.TransactionDeadlockError = TransactionDeadlockError;
  66407. var WatchError = class extends ExecutionError {
  66408. get code() {
  66409. return 84148224;
  66410. }
  66411. };
  66412. exports2.WatchError = WatchError;
  66413. var ConfigurationError = class extends base_1.GelError {
  66414. get code() {
  66415. return 100663296;
  66416. }
  66417. };
  66418. exports2.ConfigurationError = ConfigurationError;
  66419. var AccessError = class extends base_1.GelError {
  66420. get code() {
  66421. return 117440512;
  66422. }
  66423. };
  66424. exports2.AccessError = AccessError;
  66425. var AuthenticationError = class extends AccessError {
  66426. get code() {
  66427. return 117506048;
  66428. }
  66429. };
  66430. exports2.AuthenticationError = AuthenticationError;
  66431. var AvailabilityError = class extends base_1.GelError {
  66432. get code() {
  66433. return 134217728;
  66434. }
  66435. };
  66436. exports2.AvailabilityError = AvailabilityError;
  66437. var BackendUnavailableError = class extends AvailabilityError {
  66438. static tags = { [tags.SHOULD_RETRY]: true };
  66439. get code() {
  66440. return 134217729;
  66441. }
  66442. };
  66443. exports2.BackendUnavailableError = BackendUnavailableError;
  66444. var ServerOfflineError = class extends AvailabilityError {
  66445. static tags = {
  66446. [tags.SHOULD_RECONNECT]: true,
  66447. [tags.SHOULD_RETRY]: true
  66448. };
  66449. get code() {
  66450. return 134217730;
  66451. }
  66452. };
  66453. exports2.ServerOfflineError = ServerOfflineError;
  66454. var UnknownTenantError = class extends AvailabilityError {
  66455. static tags = {
  66456. [tags.SHOULD_RECONNECT]: true,
  66457. [tags.SHOULD_RETRY]: true
  66458. };
  66459. get code() {
  66460. return 134217731;
  66461. }
  66462. };
  66463. exports2.UnknownTenantError = UnknownTenantError;
  66464. var ServerBlockedError = class extends AvailabilityError {
  66465. get code() {
  66466. return 134217732;
  66467. }
  66468. };
  66469. exports2.ServerBlockedError = ServerBlockedError;
  66470. var BackendError = class extends base_1.GelError {
  66471. get code() {
  66472. return 150994944;
  66473. }
  66474. };
  66475. exports2.BackendError = BackendError;
  66476. var UnsupportedBackendFeatureError = class extends BackendError {
  66477. get code() {
  66478. return 150995200;
  66479. }
  66480. };
  66481. exports2.UnsupportedBackendFeatureError = UnsupportedBackendFeatureError;
  66482. var LogMessage = class extends base_1.GelError {
  66483. get code() {
  66484. return 4026531840;
  66485. }
  66486. };
  66487. exports2.LogMessage = LogMessage;
  66488. var WarningMessage = class extends LogMessage {
  66489. get code() {
  66490. return 4026597376;
  66491. }
  66492. };
  66493. exports2.WarningMessage = WarningMessage;
  66494. var StatusMessage = class extends LogMessage {
  66495. get code() {
  66496. return 4026662912;
  66497. }
  66498. };
  66499. exports2.StatusMessage = StatusMessage;
  66500. var MigrationStatusMessage = class extends StatusMessage {
  66501. get code() {
  66502. return 4026662913;
  66503. }
  66504. };
  66505. exports2.MigrationStatusMessage = MigrationStatusMessage;
  66506. var ClientError = class extends base_1.GelError {
  66507. get code() {
  66508. return 4278190080;
  66509. }
  66510. };
  66511. exports2.ClientError = ClientError;
  66512. var ClientConnectionError = class extends ClientError {
  66513. get code() {
  66514. return 4278255616;
  66515. }
  66516. };
  66517. exports2.ClientConnectionError = ClientConnectionError;
  66518. var ClientConnectionFailedError = class extends ClientConnectionError {
  66519. get code() {
  66520. return 4278255872;
  66521. }
  66522. };
  66523. exports2.ClientConnectionFailedError = ClientConnectionFailedError;
  66524. var ClientConnectionFailedTemporarilyError = class extends ClientConnectionFailedError {
  66525. static tags = {
  66526. [tags.SHOULD_RECONNECT]: true,
  66527. [tags.SHOULD_RETRY]: true
  66528. };
  66529. get code() {
  66530. return 4278255873;
  66531. }
  66532. };
  66533. exports2.ClientConnectionFailedTemporarilyError = ClientConnectionFailedTemporarilyError;
  66534. var ClientConnectionTimeoutError = class extends ClientConnectionError {
  66535. static tags = {
  66536. [tags.SHOULD_RECONNECT]: true,
  66537. [tags.SHOULD_RETRY]: true
  66538. };
  66539. get code() {
  66540. return 4278256128;
  66541. }
  66542. };
  66543. exports2.ClientConnectionTimeoutError = ClientConnectionTimeoutError;
  66544. var ClientConnectionClosedError = class extends ClientConnectionError {
  66545. static tags = {
  66546. [tags.SHOULD_RECONNECT]: true,
  66547. [tags.SHOULD_RETRY]: true
  66548. };
  66549. get code() {
  66550. return 4278256384;
  66551. }
  66552. };
  66553. exports2.ClientConnectionClosedError = ClientConnectionClosedError;
  66554. var InterfaceError = class extends ClientError {
  66555. get code() {
  66556. return 4278321152;
  66557. }
  66558. };
  66559. exports2.InterfaceError = InterfaceError;
  66560. var QueryArgumentError = class extends InterfaceError {
  66561. get code() {
  66562. return 4278321408;
  66563. }
  66564. };
  66565. exports2.QueryArgumentError = QueryArgumentError;
  66566. var MissingArgumentError = class extends QueryArgumentError {
  66567. get code() {
  66568. return 4278321409;
  66569. }
  66570. };
  66571. exports2.MissingArgumentError = MissingArgumentError;
  66572. var UnknownArgumentError = class extends QueryArgumentError {
  66573. get code() {
  66574. return 4278321410;
  66575. }
  66576. };
  66577. exports2.UnknownArgumentError = UnknownArgumentError;
  66578. var InvalidArgumentError = class extends QueryArgumentError {
  66579. get code() {
  66580. return 4278321411;
  66581. }
  66582. };
  66583. exports2.InvalidArgumentError = InvalidArgumentError;
  66584. var NoDataError = class extends ClientError {
  66585. get code() {
  66586. return 4278386688;
  66587. }
  66588. };
  66589. exports2.NoDataError = NoDataError;
  66590. var InternalClientError = class extends ClientError {
  66591. get code() {
  66592. return 4278452224;
  66593. }
  66594. };
  66595. exports2.InternalClientError = InternalClientError;
  66596. }
  66597. });
  66598. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/lru.js
  66599. var require_lru = __commonJS({
  66600. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/lru.js"(exports2) {
  66601. "use strict";
  66602. Object.defineProperty(exports2, "__esModule", { value: true });
  66603. var errors_1 = require_errors();
  66604. var Node3 = class {
  66605. key;
  66606. value;
  66607. next;
  66608. prev;
  66609. constructor(key, value) {
  66610. this.key = key;
  66611. this.value = value;
  66612. this.next = null;
  66613. this.prev = null;
  66614. }
  66615. };
  66616. var Deque = class {
  66617. head;
  66618. tail;
  66619. len;
  66620. constructor() {
  66621. this.head = null;
  66622. this.tail = null;
  66623. this.len = 0;
  66624. }
  66625. get length() {
  66626. return this.len;
  66627. }
  66628. push(key, value) {
  66629. const node = new Node3(key, value);
  66630. if (this.head == null) {
  66631. this.head = node;
  66632. this.tail = node;
  66633. } else {
  66634. this.head.prev = node;
  66635. node.next = this.head;
  66636. this.head = node;
  66637. }
  66638. this.len++;
  66639. return node;
  66640. }
  66641. moveToTop(node) {
  66642. if (node.prev == null) {
  66643. return;
  66644. }
  66645. const prev = node.prev;
  66646. const next = node.next;
  66647. prev.next = next;
  66648. if (next != null) {
  66649. next.prev = prev;
  66650. }
  66651. if (this.tail === node) {
  66652. this.tail = prev;
  66653. }
  66654. node.prev = null;
  66655. node.next = this.head;
  66656. this.head.prev = node;
  66657. this.head = node;
  66658. }
  66659. deleteBottom() {
  66660. if (!this.len || !this.tail || !this.head) {
  66661. return null;
  66662. }
  66663. if (this.tail === this.head) {
  66664. this.len = 0;
  66665. const node = this.tail;
  66666. this.tail = null;
  66667. this.head = null;
  66668. return node;
  66669. }
  66670. const tail = this.tail;
  66671. const beforeLast = this.tail.prev;
  66672. beforeLast.next = null;
  66673. this.tail.prev = null;
  66674. this.tail.next = null;
  66675. this.tail = beforeLast;
  66676. this.len--;
  66677. return tail;
  66678. }
  66679. };
  66680. var LRU = class {
  66681. capacity;
  66682. map;
  66683. deque;
  66684. constructor({ capacity }) {
  66685. if (capacity <= 0) {
  66686. throw new TypeError("capacity is expected to be greater than 0");
  66687. }
  66688. this.capacity = capacity;
  66689. this.map = /* @__PURE__ */ new Map();
  66690. this.deque = new Deque();
  66691. }
  66692. get length() {
  66693. const len = this.map.size;
  66694. if (len !== this.deque.length) {
  66695. throw new errors_1.InternalClientError("deque & map disagree on elements count");
  66696. }
  66697. return len;
  66698. }
  66699. has(key) {
  66700. return this.map.has(key);
  66701. }
  66702. get(key) {
  66703. const node = this.map.get(key);
  66704. if (node != null) {
  66705. this.deque.moveToTop(node);
  66706. return node.value;
  66707. }
  66708. return void 0;
  66709. }
  66710. set(key, value) {
  66711. const existingNode = this.map.get(key);
  66712. if (existingNode != null) {
  66713. existingNode.value = value;
  66714. this.deque.moveToTop(existingNode);
  66715. } else {
  66716. const newNode = this.deque.push(key, value);
  66717. this.map.set(key, newNode);
  66718. while (this.deque.length > this.capacity) {
  66719. const bottomNode = this.deque.deleteBottom();
  66720. this.map.delete(bottomNode.key);
  66721. }
  66722. }
  66723. }
  66724. *keys() {
  66725. let node = this.deque.head;
  66726. while (node != null) {
  66727. yield node.key;
  66728. node = node.next;
  66729. }
  66730. }
  66731. *entries() {
  66732. let node = this.deque.head;
  66733. while (node != null) {
  66734. yield [node.key, node.value];
  66735. node = node.next;
  66736. }
  66737. }
  66738. *values() {
  66739. let node = this.deque.head;
  66740. while (node != null) {
  66741. yield node.value;
  66742. node = node.next;
  66743. }
  66744. }
  66745. };
  66746. exports2.default = LRU;
  66747. }
  66748. });
  66749. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/consts.js
  66750. var require_consts = __commonJS({
  66751. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/consts.js"(exports2) {
  66752. "use strict";
  66753. Object.defineProperty(exports2, "__esModule", { value: true });
  66754. exports2.KNOWN_TYPENAMES = exports2.KNOWN_TYPES = exports2.INVALID_CODEC_ID = exports2.NULL_CODEC_ID = void 0;
  66755. exports2.NULL_CODEC_ID = "00000000000000000000000000000000";
  66756. exports2.INVALID_CODEC_ID = "ffffffffffffffffffffffffffffffff";
  66757. exports2.KNOWN_TYPES = /* @__PURE__ */ new Map([
  66758. ["00000000000000000000000000000001", "anytype"],
  66759. ["00000000000000000000000000000002", "anytuple"],
  66760. ["00000000000000000000000000000003", "anyobject"],
  66761. ["000000000000000000000000000000f0", "std"],
  66762. ["000000000000000000000000000000ff", "empty-tuple"],
  66763. ["00000000000000000000000000000100", "std::uuid"],
  66764. ["00000000000000000000000000000101", "std::str"],
  66765. ["00000000000000000000000000000102", "std::bytes"],
  66766. ["00000000000000000000000000000103", "std::int16"],
  66767. ["00000000000000000000000000000104", "std::int32"],
  66768. ["00000000000000000000000000000105", "std::int64"],
  66769. ["00000000000000000000000000000106", "std::float32"],
  66770. ["00000000000000000000000000000107", "std::float64"],
  66771. ["00000000000000000000000000000108", "std::decimal"],
  66772. ["00000000000000000000000000000109", "std::bool"],
  66773. ["0000000000000000000000000000010a", "std::datetime"],
  66774. ["0000000000000000000000000000010b", "cal::local_datetime"],
  66775. ["0000000000000000000000000000010c", "cal::local_date"],
  66776. ["0000000000000000000000000000010d", "cal::local_time"],
  66777. ["0000000000000000000000000000010e", "std::duration"],
  66778. ["0000000000000000000000000000010f", "std::json"],
  66779. ["00000000000000000000000000000110", "std::bigint"],
  66780. ["00000000000000000000000000000111", "cal::relative_duration"],
  66781. ["00000000000000000000000000000112", "cal::date_duration"],
  66782. ["00000000000000000000000000000130", "cfg::memory"],
  66783. ["00000000000000000000000001000001", "std::pg::json"],
  66784. ["00000000000000000000000001000002", "std::pg::timestamptz"],
  66785. ["00000000000000000000000001000003", "std::pg::timestamp"],
  66786. ["00000000000000000000000001000004", "std::pg::date"],
  66787. ["00000000000000000000000001000005", "std::pg::interval"],
  66788. ["9565dd8804f511eea6910b6ebe179825", "ext::pgvector::vector"],
  66789. ["4ba84534188e43b4a7cecea2af0f405b", "ext::pgvector::halfvec"],
  66790. ["003e434dcac2430ab238fb39d73447d2", "ext::pgvector::sparsevec"],
  66791. ["44c901c0d922489483c8061bd05e4840", "ext::postgis::geometry"],
  66792. ["4d7388783a5f4821ab769d8e7d6b32c4", "ext::postgis::geography"],
  66793. ["7fae553663114f608eb9096a5d972f48", "ext::postgis::box2d"],
  66794. ["c1a50ff8fded48b085c24905a8481433", "ext::postgis::box3d"]
  66795. ]);
  66796. exports2.KNOWN_TYPENAMES = (() => {
  66797. const res = /* @__PURE__ */ new Map();
  66798. for (const [id, name] of exports2.KNOWN_TYPES.entries()) {
  66799. res.set(name, id);
  66800. }
  66801. return res;
  66802. })();
  66803. }
  66804. });
  66805. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/ifaces.js
  66806. var require_ifaces = __commonJS({
  66807. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/ifaces.js"(exports2) {
  66808. "use strict";
  66809. Object.defineProperty(exports2, "__esModule", { value: true });
  66810. exports2.ScalarCodec = exports2.Codec = void 0;
  66811. var buffer_1 = require_buffer();
  66812. var consts_1 = require_consts();
  66813. var Codec = class {
  66814. tid;
  66815. tidBuffer;
  66816. constructor(tid) {
  66817. this.tid = tid;
  66818. this.tidBuffer = (0, buffer_1.uuidToBuffer)(tid);
  66819. }
  66820. getKnownTypeName() {
  66821. return "anytype";
  66822. }
  66823. };
  66824. exports2.Codec = Codec;
  66825. var ScalarCodec = class extends Codec {
  66826. typeName;
  66827. ancestors = null;
  66828. constructor(tid, typeName) {
  66829. super(tid);
  66830. this.typeName = typeName;
  66831. }
  66832. derive(tid, typeName, ancestors) {
  66833. const self2 = this.constructor;
  66834. const codec = new self2(tid, typeName);
  66835. codec.ancestors = ancestors;
  66836. return codec;
  66837. }
  66838. getSubcodecs() {
  66839. return [];
  66840. }
  66841. getKind() {
  66842. return "scalar";
  66843. }
  66844. tsType = "unknown";
  66845. tsModule = null;
  66846. getKnownTypeName() {
  66847. if (this.typeName) {
  66848. return this.typeName;
  66849. }
  66850. return consts_1.KNOWN_TYPES.get(this.tid) || "anytype";
  66851. }
  66852. };
  66853. exports2.ScalarCodec = ScalarCodec;
  66854. }
  66855. });
  66856. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/boolean.js
  66857. var require_boolean = __commonJS({
  66858. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/boolean.js"(exports2) {
  66859. "use strict";
  66860. Object.defineProperty(exports2, "__esModule", { value: true });
  66861. exports2.BoolCodec = void 0;
  66862. var ifaces_1 = require_ifaces();
  66863. var errors_1 = require_errors();
  66864. var BoolCodec = class extends ifaces_1.ScalarCodec {
  66865. tsType = "boolean";
  66866. encode(buf, object, ctx) {
  66867. const val2 = ctx.preEncode(this, object);
  66868. const typeOf = typeof val2;
  66869. if (typeOf !== "boolean" && typeOf !== "number") {
  66870. throw new errors_1.InvalidArgumentError(`a boolean or a number was expected, got "${val2}"`);
  66871. }
  66872. buf.writeInt32(1);
  66873. buf.writeChar(val2 ? 1 : 0);
  66874. }
  66875. decode(buf, ctx) {
  66876. return ctx.postDecode(this, buf.readUInt8() !== 0);
  66877. }
  66878. };
  66879. exports2.BoolCodec = BoolCodec;
  66880. }
  66881. });
  66882. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numbers.js
  66883. var require_numbers = __commonJS({
  66884. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numbers.js"(exports2) {
  66885. "use strict";
  66886. Object.defineProperty(exports2, "__esModule", { value: true });
  66887. exports2.Float64Codec = exports2.Float32Codec = exports2.Int16Codec = exports2.Int32Codec = exports2.Int64Codec = void 0;
  66888. var ifaces_1 = require_ifaces();
  66889. var errors_1 = require_errors();
  66890. var Int64Codec = class extends ifaces_1.ScalarCodec {
  66891. tsType = "number";
  66892. encode(buf, object, ctx) {
  66893. if (ctx.hasOverload(this)) {
  66894. const val2 = ctx.preEncode(this, object);
  66895. buf.writeInt32(8);
  66896. buf.writeBigInt64(val2);
  66897. return;
  66898. }
  66899. if (typeof object !== "number") {
  66900. throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
  66901. }
  66902. buf.writeInt32(8);
  66903. buf.writeInt64(object);
  66904. }
  66905. decode(buf, ctx) {
  66906. if (ctx.hasOverload(this)) {
  66907. return ctx.postDecode(this, buf.readBigInt64());
  66908. }
  66909. return buf.readInt64();
  66910. }
  66911. };
  66912. exports2.Int64Codec = Int64Codec;
  66913. var Int32Codec = class extends ifaces_1.ScalarCodec {
  66914. tsType = "number";
  66915. encode(buf, object, ctx) {
  66916. object = ctx.preEncode(this, object);
  66917. if (typeof object !== "number") {
  66918. throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
  66919. }
  66920. buf.writeInt32(4);
  66921. buf.writeInt32(object);
  66922. }
  66923. decode(buf, ctx) {
  66924. return ctx.postDecode(this, buf.readInt32());
  66925. }
  66926. };
  66927. exports2.Int32Codec = Int32Codec;
  66928. var Int16Codec = class extends ifaces_1.ScalarCodec {
  66929. tsType = "number";
  66930. encode(buf, object, ctx) {
  66931. object = ctx.preEncode(this, object);
  66932. if (typeof object !== "number") {
  66933. throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
  66934. }
  66935. buf.writeInt32(2);
  66936. buf.writeInt16(object);
  66937. }
  66938. decode(buf, ctx) {
  66939. return ctx.postDecode(this, buf.readInt16());
  66940. }
  66941. };
  66942. exports2.Int16Codec = Int16Codec;
  66943. var Float32Codec = class extends ifaces_1.ScalarCodec {
  66944. tsType = "number";
  66945. encode(buf, object, ctx) {
  66946. object = ctx.preEncode(this, object);
  66947. if (typeof object !== "number") {
  66948. throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
  66949. }
  66950. buf.writeInt32(4);
  66951. buf.writeFloat32(object);
  66952. }
  66953. decode(buf, ctx) {
  66954. return ctx.postDecode(this, buf.readFloat32());
  66955. }
  66956. };
  66957. exports2.Float32Codec = Float32Codec;
  66958. var Float64Codec = class extends ifaces_1.ScalarCodec {
  66959. tsType = "number";
  66960. encode(buf, object, ctx) {
  66961. object = ctx.preEncode(this, object);
  66962. if (typeof object !== "number") {
  66963. throw new errors_1.InvalidArgumentError(`a number was expected, got "${object}"`);
  66964. }
  66965. buf.writeInt32(8);
  66966. buf.writeFloat64(object);
  66967. }
  66968. decode(buf, ctx) {
  66969. return ctx.postDecode(this, buf.readFloat64());
  66970. }
  66971. };
  66972. exports2.Float64Codec = Float64Codec;
  66973. }
  66974. });
  66975. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numerics.js
  66976. var require_numerics = __commonJS({
  66977. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/numerics.js"(exports2) {
  66978. "use strict";
  66979. Object.defineProperty(exports2, "__esModule", { value: true });
  66980. exports2.DecimalStringCodec = exports2.BigIntCodec = void 0;
  66981. var ifaces_1 = require_ifaces();
  66982. var errors_1 = require_errors();
  66983. var NUMERIC_POS = 0;
  66984. var NUMERIC_NEG = 16384;
  66985. var BigIntCodec = class extends ifaces_1.ScalarCodec {
  66986. tsType = "bigint";
  66987. encode(buf, object, ctx) {
  66988. object = ctx.preEncode(this, object);
  66989. if (typeof object !== "bigint") {
  66990. throw new errors_1.InvalidArgumentError(`a bigint was expected, got "${object}"`);
  66991. }
  66992. const digits = [];
  66993. let sign = NUMERIC_POS;
  66994. let uval = object;
  66995. if (object === 0n) {
  66996. buf.writeUInt32(8);
  66997. buf.writeUInt32(0);
  66998. buf.writeUInt16(NUMERIC_POS);
  66999. buf.writeUInt16(0);
  67000. return;
  67001. }
  67002. if (object < 0n) {
  67003. sign = NUMERIC_NEG;
  67004. uval = -uval;
  67005. }
  67006. while (uval) {
  67007. const mod = uval % 10000n;
  67008. uval /= 10000n;
  67009. digits.push(mod);
  67010. }
  67011. buf.writeUInt32(8 + digits.length * 2);
  67012. buf.writeUInt16(digits.length);
  67013. buf.writeUInt16(digits.length - 1);
  67014. buf.writeUInt16(sign);
  67015. buf.writeUInt16(0);
  67016. for (let i4 = digits.length - 1; i4 >= 0; i4--) {
  67017. buf.writeUInt16(Number(digits[i4]));
  67018. }
  67019. }
  67020. decode(buf, ctx) {
  67021. const val2 = BigInt(decodeBigIntToString(buf));
  67022. return ctx.postDecode(this, val2);
  67023. }
  67024. };
  67025. exports2.BigIntCodec = BigIntCodec;
  67026. var DecimalStringCodec = class extends ifaces_1.ScalarCodec {
  67027. tsType = "string";
  67028. encode(buf, object, ctx) {
  67029. object = ctx.preEncode(this, object);
  67030. if (typeof object !== "string") {
  67031. throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
  67032. }
  67033. const match2 = object.match(/^(-?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([-+]?[0-9]+))?$/);
  67034. if (!match2) {
  67035. throw new errors_1.InvalidArgumentError(`invalid decimal string "${object}"`);
  67036. }
  67037. const [_3, sign, int, _frac, _exp] = match2;
  67038. const frac = _frac ?? "";
  67039. const exp = _exp ? parseInt(_exp, 10) : 0;
  67040. const sdigits = int.padStart(Math.ceil(int.length / 4) * 4, "0") + frac.padEnd(Math.ceil(frac.length / 4) * 4, "0");
  67041. const digits = [];
  67042. for (let i4 = 0, len = sdigits.length; i4 < len; i4 += 4) {
  67043. digits.push(parseInt(sdigits.slice(i4, i4 + 4), 10));
  67044. }
  67045. buf.writeUInt32(8 + digits.length * 2);
  67046. buf.writeUInt16(digits.length);
  67047. buf.writeInt16(Math.ceil((int.length + exp) / 4) - 1);
  67048. buf.writeUInt16(sign === "-" ? NUMERIC_NEG : NUMERIC_POS);
  67049. buf.writeUInt16(Math.max(frac.length - exp, 0));
  67050. for (let i4 = 0, len = digits.length; i4 < len; i4++) {
  67051. buf.writeUInt16(digits[i4]);
  67052. }
  67053. }
  67054. decode(buf, ctx) {
  67055. if (ctx.hasOverload(this)) {
  67056. return ctx.postDecode(this, decodeDecimalToString(buf));
  67057. }
  67058. return decodeDecimalToString(buf);
  67059. }
  67060. };
  67061. exports2.DecimalStringCodec = DecimalStringCodec;
  67062. function decodeBigIntToString(buf) {
  67063. const ndigits = buf.readUInt16();
  67064. const weight = buf.readInt16();
  67065. const sign = buf.readUInt16();
  67066. const dscale = buf.readUInt16();
  67067. let result = "";
  67068. switch (sign) {
  67069. case NUMERIC_POS:
  67070. break;
  67071. case NUMERIC_NEG:
  67072. result += "-";
  67073. break;
  67074. default:
  67075. throw new errors_1.ProtocolError("bad bigint sign data");
  67076. }
  67077. if (dscale !== 0) {
  67078. throw new errors_1.ProtocolError("bigint data has fractional part");
  67079. }
  67080. if (ndigits === 0) {
  67081. return "0";
  67082. }
  67083. let i4 = weight;
  67084. let d3 = 0;
  67085. while (i4 >= 0) {
  67086. if (i4 <= weight && d3 < ndigits) {
  67087. const digit = buf.readUInt16().toString();
  67088. result += d3 > 0 ? digit.padStart(4, "0") : digit;
  67089. d3++;
  67090. } else {
  67091. result += "0000";
  67092. }
  67093. i4--;
  67094. }
  67095. return result;
  67096. }
  67097. function decodeDecimalToString(buf) {
  67098. const ndigits = buf.readUInt16();
  67099. const weight = buf.readInt16();
  67100. const sign = buf.readUInt16();
  67101. const dscale = buf.readUInt16();
  67102. let result = "";
  67103. switch (sign) {
  67104. case NUMERIC_POS:
  67105. break;
  67106. case NUMERIC_NEG:
  67107. result += "-";
  67108. break;
  67109. default:
  67110. throw new errors_1.ProtocolError("bad decimal sign data");
  67111. }
  67112. let d3 = 0;
  67113. if (weight < 0) {
  67114. d3 = weight + 1;
  67115. result += "0";
  67116. } else {
  67117. for (d3 = 0; d3 <= weight; d3++) {
  67118. const digit = d3 < ndigits ? buf.readUInt16() : 0;
  67119. let sdigit = digit.toString();
  67120. if (d3 > 0) {
  67121. sdigit = sdigit.padStart(4, "0");
  67122. }
  67123. result += sdigit;
  67124. }
  67125. }
  67126. if (dscale > 0) {
  67127. result += ".";
  67128. const end = result.length + dscale;
  67129. for (let i4 = 0; i4 < dscale; d3++, i4 += 4) {
  67130. const digit = d3 >= 0 && d3 < ndigits ? buf.readUInt16() : 0;
  67131. result += digit.toString().padStart(4, "0");
  67132. }
  67133. result = result.slice(0, end);
  67134. }
  67135. return result;
  67136. }
  67137. }
  67138. });
  67139. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/text.js
  67140. var require_text = __commonJS({
  67141. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/text.js"(exports2) {
  67142. "use strict";
  67143. Object.defineProperty(exports2, "__esModule", { value: true });
  67144. exports2.StrCodec = void 0;
  67145. var buffer_1 = require_buffer();
  67146. var ifaces_1 = require_ifaces();
  67147. var errors_1 = require_errors();
  67148. var StrCodec = class extends ifaces_1.ScalarCodec {
  67149. tsType = "string";
  67150. encode(buf, object, ctx) {
  67151. object = ctx.preEncode(this, object);
  67152. if (typeof object !== "string") {
  67153. throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
  67154. }
  67155. const val2 = object;
  67156. const strbuf = buffer_1.utf8Encoder.encode(val2);
  67157. buf.writeInt32(strbuf.length);
  67158. buf.writeBuffer(strbuf);
  67159. }
  67160. decode(buf, ctx) {
  67161. return ctx.postDecode(this, buf.consumeAsString());
  67162. }
  67163. };
  67164. exports2.StrCodec = StrCodec;
  67165. }
  67166. });
  67167. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/uuid.js
  67168. var require_uuid = __commonJS({
  67169. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/uuid.js"(exports2) {
  67170. "use strict";
  67171. Object.defineProperty(exports2, "__esModule", { value: true });
  67172. exports2.UUIDCodec = void 0;
  67173. var buffer_1 = require_buffer();
  67174. var ifaces_1 = require_ifaces();
  67175. var errors_1 = require_errors();
  67176. function UUIDBufferFromString(uuid) {
  67177. let uuidClean = uuid;
  67178. if (uuidClean.length !== 32) {
  67179. uuidClean = uuidClean.replace(/-/g, "");
  67180. if (uuidClean.length !== 32) {
  67181. throw new TypeError(`invalid UUID "${uuid}"`);
  67182. }
  67183. }
  67184. try {
  67185. return (0, buffer_1.uuidToBuffer)(uuidClean);
  67186. } catch {
  67187. throw new TypeError(`invalid UUID "${uuid}"`);
  67188. }
  67189. }
  67190. var UUIDCodec = class extends ifaces_1.ScalarCodec {
  67191. tsType = "string";
  67192. encode(buf, object, ctx) {
  67193. if (ctx.hasOverload(this)) {
  67194. const val2 = ctx.preEncode(this, object);
  67195. if (!(val2 instanceof Uint8Array)) {
  67196. throw new errors_1.InvalidArgumentError(`a Uint8Array was expected from a custom UUID codec`);
  67197. }
  67198. if (val2.length != 16) {
  67199. throw new errors_1.InvalidArgumentError(`a 16-element long Uint8Array was expected from a custom UUID codec`);
  67200. }
  67201. buf.writeInt32(16);
  67202. buf.writeBuffer(val2);
  67203. return;
  67204. }
  67205. if (typeof object === "string") {
  67206. const ubuf = UUIDBufferFromString(object);
  67207. buf.writeInt32(16);
  67208. buf.writeBuffer(ubuf);
  67209. } else {
  67210. throw new errors_1.InvalidArgumentError(`cannot encode UUID "${object}": invalid type`);
  67211. }
  67212. }
  67213. decode(buf, ctx) {
  67214. if (ctx.hasOverload(this)) {
  67215. return ctx.postDecode(this, buf.readUUIDBytes());
  67216. }
  67217. return buf.readUUID("-");
  67218. }
  67219. };
  67220. exports2.UUIDCodec = UUIDCodec;
  67221. }
  67222. });
  67223. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/bytes.js
  67224. var require_bytes = __commonJS({
  67225. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/bytes.js"(exports2) {
  67226. "use strict";
  67227. Object.defineProperty(exports2, "__esModule", { value: true });
  67228. exports2.BytesCodec = void 0;
  67229. var ifaces_1 = require_ifaces();
  67230. var errors_1 = require_errors();
  67231. var BytesCodec = class extends ifaces_1.ScalarCodec {
  67232. tsType = "Uint8Array";
  67233. encode(buf, object, ctx) {
  67234. const val2 = ctx.preEncode(this, object);
  67235. if (!(val2 instanceof Uint8Array)) {
  67236. throw new errors_1.InvalidArgumentError(`a Uint8Array or Buffer was expected, got "${val2}"`);
  67237. }
  67238. buf.writeInt32(val2.length);
  67239. buf.writeBuffer(val2);
  67240. }
  67241. decode(buf, ctx) {
  67242. return ctx.postDecode(this, buf.consumeAsBuffer());
  67243. }
  67244. };
  67245. exports2.BytesCodec = BytesCodec;
  67246. }
  67247. });
  67248. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/json.js
  67249. var require_json = __commonJS({
  67250. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/json.js"(exports2) {
  67251. "use strict";
  67252. Object.defineProperty(exports2, "__esModule", { value: true });
  67253. exports2.PgTextJSONStringCodec = exports2.PgTextJSONCodec = exports2.JSONCodec = void 0;
  67254. var buffer_1 = require_buffer();
  67255. var ifaces_1 = require_ifaces();
  67256. var errors_1 = require_errors();
  67257. var JSONCodec = class extends ifaces_1.ScalarCodec {
  67258. tsType = "unknown";
  67259. jsonFormat = 1;
  67260. encode(buf, object, ctx) {
  67261. let val2;
  67262. if (ctx.hasOverload(this)) {
  67263. val2 = ctx.preEncode(this, object);
  67264. } else {
  67265. try {
  67266. val2 = JSON.stringify(object);
  67267. } catch (_err) {
  67268. throw new errors_1.InvalidArgumentError(`a JSON-serializable value was expected, got "${object}"`);
  67269. }
  67270. }
  67271. if (typeof val2 !== "string") {
  67272. throw new errors_1.InvalidArgumentError(`a JSON-serializable value was expected, got "${object}"`);
  67273. }
  67274. const strbuf = buffer_1.utf8Encoder.encode(val2);
  67275. if (this.jsonFormat !== null) {
  67276. buf.writeInt32(strbuf.length + 1);
  67277. buf.writeChar(this.jsonFormat);
  67278. } else {
  67279. buf.writeInt32(strbuf.length);
  67280. }
  67281. buf.writeBuffer(strbuf);
  67282. }
  67283. decode(buf, ctx) {
  67284. if (this.jsonFormat !== null) {
  67285. const format = buf.readUInt8();
  67286. if (format !== this.jsonFormat) {
  67287. throw new errors_1.ProtocolError(`unexpected JSON format ${format}`);
  67288. }
  67289. }
  67290. if (ctx.hasOverload(this)) {
  67291. return ctx.postDecode(this, buf.consumeAsString());
  67292. } else {
  67293. return JSON.parse(buf.consumeAsString());
  67294. }
  67295. }
  67296. };
  67297. exports2.JSONCodec = JSONCodec;
  67298. var PgTextJSONCodec = class extends JSONCodec {
  67299. jsonFormat = null;
  67300. };
  67301. exports2.PgTextJSONCodec = PgTextJSONCodec;
  67302. var PgTextJSONStringCodec = class extends ifaces_1.ScalarCodec {
  67303. encode(buf, object, ctx) {
  67304. if (ctx.hasOverload(this)) {
  67305. object = ctx.preEncode(this, object);
  67306. }
  67307. if (typeof object !== "string") {
  67308. throw new errors_1.InvalidArgumentError(`a string was expected, got "${object}"`);
  67309. }
  67310. const strbuf = buffer_1.utf8Encoder.encode(object);
  67311. buf.writeInt32(strbuf.length);
  67312. buf.writeBuffer(strbuf);
  67313. }
  67314. decode(buf, ctx) {
  67315. return ctx.postDecode(this, buf.consumeAsString());
  67316. }
  67317. };
  67318. exports2.PgTextJSONStringCodec = PgTextJSONStringCodec;
  67319. }
  67320. });
  67321. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/dateutil.js
  67322. var require_dateutil = __commonJS({
  67323. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/dateutil.js"(exports2) {
  67324. "use strict";
  67325. Object.defineProperty(exports2, "__esModule", { value: true });
  67326. exports2.isLeapYear = isLeapYear2;
  67327. exports2.daysInMonth = daysInMonth;
  67328. exports2.daysBeforeMonth = daysBeforeMonth;
  67329. exports2.ymd2ord = ymd2ord;
  67330. exports2.ord2ymd = ord2ymd;
  67331. function isLeapYear2(year) {
  67332. return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
  67333. }
  67334. function daysInMonth(year, month) {
  67335. if (month === 2 && isLeapYear2(year)) {
  67336. return 29;
  67337. }
  67338. return _DAYS_IN_MONTH[month];
  67339. }
  67340. function daysBeforeYear(year) {
  67341. const y2 = year - 1;
  67342. return y2 * 365 + Math.trunc(y2 / 4) - Math.trunc(y2 / 100) + Math.trunc(y2 / 400);
  67343. }
  67344. function daysBeforeMonth(year, month) {
  67345. return _DAYS_BEFORE_MONTH[month] + (month > 2 && isLeapYear2(year) ? 1 : 0);
  67346. }
  67347. var _DI400Y = daysBeforeYear(401);
  67348. var _DI100Y = daysBeforeYear(101);
  67349. var _DI4Y = daysBeforeYear(5);
  67350. var _DAYS_IN_MONTH = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  67351. var _DAYS_BEFORE_MONTH = (() => {
  67352. const dbf = [-1];
  67353. let dbm = 0;
  67354. for (let i4 = 1; i4 < _DAYS_IN_MONTH.length; i4++) {
  67355. const dim = _DAYS_IN_MONTH[i4];
  67356. dbf.push(dbm);
  67357. dbm += dim;
  67358. }
  67359. return dbf;
  67360. })();
  67361. function ymd2ord(year, month, day) {
  67362. return daysBeforeYear(year) + daysBeforeMonth(year, month) + day;
  67363. }
  67364. function divmod(dividend, divisor) {
  67365. const quotient = Math.floor(dividend / divisor);
  67366. return [quotient, dividend - divisor * quotient];
  67367. }
  67368. function ord2ymd(n3) {
  67369. n3--;
  67370. let n400;
  67371. [n400, n3] = divmod(n3, _DI400Y);
  67372. let year = n400 * 400 + 1;
  67373. let n100;
  67374. [n100, n3] = divmod(n3, _DI100Y);
  67375. let n4;
  67376. [n4, n3] = divmod(n3, _DI4Y);
  67377. let n1;
  67378. [n1, n3] = divmod(n3, 365);
  67379. year += n100 * 100 + n4 * 4 + n1;
  67380. if (n1 === 4 || n100 === 4) {
  67381. return [year - 1, 12, 31];
  67382. }
  67383. const leapyear = n1 === 3 && (n4 !== 24 || n100 === 3);
  67384. let month = n3 + 50 >> 5;
  67385. let preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 && leapyear ? 1 : 0);
  67386. if (preceding > n3) {
  67387. month -= 1;
  67388. preceding -= _DAYS_IN_MONTH[month] + (month === 2 && leapyear ? 1 : 0);
  67389. }
  67390. n3 -= preceding;
  67391. return [year, month, n3 + 1];
  67392. }
  67393. }
  67394. });
  67395. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/datetime.js
  67396. var require_datetime = __commonJS({
  67397. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/datetime.js"(exports2) {
  67398. "use strict";
  67399. Object.defineProperty(exports2, "__esModule", { value: true });
  67400. exports2.DateDuration = exports2.RelativeDuration = exports2.Duration = exports2.LocalDateTime = exports2.LocalDate = exports2.localDateInstances = exports2.LocalTime = exports2.localTimeInstances = exports2.DATE_PRIVATE = void 0;
  67401. exports2.LocalDateToOrdinal = LocalDateToOrdinal;
  67402. exports2.LocalDateFromOrdinal = LocalDateFromOrdinal;
  67403. exports2.parseHumanDurationString = parseHumanDurationString;
  67404. var dateutil_1 = require_dateutil();
  67405. exports2.DATE_PRIVATE = Symbol.for("gel.datetime");
  67406. function toNumber(val2) {
  67407. const n3 = Number(val2);
  67408. if (Number.isNaN(n3)) {
  67409. return 0;
  67410. }
  67411. return n3;
  67412. }
  67413. function assertInteger(val2) {
  67414. if (!Number.isInteger(val2)) {
  67415. throw new RangeError(`unsupported fractional value ${val2}`);
  67416. }
  67417. return val2;
  67418. }
  67419. exports2.localTimeInstances = /* @__PURE__ */ new WeakMap();
  67420. var LocalTime = class {
  67421. hour;
  67422. minute;
  67423. second;
  67424. millisecond;
  67425. microsecond;
  67426. nanosecond;
  67427. constructor(isoHour = 0, isoMinute = 0, isoSecond = 0, isoMillisecond = 0, isoMicrosecond = 0, isoNanosecond = 0) {
  67428. isoHour = Math.floor(toNumber(isoHour));
  67429. isoMinute = Math.floor(toNumber(isoMinute));
  67430. isoSecond = Math.floor(toNumber(isoSecond));
  67431. isoMillisecond = Math.floor(toNumber(isoMillisecond));
  67432. isoMicrosecond = Math.floor(toNumber(isoMicrosecond));
  67433. isoNanosecond = Math.floor(toNumber(isoNanosecond));
  67434. if (isoHour < 0 || isoHour > 23) {
  67435. throw new RangeError(`invalid number of hours ${isoHour}: expected a value in 0-23 range`);
  67436. }
  67437. if (isoMinute < 0 || isoMinute > 59) {
  67438. throw new RangeError(`invalid number of minutes ${isoMinute}: expected a value in 0-59 range`);
  67439. }
  67440. if (isoSecond < 0 || isoSecond > 59) {
  67441. throw new RangeError(`invalid number of seconds ${isoSecond}: expected a value in 0-59 range`);
  67442. }
  67443. if (isoMillisecond < 0 || isoMillisecond > 999) {
  67444. throw new RangeError(`invalid number of milliseconds ${isoMillisecond}: expected a value in 0-999 range`);
  67445. }
  67446. if (isoMicrosecond < 0 || isoMicrosecond > 999) {
  67447. throw new RangeError(`invalid number of microseconds ${isoMicrosecond}: expected a value in 0-999 range`);
  67448. }
  67449. if (isoNanosecond < 0 || isoNanosecond > 999) {
  67450. throw new RangeError(`invalid number of nanoseconds ${isoNanosecond}: expected a value in 0-999 range`);
  67451. }
  67452. this.hour = isoHour;
  67453. this.minute = isoMinute;
  67454. this.second = isoSecond;
  67455. this.millisecond = isoMillisecond;
  67456. this.microsecond = isoMicrosecond;
  67457. this.nanosecond = isoNanosecond;
  67458. forwardJsonAsToString(this);
  67459. throwOnValueOf(this, "LocalTime");
  67460. }
  67461. toString() {
  67462. const hh = this.hour.toString().padStart(2, "0");
  67463. const mm = this.minute.toString().padStart(2, "0");
  67464. const ss = this.second.toString().padStart(2, "0");
  67465. let repr = `${hh}:${mm}:${ss}`;
  67466. if (this.millisecond || this.microsecond || this.nanosecond) {
  67467. repr += `.${this.millisecond.toString().padStart(3, "0")}${this.microsecond.toString().padStart(3, "0")}${this.nanosecond.toString().padStart(3, "0")}`.replace(/(?:0+)$/, "");
  67468. }
  67469. return repr;
  67470. }
  67471. };
  67472. exports2.LocalTime = LocalTime;
  67473. exports2.localDateInstances = /* @__PURE__ */ new WeakMap();
  67474. var LocalDate = class {
  67475. constructor(isoYear, isoMonth, isoDay) {
  67476. isoYear = Math.trunc(toNumber(isoYear));
  67477. isoMonth = Math.floor(toNumber(isoMonth));
  67478. isoDay = Math.floor(toNumber(isoDay));
  67479. if (isoYear < -271820 || isoYear > 275759) {
  67480. throw new RangeError(`invalid year ${isoYear}: expected a value in -271820-275759 range`);
  67481. }
  67482. if (isoMonth < 1 || isoMonth > 12) {
  67483. throw new RangeError(`invalid month ${isoMonth}: expected a value in 1-12 range`);
  67484. }
  67485. const maxDays = (0, dateutil_1.daysInMonth)(isoYear, isoMonth);
  67486. if (isoDay < 1 || isoDay > maxDays) {
  67487. throw new RangeError(`invalid number of days ${isoDay}: expected a value in 1-${maxDays} range`);
  67488. }
  67489. const date = new Date(Date.UTC(isoYear, isoMonth - 1, isoDay));
  67490. if (isoYear >= 0 && isoYear <= 99) {
  67491. date.setUTCFullYear(isoYear);
  67492. }
  67493. exports2.localDateInstances.set(this, date);
  67494. forwardJsonAsToString(this);
  67495. throwOnValueOf(this, "LocalDate");
  67496. }
  67497. get year() {
  67498. return exports2.localDateInstances.get(this).getUTCFullYear();
  67499. }
  67500. get month() {
  67501. return exports2.localDateInstances.get(this).getUTCMonth() + 1;
  67502. }
  67503. get day() {
  67504. return exports2.localDateInstances.get(this).getUTCDate();
  67505. }
  67506. get dayOfWeek() {
  67507. return (exports2.localDateInstances.get(this).getUTCDay() + 6) % 7 + 1;
  67508. }
  67509. get dayOfYear() {
  67510. const date = exports2.localDateInstances.get(this);
  67511. return (0, dateutil_1.daysBeforeMonth)(date.getUTCFullYear(), date.getUTCMonth() + 1) + date.getUTCDate();
  67512. }
  67513. get daysInWeek() {
  67514. return 7;
  67515. }
  67516. get daysInMonth() {
  67517. const date = exports2.localDateInstances.get(this);
  67518. return (0, dateutil_1.daysInMonth)(date.getUTCFullYear(), date.getUTCMonth() + 1);
  67519. }
  67520. get daysInYear() {
  67521. return this.inLeapYear ? 366 : 365;
  67522. }
  67523. get monthsInYear() {
  67524. return 12;
  67525. }
  67526. get inLeapYear() {
  67527. return (0, dateutil_1.isLeapYear)(exports2.localDateInstances.get(this).getUTCFullYear());
  67528. }
  67529. toString() {
  67530. const year = this.year < 0 || this.year > 9999 ? (this.year < 0 ? "-" : "+") + Math.abs(this.year).toString().padStart(6, "0") : this.year.toString().padStart(4, "0");
  67531. const month = this.month.toString().padStart(2, "0");
  67532. const day = this.day.toString().padStart(2, "0");
  67533. return `${year}-${month}-${day}`;
  67534. }
  67535. };
  67536. exports2.LocalDate = LocalDate;
  67537. function LocalDateToOrdinal(localdate) {
  67538. return (0, dateutil_1.ymd2ord)(localdate.year, localdate.month, localdate.day);
  67539. }
  67540. function LocalDateFromOrdinal(ordinal) {
  67541. const [year, month, day] = (0, dateutil_1.ord2ymd)(ordinal);
  67542. return new LocalDate(year, month, day);
  67543. }
  67544. var LocalDateTime = class extends LocalDate {
  67545. constructor(isoYear, isoMonth, isoDay, isoHour = 0, isoMinute = 0, isoSecond = 0, isoMillisecond = 0, isoMicrosecond = 0, isoNanosecond = 0) {
  67546. super(isoYear, isoMonth, isoDay);
  67547. const time = new LocalTime(isoHour, isoMinute, isoSecond, isoMillisecond, isoMicrosecond, isoNanosecond);
  67548. exports2.localTimeInstances.set(this, time);
  67549. throwOnValueOf(this, "LocalDateTime");
  67550. }
  67551. get hour() {
  67552. return exports2.localTimeInstances.get(this).hour;
  67553. }
  67554. get minute() {
  67555. return exports2.localTimeInstances.get(this).minute;
  67556. }
  67557. get second() {
  67558. return exports2.localTimeInstances.get(this).second;
  67559. }
  67560. get millisecond() {
  67561. return exports2.localTimeInstances.get(this).millisecond;
  67562. }
  67563. get microsecond() {
  67564. return exports2.localTimeInstances.get(this).microsecond;
  67565. }
  67566. get nanosecond() {
  67567. return exports2.localTimeInstances.get(this).nanosecond;
  67568. }
  67569. toString() {
  67570. return `${super.toString()}T${exports2.localTimeInstances.get(this).toString()}`;
  67571. }
  67572. };
  67573. exports2.LocalDateTime = LocalDateTime;
  67574. var durationRegex2 = new RegExp(`^(\\-|\\+)?P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)W)?(?:(\\d+)D)?(T(?:(\\d+)(\\.\\d{1,10})?H)?(?:(\\d+)(\\.\\d{1,10})?M)?(?:(\\d+)(\\.\\d{1,9})?S)?)?$`, "i");
  67575. var Duration = class _Duration {
  67576. years;
  67577. months;
  67578. weeks;
  67579. days;
  67580. hours;
  67581. minutes;
  67582. seconds;
  67583. milliseconds;
  67584. microseconds;
  67585. nanoseconds;
  67586. sign;
  67587. constructor(years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0, microseconds = 0, nanoseconds = 0) {
  67588. years = assertInteger(toNumber(years));
  67589. months = assertInteger(toNumber(months));
  67590. weeks = assertInteger(toNumber(weeks));
  67591. days = assertInteger(toNumber(days));
  67592. hours = assertInteger(toNumber(hours));
  67593. minutes = assertInteger(toNumber(minutes));
  67594. seconds = assertInteger(toNumber(seconds));
  67595. milliseconds = assertInteger(toNumber(milliseconds));
  67596. microseconds = assertInteger(toNumber(microseconds));
  67597. nanoseconds = assertInteger(toNumber(nanoseconds));
  67598. const fields = [
  67599. years,
  67600. months,
  67601. weeks,
  67602. days,
  67603. hours,
  67604. minutes,
  67605. seconds,
  67606. milliseconds,
  67607. microseconds,
  67608. nanoseconds
  67609. ];
  67610. let sign = 0;
  67611. for (const field of fields) {
  67612. if (field === Infinity || field === -Infinity) {
  67613. throw new RangeError("infinite values not allowed as duration fields");
  67614. }
  67615. const fieldSign = Math.sign(field);
  67616. if (sign && fieldSign && fieldSign !== sign) {
  67617. throw new RangeError("mixed-sign values not allowed as duration fields");
  67618. }
  67619. sign = sign || fieldSign;
  67620. }
  67621. this.years = years || 0;
  67622. this.months = months || 0;
  67623. this.weeks = weeks || 0;
  67624. this.days = days || 0;
  67625. this.hours = hours || 0;
  67626. this.minutes = minutes || 0;
  67627. this.seconds = seconds || 0;
  67628. this.milliseconds = milliseconds || 0;
  67629. this.microseconds = microseconds || 0;
  67630. this.nanoseconds = nanoseconds || 0;
  67631. this.sign = sign || 0;
  67632. forwardJsonAsToString(this);
  67633. throwOnValueOf(this, "TemporalDuration");
  67634. }
  67635. get blank() {
  67636. return this.sign === 0;
  67637. }
  67638. toString() {
  67639. let dateParts = "";
  67640. if (this.years) {
  67641. dateParts += BigInt(Math.abs(this.years)) + "Y";
  67642. }
  67643. if (this.months) {
  67644. dateParts += BigInt(Math.abs(this.months)) + "M";
  67645. }
  67646. if (this.weeks) {
  67647. dateParts += BigInt(Math.abs(this.weeks)) + "W";
  67648. }
  67649. if (this.days) {
  67650. dateParts += BigInt(Math.abs(this.days)) + "D";
  67651. }
  67652. let timeParts = "";
  67653. if (this.hours) {
  67654. timeParts += BigInt(Math.abs(this.hours)) + "H";
  67655. }
  67656. if (this.minutes) {
  67657. timeParts += BigInt(Math.abs(this.minutes)) + "M";
  67658. }
  67659. if (!dateParts && !timeParts || this.seconds || this.milliseconds || this.microseconds || this.nanoseconds) {
  67660. const totalNanoseconds = (BigInt(Math.abs(this.seconds)) * BigInt(1e9) + BigInt(Math.abs(this.milliseconds)) * BigInt(1e6) + BigInt(Math.abs(this.microseconds)) * BigInt(1e3) + BigInt(Math.abs(this.nanoseconds))).toString().padStart(10, "0");
  67661. const seconds = totalNanoseconds.slice(0, -9);
  67662. const fracSeconds = totalNanoseconds.slice(-9).replace(/0+$/, "");
  67663. timeParts += seconds + (fracSeconds.length ? "." + fracSeconds : "") + "S";
  67664. }
  67665. return (this.sign === -1 ? "-" : "") + "P" + dateParts + (timeParts ? "T" + timeParts : "");
  67666. }
  67667. static from(item) {
  67668. let result;
  67669. if (item instanceof _Duration) {
  67670. result = item;
  67671. }
  67672. if (typeof item === "object") {
  67673. if (item.years === void 0 && item.months === void 0 && item.weeks === void 0 && item.days === void 0 && item.hours === void 0 && item.minutes === void 0 && item.seconds === void 0 && item.milliseconds === void 0 && item.microseconds === void 0 && item.nanoseconds === void 0) {
  67674. throw new TypeError(`invalid duration-like`);
  67675. }
  67676. result = item;
  67677. } else {
  67678. const str = String(item);
  67679. const matches = str.match(durationRegex2);
  67680. if (!matches) {
  67681. throw new RangeError(`invalid duration: ${str}`);
  67682. }
  67683. const [_duration, _sign, years, months, weeks, days, _time, hours, fHours, minutes, fMinutes, seconds, fSeconds] = matches;
  67684. if (_duration.length < 3 || _time.length === 1) {
  67685. throw new RangeError(`invalid duration: ${str}`);
  67686. }
  67687. const sign = _sign === "-" ? -1 : 1;
  67688. result = {};
  67689. if (years) {
  67690. result.years = sign * Number(years);
  67691. }
  67692. if (months) {
  67693. result.months = sign * Number(months);
  67694. }
  67695. if (weeks) {
  67696. result.weeks = sign * Number(weeks);
  67697. }
  67698. if (days) {
  67699. result.days = sign * Number(days);
  67700. }
  67701. if (hours) {
  67702. result.hours = sign * Number(hours);
  67703. }
  67704. if (fHours) {
  67705. if (minutes || fMinutes || seconds || fSeconds) {
  67706. throw new RangeError("only the smallest unit can be fractional");
  67707. }
  67708. result.minutes = Number(fHours) * 60;
  67709. } else {
  67710. result.minutes = toNumber(minutes);
  67711. }
  67712. if (fMinutes) {
  67713. if (seconds || fSeconds) {
  67714. throw new RangeError("only the smallest unit can be fractional");
  67715. }
  67716. result.seconds = Number(fMinutes) * 60;
  67717. } else if (seconds) {
  67718. result.seconds = Number(seconds);
  67719. } else {
  67720. result.seconds = result.minutes % 1 * 60;
  67721. }
  67722. if (fSeconds) {
  67723. const ns = fSeconds.slice(1).padEnd(9, "0");
  67724. result.milliseconds = Number(ns.slice(0, 3));
  67725. result.microseconds = Number(ns.slice(3, 6));
  67726. result.nanoseconds = sign * Number(ns.slice(6));
  67727. } else {
  67728. result.milliseconds = result.seconds % 1 * 1e3;
  67729. result.microseconds = result.milliseconds % 1 * 1e3;
  67730. result.nanoseconds = sign * Math.floor(result.microseconds % 1 * 1e3);
  67731. }
  67732. result.minutes = sign * Math.floor(result.minutes);
  67733. result.seconds = sign * Math.floor(result.seconds);
  67734. result.milliseconds = sign * Math.floor(result.milliseconds);
  67735. result.microseconds = sign * Math.floor(result.microseconds);
  67736. }
  67737. return new _Duration(result.years, result.months, result.weeks, result.days, result.hours, result.minutes, result.seconds, result.milliseconds, result.microseconds, result.nanoseconds);
  67738. }
  67739. };
  67740. exports2.Duration = Duration;
  67741. var RelativeDuration = class {
  67742. years;
  67743. months;
  67744. weeks;
  67745. days;
  67746. hours;
  67747. minutes;
  67748. seconds;
  67749. milliseconds;
  67750. microseconds;
  67751. constructor(years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0, microseconds = 0) {
  67752. this.years = Math.trunc(years) || 0;
  67753. this.months = Math.trunc(months) || 0;
  67754. this.weeks = Math.trunc(weeks) || 0;
  67755. this.days = Math.trunc(days) || 0;
  67756. this.hours = Math.trunc(hours) || 0;
  67757. this.minutes = Math.trunc(minutes) || 0;
  67758. this.seconds = Math.trunc(seconds) || 0;
  67759. this.milliseconds = Math.trunc(milliseconds) || 0;
  67760. this.microseconds = Math.trunc(microseconds) || 0;
  67761. forwardJsonAsToString(this);
  67762. throwOnValueOf(this, "RelativeDuration");
  67763. }
  67764. toString() {
  67765. let str = "P";
  67766. if (this.years) {
  67767. str += `${this.years}Y`;
  67768. }
  67769. if (this.months) {
  67770. str += `${this.months}M`;
  67771. }
  67772. const days = this.days + 7 * this.weeks;
  67773. if (days) {
  67774. str += `${days}D`;
  67775. }
  67776. let timeParts = "";
  67777. if (this.hours) {
  67778. timeParts += `${this.hours}H`;
  67779. }
  67780. if (this.minutes) {
  67781. timeParts += `${this.minutes}M`;
  67782. }
  67783. const seconds = this.seconds + this.milliseconds / 1e3 + this.microseconds / 1e6;
  67784. if (seconds !== 0) {
  67785. timeParts += `${seconds}S`;
  67786. }
  67787. if (timeParts) {
  67788. str += `T${timeParts}`;
  67789. }
  67790. if (str === "P") {
  67791. return "PT0S";
  67792. }
  67793. return str;
  67794. }
  67795. };
  67796. exports2.RelativeDuration = RelativeDuration;
  67797. var DateDuration = class {
  67798. years;
  67799. months;
  67800. weeks;
  67801. days;
  67802. constructor(years = 0, months = 0, weeks = 0, days = 0) {
  67803. this.years = Math.trunc(years) || 0;
  67804. this.months = Math.trunc(months) || 0;
  67805. this.weeks = Math.trunc(weeks) || 0;
  67806. this.days = Math.trunc(days) || 0;
  67807. forwardJsonAsToString(this);
  67808. throwOnValueOf(this, "DateDuration");
  67809. }
  67810. toString() {
  67811. let str = "P";
  67812. if (this.years) {
  67813. str += `${this.years}Y`;
  67814. }
  67815. if (this.months) {
  67816. str += `${this.months}M`;
  67817. }
  67818. const days = this.days + 7 * this.weeks;
  67819. if (days) {
  67820. str += `${days}D`;
  67821. }
  67822. if (str === "P") {
  67823. return "PT0S";
  67824. }
  67825. return str;
  67826. }
  67827. };
  67828. exports2.DateDuration = DateDuration;
  67829. var humanDurationPrefixes = {
  67830. h: 36e5,
  67831. hou: 36e5,
  67832. m: 6e4,
  67833. min: 6e4,
  67834. s: 1e3,
  67835. sec: 1e3,
  67836. ms: 1,
  67837. mil: 1
  67838. };
  67839. function parseHumanDurationString(durationStr) {
  67840. const regex = /(\d+|\d+\.\d+|\.\d+)\s*(hours?|minutes?|seconds?|milliseconds?|ms|h|m|s)\s*/g;
  67841. let duration = 0;
  67842. const seen = /* @__PURE__ */ new Set();
  67843. let match2 = regex.exec(durationStr);
  67844. let lastIndex = 0;
  67845. while (match2) {
  67846. if (match2.index !== lastIndex) {
  67847. throw new Error(`invalid duration "${durationStr}"`);
  67848. }
  67849. const mult = humanDurationPrefixes[match2[2].slice(0, 3)];
  67850. if (seen.has(mult)) {
  67851. throw new Error(`invalid duration "${durationStr}"`);
  67852. }
  67853. duration += Number(match2[1]) * mult;
  67854. seen.add(mult);
  67855. lastIndex = regex.lastIndex;
  67856. match2 = regex.exec(durationStr);
  67857. }
  67858. if (lastIndex !== durationStr.length) {
  67859. throw new Error(`invalid duration "${durationStr}"`);
  67860. }
  67861. return duration;
  67862. }
  67863. var forwardJsonAsToString = (obj) => {
  67864. Object.defineProperty(obj, "toJSON", {
  67865. value: () => obj.toString(),
  67866. enumerable: false,
  67867. configurable: true
  67868. });
  67869. };
  67870. var throwOnValueOf = (obj, typename) => {
  67871. Object.defineProperty(obj, "valueOf", {
  67872. value: () => {
  67873. throw new TypeError(`Not possible to compare ${typename}`);
  67874. },
  67875. enumerable: false,
  67876. configurable: true
  67877. });
  67878. };
  67879. }
  67880. });
  67881. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/datetime.js
  67882. var require_datetime2 = __commonJS({
  67883. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/datetime.js"(exports2) {
  67884. "use strict";
  67885. Object.defineProperty(exports2, "__esModule", { value: true });
  67886. exports2.DateDurationCodec = exports2.RelativeDurationCodec = exports2.DurationCodec = exports2.LocalTimeCodec = exports2.LocalDateCodec = exports2.LocalDateTimeCodec = exports2.DateTimeCodec = void 0;
  67887. exports2.checkValidGelDuration = checkValidGelDuration;
  67888. var ifaces_1 = require_ifaces();
  67889. var datetime_1 = require_datetime();
  67890. var dateutil_1 = require_dateutil();
  67891. var errors_1 = require_errors();
  67892. var TIMESHIFT = 9466848e5;
  67893. var BI_TIMESHIFT_US = BigInt(TIMESHIFT) * 1000n;
  67894. var DATESHIFT_ORD = (0, dateutil_1.ymd2ord)(2e3, 1, 1);
  67895. var DateTimeCodec = class extends ifaces_1.ScalarCodec {
  67896. tsType = "Date";
  67897. encode(buf, object, ctx) {
  67898. if (ctx.hasOverload(this)) {
  67899. const val2 = ctx.preEncode(this, object);
  67900. if (typeof val2 != "bigint") {
  67901. throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom std::datetime codec`);
  67902. }
  67903. buf.writeInt32(8);
  67904. buf.writeBigInt64(val2 - BI_TIMESHIFT_US);
  67905. return;
  67906. }
  67907. if (!(object instanceof Date)) {
  67908. throw new errors_1.InvalidArgumentError(`a Date instance was expected, got "${object}"`);
  67909. }
  67910. const ms = object.getTime() - TIMESHIFT;
  67911. const us = ms * 1e3;
  67912. buf.writeInt32(8);
  67913. buf.writeInt64(us);
  67914. }
  67915. decode(buf, ctx) {
  67916. if (ctx.hasOverload(this)) {
  67917. const us2 = buf.readBigInt64();
  67918. return ctx.postDecode(this, us2 + BI_TIMESHIFT_US);
  67919. }
  67920. const us = Number(buf.readBigInt64());
  67921. let ms = Math.round(us / 1e3);
  67922. if (Math.abs(us % 1e3) === 500 && Math.abs(ms) % 2 === 1) {
  67923. ms -= 1;
  67924. }
  67925. ms += TIMESHIFT;
  67926. return new Date(ms);
  67927. }
  67928. };
  67929. exports2.DateTimeCodec = DateTimeCodec;
  67930. var LocalDateTimeCodec = class extends ifaces_1.ScalarCodec {
  67931. tsType = "LocalDateTime";
  67932. tsModule = "gel";
  67933. encode(buf, object, ctx) {
  67934. if (ctx.hasOverload(this)) {
  67935. let us2 = ctx.preEncode(this, object);
  67936. if (typeof us2 != "bigint") {
  67937. throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cal::local_datetime codec`);
  67938. }
  67939. us2 -= BI_TIMESHIFT_US;
  67940. buf.writeInt32(8);
  67941. buf.writeBigInt64(us2);
  67942. return;
  67943. }
  67944. if (!(object instanceof datetime_1.LocalDateTime)) {
  67945. throw new errors_1.InvalidArgumentError(`a LocalDateTime instance was expected, got "${object}"`);
  67946. }
  67947. const ms = BigInt(datetime_1.localDateInstances.get(object).getTime() - TIMESHIFT);
  67948. let us = ms * 1000n + BigInt(object.hour * 36e8 + object.minute * 6e7 + object.second * 1e6 + object.millisecond * 1e3 + object.microsecond);
  67949. if (object.nanosecond === 500 && Math.abs(object.microsecond) % 2 === 1 || object.nanosecond > 500) {
  67950. us += 1n;
  67951. }
  67952. buf.writeInt32(8);
  67953. buf.writeBigInt64(us);
  67954. }
  67955. decode(buf, ctx) {
  67956. const bi_us = buf.readBigInt64();
  67957. if (ctx.hasOverload(this)) {
  67958. return ctx.postDecode(this, BigInt(bi_us + BI_TIMESHIFT_US));
  67959. }
  67960. const bi_ms = bi_us / 1000n;
  67961. let us = Number(bi_us - bi_ms * 1000n);
  67962. let ms = Number(bi_ms);
  67963. if (us < 0) {
  67964. us += 1e3;
  67965. ms -= 1;
  67966. }
  67967. ms += TIMESHIFT;
  67968. const date = new Date(ms);
  67969. return new datetime_1.LocalDateTime(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds(), us);
  67970. }
  67971. };
  67972. exports2.LocalDateTimeCodec = LocalDateTimeCodec;
  67973. var LocalDateCodec = class extends ifaces_1.ScalarCodec {
  67974. tsType = "LocalDate";
  67975. tsModule = "gel";
  67976. encode(buf, object, ctx) {
  67977. if (ctx.hasOverload(this)) {
  67978. const ret = ctx.preEncode(this, object);
  67979. const ord2 = (0, dateutil_1.ymd2ord)(...ret);
  67980. buf.writeInt32(4);
  67981. buf.writeInt32(ord2 - DATESHIFT_ORD);
  67982. return;
  67983. }
  67984. if (!(object instanceof datetime_1.LocalDate)) {
  67985. throw new errors_1.InvalidArgumentError(`a LocalDate instance was expected, got "${object}"`);
  67986. }
  67987. const ord = (0, datetime_1.LocalDateToOrdinal)(object);
  67988. buf.writeInt32(4);
  67989. buf.writeInt32(ord - DATESHIFT_ORD);
  67990. }
  67991. decode(buf, ctx) {
  67992. const ord = buf.readInt32() + DATESHIFT_ORD;
  67993. if (ctx.hasOverload(this)) {
  67994. return ctx.postDecode(this, (0, dateutil_1.ord2ymd)(ord));
  67995. }
  67996. return (0, datetime_1.LocalDateFromOrdinal)(ord);
  67997. }
  67998. };
  67999. exports2.LocalDateCodec = LocalDateCodec;
  68000. var LocalTimeCodec = class extends ifaces_1.ScalarCodec {
  68001. tsType = "LocalTime";
  68002. tsModule = "gel";
  68003. encode(buf, object, ctx) {
  68004. if (ctx.hasOverload(this)) {
  68005. const us2 = ctx.preEncode(this, object);
  68006. if (typeof us2 != "bigint") {
  68007. throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cal::local_time codec`);
  68008. }
  68009. buf.writeInt32(8);
  68010. buf.writeBigInt64(us2);
  68011. return;
  68012. }
  68013. if (!(object instanceof datetime_1.LocalTime)) {
  68014. throw new errors_1.InvalidArgumentError(`a LocalTime instance was expected, got "${object}"`);
  68015. }
  68016. let us = object.hour * 36e8 + object.minute * 6e7 + object.second * 1e6 + object.millisecond * 1e3 + object.microsecond;
  68017. if (object.nanosecond === 500 && us % 2 === 1 || object.nanosecond > 500) {
  68018. us += 1;
  68019. }
  68020. buf.writeInt32(8);
  68021. buf.writeInt64(us);
  68022. }
  68023. decode(buf, ctx) {
  68024. const bius = buf.readBigInt64();
  68025. if (ctx.hasOverload(this)) {
  68026. return ctx.postDecode(this, bius);
  68027. }
  68028. let us = Number(bius);
  68029. let seconds = Math.floor(us / 1e6);
  68030. const ms = Math.floor(us % 1e6 / 1e3);
  68031. us = us % 1e6 - ms * 1e3;
  68032. let minutes = Math.floor(seconds / 60);
  68033. seconds = Math.floor(seconds % 60);
  68034. const hours = Math.floor(minutes / 60);
  68035. minutes = Math.floor(minutes % 60);
  68036. return new datetime_1.LocalTime(hours, minutes, seconds, ms, us);
  68037. }
  68038. };
  68039. exports2.LocalTimeCodec = LocalTimeCodec;
  68040. var unencodableDurationFields = [
  68041. "years",
  68042. "months",
  68043. "weeks",
  68044. "days"
  68045. ];
  68046. function checkValidGelDuration(duration) {
  68047. for (const field of unencodableDurationFields) {
  68048. if (duration[field] !== 0) {
  68049. return field;
  68050. }
  68051. }
  68052. return null;
  68053. }
  68054. var DurationCodec = class extends ifaces_1.ScalarCodec {
  68055. tsType = "Duration";
  68056. tsModule = "gel";
  68057. encode(buf, object, ctx) {
  68058. if (ctx.hasOverload(this)) {
  68059. const us2 = ctx.preEncode(this, object);
  68060. if (typeof us2 != "bigint") {
  68061. throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom std::duration codec`);
  68062. }
  68063. buf.writeInt32(16);
  68064. buf.writeBigInt64(us2);
  68065. buf.writeInt32(0);
  68066. buf.writeInt32(0);
  68067. return;
  68068. }
  68069. if (!(object instanceof datetime_1.Duration)) {
  68070. throw new errors_1.InvalidArgumentError(`a Duration instance was expected, got "${object}"`);
  68071. }
  68072. const invalidField = checkValidGelDuration(object);
  68073. if (invalidField) {
  68074. throw new errors_1.InvalidArgumentError(`Cannot encode a 'Duration' with a non-zero number of ${invalidField}`);
  68075. }
  68076. let us = BigInt(Math.abs(object.microseconds));
  68077. us += BigInt(Math.abs(object.milliseconds)) * BigInt(1e3);
  68078. us += BigInt(Math.abs(object.seconds)) * BigInt(1e6);
  68079. us += BigInt(Math.abs(object.minutes)) * BigInt(6e7);
  68080. us += BigInt(Math.abs(object.hours)) * BigInt(36e8);
  68081. if (Math.abs(object.nanoseconds) === 500 && Math.abs(object.microseconds) % 2 === 1 || Math.abs(object.nanoseconds) > 500) {
  68082. us += 1n;
  68083. }
  68084. if (object.sign < 0) {
  68085. us *= -1n;
  68086. }
  68087. buf.writeInt32(16);
  68088. buf.writeBigInt64(us);
  68089. buf.writeInt32(0);
  68090. buf.writeInt32(0);
  68091. }
  68092. decode(buf, ctx) {
  68093. let bius = buf.readBigInt64();
  68094. const days = buf.readInt32();
  68095. const months = buf.readInt32();
  68096. if (days !== 0) {
  68097. throw new errors_1.ProtocolError("non-zero reserved bytes in duration");
  68098. }
  68099. if (months !== 0) {
  68100. throw new errors_1.ProtocolError("non-zero reserved bytes in duration");
  68101. }
  68102. if (ctx.hasOverload(this)) {
  68103. return ctx.postDecode(this, bius);
  68104. }
  68105. let sign = 1;
  68106. if (Number(bius) < 0) {
  68107. sign = -1;
  68108. bius *= -1n;
  68109. }
  68110. const biMillion = 1000000n;
  68111. const biSeconds = bius / biMillion;
  68112. let us = Number(bius - biSeconds * biMillion);
  68113. const ms = Math.floor(us / 1e3);
  68114. us = us % 1e3;
  68115. let seconds = Number(biSeconds);
  68116. let minutes = Math.floor(seconds / 60);
  68117. seconds = Math.floor(seconds % 60);
  68118. const hours = Math.floor(minutes / 60);
  68119. minutes = Math.floor(minutes % 60);
  68120. return new datetime_1.Duration(0, 0, 0, 0, hours * sign, minutes * sign, seconds * sign, ms * sign, us * sign);
  68121. }
  68122. };
  68123. exports2.DurationCodec = DurationCodec;
  68124. var RelativeDurationCodec = class extends ifaces_1.ScalarCodec {
  68125. tsType = "RelativeDuration";
  68126. tsModule = "gel";
  68127. encode(buf, object, ctx) {
  68128. if (ctx.hasOverload(this)) {
  68129. const ret = ctx.preEncode(this, object);
  68130. buf.writeInt32(16);
  68131. buf.writeBigInt64(ret[2]);
  68132. buf.writeInt32(ret[1]);
  68133. buf.writeInt32(ret[0]);
  68134. return;
  68135. }
  68136. if (!(object instanceof datetime_1.RelativeDuration)) {
  68137. throw new errors_1.InvalidArgumentError(`
  68138. a RelativeDuration instance was expected, got "${object}"
  68139. `);
  68140. }
  68141. const us = BigInt(object.microseconds) + BigInt(object.milliseconds) * BigInt(1e3) + BigInt(object.seconds) * BigInt(1e6) + BigInt(object.minutes) * BigInt(6e7) + BigInt(object.hours) * BigInt(36e8);
  68142. buf.writeInt32(16);
  68143. buf.writeBigInt64(us);
  68144. buf.writeInt32(object.days + 7 * object.weeks);
  68145. buf.writeInt32(object.months + 12 * object.years);
  68146. }
  68147. decode(buf, ctx) {
  68148. let bius = buf.readBigInt64();
  68149. let days = buf.readInt32();
  68150. let months = buf.readInt32();
  68151. if (ctx.hasOverload(this)) {
  68152. return ctx.postDecode(this, [
  68153. months,
  68154. days,
  68155. bius
  68156. ]);
  68157. }
  68158. let sign = 1;
  68159. if (Number(bius) < 0) {
  68160. sign = -1;
  68161. bius *= -1n;
  68162. }
  68163. const million = BigInt(1e6);
  68164. const biSeconds = bius / million;
  68165. let us = Number(bius - biSeconds * million);
  68166. const ms = Math.trunc(us / 1e3);
  68167. us = us % 1e3;
  68168. let seconds = Number(biSeconds);
  68169. let minutes = Math.trunc(seconds / 60);
  68170. seconds = Math.trunc(seconds % 60);
  68171. const hours = Math.trunc(minutes / 60);
  68172. minutes = Math.trunc(minutes % 60);
  68173. const weeks = Math.trunc(days / 7);
  68174. days = Math.trunc(days % 7);
  68175. const years = Math.trunc(months / 12);
  68176. months = Math.trunc(months % 12);
  68177. return new datetime_1.RelativeDuration(years, months, weeks, days, hours * sign, minutes * sign, seconds * sign, ms * sign, us * sign);
  68178. }
  68179. };
  68180. exports2.RelativeDurationCodec = RelativeDurationCodec;
  68181. var DateDurationCodec = class extends ifaces_1.ScalarCodec {
  68182. tsType = "DateDuration";
  68183. tsModule = "gel";
  68184. encode(buf, object, ctx) {
  68185. if (ctx.hasOverload(this)) {
  68186. const ret = ctx.preEncode(this, object);
  68187. buf.writeInt32(16);
  68188. buf.writeInt64(0);
  68189. buf.writeInt32(ret[1]);
  68190. buf.writeInt32(ret[0]);
  68191. return;
  68192. }
  68193. if (!(object instanceof datetime_1.DateDuration)) {
  68194. throw new errors_1.InvalidArgumentError(`
  68195. a DateDuration instance was expected, got "${object}"
  68196. `);
  68197. }
  68198. buf.writeInt32(16);
  68199. buf.writeInt64(0);
  68200. buf.writeInt32(object.days + 7 * object.weeks);
  68201. buf.writeInt32(object.months + 12 * object.years);
  68202. }
  68203. decode(buf, ctx) {
  68204. buf.discard(8);
  68205. let days = buf.readInt32();
  68206. let months = buf.readInt32();
  68207. if (ctx.hasOverload(this)) {
  68208. return ctx.postDecode(this, [months, days]);
  68209. }
  68210. const weeks = Math.trunc(days / 7);
  68211. days = Math.trunc(days % 7);
  68212. const years = Math.trunc(months / 12);
  68213. months = Math.trunc(months % 12);
  68214. return new datetime_1.DateDuration(years, months, weeks, days);
  68215. }
  68216. };
  68217. exports2.DateDurationCodec = DateDurationCodec;
  68218. }
  68219. });
  68220. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/memory.js
  68221. var require_memory = __commonJS({
  68222. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/memory.js"(exports2) {
  68223. "use strict";
  68224. Object.defineProperty(exports2, "__esModule", { value: true });
  68225. exports2.ConfigMemory = void 0;
  68226. var KiB = 1024;
  68227. var MiB = 1024 * KiB;
  68228. var GiB = 1024 * MiB;
  68229. var TiB = 1024 * GiB;
  68230. var PiB = 1024 * TiB;
  68231. var ConfigMemory = class {
  68232. _bytes;
  68233. constructor(bytes) {
  68234. this._bytes = bytes;
  68235. }
  68236. get bytes() {
  68237. return Number(this._bytes);
  68238. }
  68239. get bytesBigInt() {
  68240. return this._bytes;
  68241. }
  68242. get kibibytes() {
  68243. return Number(this._bytes) / KiB;
  68244. }
  68245. get mebibytes() {
  68246. return Number(this._bytes) / MiB;
  68247. }
  68248. get gibibytes() {
  68249. return Number(this._bytes) / GiB;
  68250. }
  68251. get tebibytes() {
  68252. return Number(this._bytes) / TiB;
  68253. }
  68254. get pebibytes() {
  68255. return Number(this._bytes) / PiB;
  68256. }
  68257. toString() {
  68258. const bytes = this._bytes;
  68259. const bigPiB = BigInt(PiB);
  68260. if (bytes >= bigPiB && Number(bytes % bigPiB) === 0) {
  68261. return `${bytes / bigPiB}PiB`;
  68262. }
  68263. const bigTiB = BigInt(TiB);
  68264. if (bytes >= bigTiB && Number(bytes % bigTiB) === 0) {
  68265. return `${bytes / bigTiB}TiB`;
  68266. }
  68267. const bigGiB = BigInt(GiB);
  68268. if (bytes >= bigGiB && Number(bytes % bigGiB) === 0) {
  68269. return `${bytes / bigGiB}GiB`;
  68270. }
  68271. const bigMiB = BigInt(MiB);
  68272. if (bytes >= bigMiB && Number(bytes % bigMiB) === 0) {
  68273. return `${bytes / bigMiB}MiB`;
  68274. }
  68275. const bigKiB = BigInt(KiB);
  68276. if (bytes >= bigKiB && Number(bytes % bigKiB) === 0) {
  68277. return `${bytes / bigKiB}KiB`;
  68278. }
  68279. return `${bytes}B`;
  68280. }
  68281. };
  68282. exports2.ConfigMemory = ConfigMemory;
  68283. }
  68284. });
  68285. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/memory.js
  68286. var require_memory2 = __commonJS({
  68287. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/memory.js"(exports2) {
  68288. "use strict";
  68289. Object.defineProperty(exports2, "__esModule", { value: true });
  68290. exports2.ConfigMemoryCodec = void 0;
  68291. var ifaces_1 = require_ifaces();
  68292. var memory_1 = require_memory();
  68293. var errors_1 = require_errors();
  68294. var ConfigMemoryCodec = class extends ifaces_1.ScalarCodec {
  68295. tsType = "ConfigMemory";
  68296. tsModule = "gel";
  68297. encode(buf, object, ctx) {
  68298. if (ctx.hasOverload(this)) {
  68299. const val2 = ctx.preEncode(this, object);
  68300. if (typeof val2 != "bigint") {
  68301. throw new errors_1.InvalidArgumentError(`a bigint was expected out of a custom cfg::memory codec`);
  68302. }
  68303. buf.writeInt32(8);
  68304. buf.writeBigInt64(val2);
  68305. return;
  68306. }
  68307. if (!(object instanceof memory_1.ConfigMemory)) {
  68308. throw new errors_1.InvalidArgumentError(`a ConfigMemory instance was expected, got "${object}"`);
  68309. }
  68310. buf.writeInt32(8);
  68311. buf.writeBigInt64(object._bytes);
  68312. }
  68313. decode(buf, ctx) {
  68314. const val2 = buf.readBigInt64();
  68315. if (ctx.hasOverload(this)) {
  68316. return ctx.postDecode(this, val2);
  68317. }
  68318. return new memory_1.ConfigMemory(val2);
  68319. }
  68320. };
  68321. exports2.ConfigMemoryCodec = ConfigMemoryCodec;
  68322. }
  68323. });
  68324. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/messages.cjs
  68325. var require_messages = __commonJS({
  68326. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/messages.cjs"(exports2) {
  68327. "use strict";
  68328. Object.defineProperty(exports2, "__esModule", {
  68329. value: true
  68330. });
  68331. var THIS_IS_NOT_AN_OBJECT = exports2.THIS_IS_NOT_AN_OBJECT = "This is not an object";
  68332. var THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = exports2.THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT = "This is not a Float16Array object";
  68333. var THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY = exports2.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY = "This constructor is not a subclass of Float16Array";
  68334. var THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT = exports2.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT = "The constructor property value is not an object";
  68335. var SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT = exports2.SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT = "Species constructor didn't return TypedArray object";
  68336. var DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH = exports2.DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH = "Derived constructor created TypedArray object which was too small length";
  68337. var ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER = exports2.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER = "Attempting to access detached ArrayBuffer";
  68338. var CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT = exports2.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT = "Cannot convert undefined or null to object";
  68339. var CANNOT_MIX_BIGINT_AND_OTHER_TYPES = exports2.CANNOT_MIX_BIGINT_AND_OTHER_TYPES = "Cannot mix BigInt and other types, use explicit conversions";
  68340. var ITERATOR_PROPERTY_IS_NOT_CALLABLE = exports2.ITERATOR_PROPERTY_IS_NOT_CALLABLE = "@@iterator property is not callable";
  68341. var REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE = exports2.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE = "Reduce of empty array with no initial value";
  68342. var THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED = exports2.THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED = "The comparison function must be either a function or undefined";
  68343. var OFFSET_IS_OUT_OF_BOUNDS = exports2.OFFSET_IS_OUT_OF_BOUNDS = "Offset is out of bounds";
  68344. }
  68345. });
  68346. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/primordials.cjs
  68347. var require_primordials = __commonJS({
  68348. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/primordials.cjs"(exports2) {
  68349. "use strict";
  68350. Object.defineProperty(exports2, "__esModule", {
  68351. value: true
  68352. });
  68353. var _messages = require_messages();
  68354. function uncurryThis(target) {
  68355. return (thisArg, ...args) => {
  68356. return ReflectApply(target, thisArg, args);
  68357. };
  68358. }
  68359. function uncurryThisGetter(target, key) {
  68360. return uncurryThis(ReflectGetOwnPropertyDescriptor(target, key).get);
  68361. }
  68362. var {
  68363. apply: ReflectApply,
  68364. construct: ReflectConstruct,
  68365. defineProperty: ReflectDefineProperty,
  68366. get: ReflectGet,
  68367. getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor,
  68368. getPrototypeOf: ReflectGetPrototypeOf,
  68369. has: ReflectHas,
  68370. ownKeys: ReflectOwnKeys,
  68371. set: ReflectSet,
  68372. setPrototypeOf: ReflectSetPrototypeOf
  68373. } = Reflect;
  68374. exports2.ReflectSetPrototypeOf = ReflectSetPrototypeOf;
  68375. exports2.ReflectSet = ReflectSet;
  68376. exports2.ReflectOwnKeys = ReflectOwnKeys;
  68377. exports2.ReflectHas = ReflectHas;
  68378. exports2.ReflectGetPrototypeOf = ReflectGetPrototypeOf;
  68379. exports2.ReflectGetOwnPropertyDescriptor = ReflectGetOwnPropertyDescriptor;
  68380. exports2.ReflectGet = ReflectGet;
  68381. exports2.ReflectDefineProperty = ReflectDefineProperty;
  68382. exports2.ReflectConstruct = ReflectConstruct;
  68383. exports2.ReflectApply = ReflectApply;
  68384. var NativeProxy = exports2.NativeProxy = Proxy;
  68385. var {
  68386. EPSILON,
  68387. MAX_SAFE_INTEGER,
  68388. isFinite: NumberIsFinite,
  68389. isNaN: NumberIsNaN
  68390. } = Number;
  68391. exports2.NumberIsNaN = NumberIsNaN;
  68392. exports2.NumberIsFinite = NumberIsFinite;
  68393. exports2.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER;
  68394. exports2.EPSILON = EPSILON;
  68395. var {
  68396. iterator: SymbolIterator,
  68397. species: SymbolSpecies,
  68398. toStringTag: SymbolToStringTag,
  68399. for: SymbolFor
  68400. } = Symbol;
  68401. exports2.SymbolFor = SymbolFor;
  68402. exports2.SymbolToStringTag = SymbolToStringTag;
  68403. exports2.SymbolSpecies = SymbolSpecies;
  68404. exports2.SymbolIterator = SymbolIterator;
  68405. var NativeObject = exports2.NativeObject = Object;
  68406. var {
  68407. create: ObjectCreate,
  68408. defineProperty: ObjectDefineProperty,
  68409. freeze: ObjectFreeze,
  68410. is: ObjectIs
  68411. } = NativeObject;
  68412. exports2.ObjectIs = ObjectIs;
  68413. exports2.ObjectFreeze = ObjectFreeze;
  68414. exports2.ObjectDefineProperty = ObjectDefineProperty;
  68415. exports2.ObjectCreate = ObjectCreate;
  68416. var ObjectPrototype = NativeObject.prototype;
  68417. var ObjectPrototype__lookupGetter__ = exports2.ObjectPrototype__lookupGetter__ = ObjectPrototype.__lookupGetter__ ? uncurryThis(ObjectPrototype.__lookupGetter__) : (object, key) => {
  68418. if (object == null) {
  68419. throw NativeTypeError(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
  68420. }
  68421. let target = NativeObject(object);
  68422. do {
  68423. const descriptor = ReflectGetOwnPropertyDescriptor(target, key);
  68424. if (descriptor !== void 0) {
  68425. if (ObjectHasOwn(descriptor, "get")) {
  68426. return descriptor.get;
  68427. }
  68428. return;
  68429. }
  68430. } while ((target = ReflectGetPrototypeOf(target)) !== null);
  68431. };
  68432. var ObjectHasOwn = exports2.ObjectHasOwn = NativeObject.hasOwn || uncurryThis(ObjectPrototype.hasOwnProperty);
  68433. var NativeArray = Array;
  68434. var ArrayIsArray = exports2.ArrayIsArray = NativeArray.isArray;
  68435. var ArrayPrototype = NativeArray.prototype;
  68436. var ArrayPrototypeJoin = exports2.ArrayPrototypeJoin = uncurryThis(ArrayPrototype.join);
  68437. var ArrayPrototypePush = exports2.ArrayPrototypePush = uncurryThis(ArrayPrototype.push);
  68438. var ArrayPrototypeToLocaleString = exports2.ArrayPrototypeToLocaleString = uncurryThis(ArrayPrototype.toLocaleString);
  68439. var NativeArrayPrototypeSymbolIterator = exports2.NativeArrayPrototypeSymbolIterator = ArrayPrototype[SymbolIterator];
  68440. var ArrayPrototypeSymbolIterator = exports2.ArrayPrototypeSymbolIterator = uncurryThis(NativeArrayPrototypeSymbolIterator);
  68441. var {
  68442. abs: MathAbs,
  68443. trunc: MathTrunc
  68444. } = Math;
  68445. exports2.MathTrunc = MathTrunc;
  68446. exports2.MathAbs = MathAbs;
  68447. var NativeArrayBuffer = exports2.NativeArrayBuffer = ArrayBuffer;
  68448. var ArrayBufferIsView = exports2.ArrayBufferIsView = NativeArrayBuffer.isView;
  68449. var ArrayBufferPrototype = NativeArrayBuffer.prototype;
  68450. var ArrayBufferPrototypeSlice = exports2.ArrayBufferPrototypeSlice = uncurryThis(ArrayBufferPrototype.slice);
  68451. var ArrayBufferPrototypeGetByteLength = exports2.ArrayBufferPrototypeGetByteLength = uncurryThisGetter(ArrayBufferPrototype, "byteLength");
  68452. var NativeSharedArrayBuffer = exports2.NativeSharedArrayBuffer = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : null;
  68453. var SharedArrayBufferPrototypeGetByteLength = exports2.SharedArrayBufferPrototypeGetByteLength = NativeSharedArrayBuffer && uncurryThisGetter(NativeSharedArrayBuffer.prototype, "byteLength");
  68454. var TypedArray = exports2.TypedArray = ReflectGetPrototypeOf(Uint8Array);
  68455. var TypedArrayFrom = TypedArray.from;
  68456. var TypedArrayPrototype = exports2.TypedArrayPrototype = TypedArray.prototype;
  68457. var NativeTypedArrayPrototypeSymbolIterator = exports2.NativeTypedArrayPrototypeSymbolIterator = TypedArrayPrototype[SymbolIterator];
  68458. var TypedArrayPrototypeKeys = exports2.TypedArrayPrototypeKeys = uncurryThis(TypedArrayPrototype.keys);
  68459. var TypedArrayPrototypeValues = exports2.TypedArrayPrototypeValues = uncurryThis(TypedArrayPrototype.values);
  68460. var TypedArrayPrototypeEntries = exports2.TypedArrayPrototypeEntries = uncurryThis(TypedArrayPrototype.entries);
  68461. var TypedArrayPrototypeSet = exports2.TypedArrayPrototypeSet = uncurryThis(TypedArrayPrototype.set);
  68462. var TypedArrayPrototypeReverse = exports2.TypedArrayPrototypeReverse = uncurryThis(TypedArrayPrototype.reverse);
  68463. var TypedArrayPrototypeFill = exports2.TypedArrayPrototypeFill = uncurryThis(TypedArrayPrototype.fill);
  68464. var TypedArrayPrototypeCopyWithin = exports2.TypedArrayPrototypeCopyWithin = uncurryThis(TypedArrayPrototype.copyWithin);
  68465. var TypedArrayPrototypeSort = exports2.TypedArrayPrototypeSort = uncurryThis(TypedArrayPrototype.sort);
  68466. var TypedArrayPrototypeSlice = exports2.TypedArrayPrototypeSlice = uncurryThis(TypedArrayPrototype.slice);
  68467. var TypedArrayPrototypeSubarray = exports2.TypedArrayPrototypeSubarray = uncurryThis(TypedArrayPrototype.subarray);
  68468. var TypedArrayPrototypeGetBuffer = exports2.TypedArrayPrototypeGetBuffer = uncurryThisGetter(TypedArrayPrototype, "buffer");
  68469. var TypedArrayPrototypeGetByteOffset = exports2.TypedArrayPrototypeGetByteOffset = uncurryThisGetter(TypedArrayPrototype, "byteOffset");
  68470. var TypedArrayPrototypeGetLength = exports2.TypedArrayPrototypeGetLength = uncurryThisGetter(TypedArrayPrototype, "length");
  68471. var TypedArrayPrototypeGetSymbolToStringTag = exports2.TypedArrayPrototypeGetSymbolToStringTag = uncurryThisGetter(TypedArrayPrototype, SymbolToStringTag);
  68472. var NativeUint8Array = exports2.NativeUint8Array = Uint8Array;
  68473. var NativeUint16Array = exports2.NativeUint16Array = Uint16Array;
  68474. var Uint16ArrayFrom = (...args) => {
  68475. return ReflectApply(TypedArrayFrom, NativeUint16Array, args);
  68476. };
  68477. exports2.Uint16ArrayFrom = Uint16ArrayFrom;
  68478. var NativeUint32Array = exports2.NativeUint32Array = Uint32Array;
  68479. var NativeFloat32Array = exports2.NativeFloat32Array = Float32Array;
  68480. var ArrayIteratorPrototype = exports2.ArrayIteratorPrototype = ReflectGetPrototypeOf([][SymbolIterator]());
  68481. var ArrayIteratorPrototypeNext = exports2.ArrayIteratorPrototypeNext = uncurryThis(ArrayIteratorPrototype.next);
  68482. var GeneratorPrototypeNext = exports2.GeneratorPrototypeNext = uncurryThis(function* () {
  68483. }().next);
  68484. var IteratorPrototype = exports2.IteratorPrototype = ReflectGetPrototypeOf(ArrayIteratorPrototype);
  68485. var DataViewPrototype = DataView.prototype;
  68486. var DataViewPrototypeGetUint16 = exports2.DataViewPrototypeGetUint16 = uncurryThis(DataViewPrototype.getUint16);
  68487. var DataViewPrototypeSetUint16 = exports2.DataViewPrototypeSetUint16 = uncurryThis(DataViewPrototype.setUint16);
  68488. var NativeTypeError = exports2.NativeTypeError = TypeError;
  68489. var NativeRangeError = exports2.NativeRangeError = RangeError;
  68490. var NativeWeakSet = exports2.NativeWeakSet = WeakSet;
  68491. var WeakSetPrototype = NativeWeakSet.prototype;
  68492. var WeakSetPrototypeAdd = exports2.WeakSetPrototypeAdd = uncurryThis(WeakSetPrototype.add);
  68493. var WeakSetPrototypeHas = exports2.WeakSetPrototypeHas = uncurryThis(WeakSetPrototype.has);
  68494. var NativeWeakMap = exports2.NativeWeakMap = WeakMap;
  68495. var WeakMapPrototype = NativeWeakMap.prototype;
  68496. var WeakMapPrototypeGet = exports2.WeakMapPrototypeGet = uncurryThis(WeakMapPrototype.get);
  68497. var WeakMapPrototypeHas = exports2.WeakMapPrototypeHas = uncurryThis(WeakMapPrototype.has);
  68498. var WeakMapPrototypeSet = exports2.WeakMapPrototypeSet = uncurryThis(WeakMapPrototype.set);
  68499. }
  68500. });
  68501. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/arrayIterator.cjs
  68502. var require_arrayIterator = __commonJS({
  68503. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/arrayIterator.cjs"(exports2) {
  68504. "use strict";
  68505. Object.defineProperty(exports2, "__esModule", {
  68506. value: true
  68507. });
  68508. exports2.safeIfNeeded = safeIfNeeded;
  68509. exports2.wrap = wrap;
  68510. var _primordials = require_primordials();
  68511. var arrayIterators = new _primordials.NativeWeakMap();
  68512. var SafeIteratorPrototype = (0, _primordials.ObjectCreate)(null, {
  68513. next: {
  68514. value: function next() {
  68515. const arrayIterator = (0, _primordials.WeakMapPrototypeGet)(arrayIterators, this);
  68516. return (0, _primordials.ArrayIteratorPrototypeNext)(arrayIterator);
  68517. }
  68518. },
  68519. [_primordials.SymbolIterator]: {
  68520. value: function values() {
  68521. return this;
  68522. }
  68523. }
  68524. });
  68525. function safeIfNeeded(array2) {
  68526. if (array2[_primordials.SymbolIterator] === _primordials.NativeArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext) {
  68527. return array2;
  68528. }
  68529. const safe = (0, _primordials.ObjectCreate)(SafeIteratorPrototype);
  68530. (0, _primordials.WeakMapPrototypeSet)(arrayIterators, safe, (0, _primordials.ArrayPrototypeSymbolIterator)(array2));
  68531. return safe;
  68532. }
  68533. var generators = new _primordials.NativeWeakMap();
  68534. var DummyArrayIteratorPrototype = (0, _primordials.ObjectCreate)(_primordials.IteratorPrototype, {
  68535. next: {
  68536. value: function next() {
  68537. const generator = (0, _primordials.WeakMapPrototypeGet)(generators, this);
  68538. return (0, _primordials.GeneratorPrototypeNext)(generator);
  68539. },
  68540. writable: true,
  68541. configurable: true
  68542. }
  68543. });
  68544. for (const key of (0, _primordials.ReflectOwnKeys)(_primordials.ArrayIteratorPrototype)) {
  68545. if (key === "next") {
  68546. continue;
  68547. }
  68548. (0, _primordials.ObjectDefineProperty)(DummyArrayIteratorPrototype, key, (0, _primordials.ReflectGetOwnPropertyDescriptor)(_primordials.ArrayIteratorPrototype, key));
  68549. }
  68550. function wrap(generator) {
  68551. const dummy = (0, _primordials.ObjectCreate)(DummyArrayIteratorPrototype);
  68552. (0, _primordials.WeakMapPrototypeSet)(generators, dummy, generator);
  68553. return dummy;
  68554. }
  68555. }
  68556. });
  68557. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/is.cjs
  68558. var require_is = __commonJS({
  68559. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/is.cjs"(exports2) {
  68560. "use strict";
  68561. Object.defineProperty(exports2, "__esModule", {
  68562. value: true
  68563. });
  68564. exports2.isAnyArrayBuffer = isAnyArrayBuffer;
  68565. exports2.isCanonicalIntegerIndexString = isCanonicalIntegerIndexString;
  68566. exports2.isNativeBigIntTypedArray = isNativeBigIntTypedArray;
  68567. exports2.isNativeTypedArray = isNativeTypedArray;
  68568. exports2.isObject = isObject;
  68569. exports2.isObjectLike = isObjectLike;
  68570. exports2.isOrdinaryArray = isOrdinaryArray;
  68571. exports2.isOrdinaryNativeTypedArray = isOrdinaryNativeTypedArray;
  68572. exports2.isSharedArrayBuffer = isSharedArrayBuffer;
  68573. var _primordials = require_primordials();
  68574. function isObject(value) {
  68575. return value !== null && typeof value === "object" || typeof value === "function";
  68576. }
  68577. function isObjectLike(value) {
  68578. return value !== null && typeof value === "object";
  68579. }
  68580. function isNativeTypedArray(value) {
  68581. return (0, _primordials.TypedArrayPrototypeGetSymbolToStringTag)(value) !== void 0;
  68582. }
  68583. function isNativeBigIntTypedArray(value) {
  68584. const typedArrayName = (0, _primordials.TypedArrayPrototypeGetSymbolToStringTag)(value);
  68585. return typedArrayName === "BigInt64Array" || typedArrayName === "BigUint64Array";
  68586. }
  68587. function isArrayBuffer(value) {
  68588. try {
  68589. if ((0, _primordials.ArrayIsArray)(value)) {
  68590. return false;
  68591. }
  68592. (0, _primordials.ArrayBufferPrototypeGetByteLength)(value);
  68593. return true;
  68594. } catch (e4) {
  68595. return false;
  68596. }
  68597. }
  68598. function isSharedArrayBuffer(value) {
  68599. if (_primordials.NativeSharedArrayBuffer === null) {
  68600. return false;
  68601. }
  68602. try {
  68603. (0, _primordials.SharedArrayBufferPrototypeGetByteLength)(value);
  68604. return true;
  68605. } catch (e4) {
  68606. return false;
  68607. }
  68608. }
  68609. function isAnyArrayBuffer(value) {
  68610. return isArrayBuffer(value) || isSharedArrayBuffer(value);
  68611. }
  68612. function isOrdinaryArray(value) {
  68613. if (!(0, _primordials.ArrayIsArray)(value)) {
  68614. return false;
  68615. }
  68616. return value[_primordials.SymbolIterator] === _primordials.NativeArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext;
  68617. }
  68618. function isOrdinaryNativeTypedArray(value) {
  68619. if (!isNativeTypedArray(value)) {
  68620. return false;
  68621. }
  68622. return value[_primordials.SymbolIterator] === _primordials.NativeTypedArrayPrototypeSymbolIterator && _primordials.ArrayIteratorPrototype.next === _primordials.ArrayIteratorPrototypeNext;
  68623. }
  68624. function isCanonicalIntegerIndexString(value) {
  68625. if (typeof value !== "string") {
  68626. return false;
  68627. }
  68628. const number2 = +value;
  68629. if (value !== number2 + "") {
  68630. return false;
  68631. }
  68632. if (!(0, _primordials.NumberIsFinite)(number2)) {
  68633. return false;
  68634. }
  68635. return number2 === (0, _primordials.MathTrunc)(number2);
  68636. }
  68637. }
  68638. });
  68639. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/brand.cjs
  68640. var require_brand = __commonJS({
  68641. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/brand.cjs"(exports2) {
  68642. "use strict";
  68643. Object.defineProperty(exports2, "__esModule", {
  68644. value: true
  68645. });
  68646. exports2.hasFloat16ArrayBrand = hasFloat16ArrayBrand;
  68647. var _is = require_is();
  68648. var _messages = require_messages();
  68649. var _primordials = require_primordials();
  68650. var brand = exports2.brand = (0, _primordials.SymbolFor)("__Float16Array__");
  68651. function hasFloat16ArrayBrand(target) {
  68652. if (!(0, _is.isObjectLike)(target)) {
  68653. return false;
  68654. }
  68655. const prototype = (0, _primordials.ReflectGetPrototypeOf)(target);
  68656. if (!(0, _is.isObjectLike)(prototype)) {
  68657. return false;
  68658. }
  68659. const constructor = prototype.constructor;
  68660. if (constructor === void 0) {
  68661. return false;
  68662. }
  68663. if (!(0, _is.isObject)(constructor)) {
  68664. throw (0, _primordials.NativeTypeError)(_messages.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
  68665. }
  68666. return (0, _primordials.ReflectHas)(constructor, brand);
  68667. }
  68668. }
  68669. });
  68670. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/converter.cjs
  68671. var require_converter = __commonJS({
  68672. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/converter.cjs"(exports2) {
  68673. "use strict";
  68674. Object.defineProperty(exports2, "__esModule", {
  68675. value: true
  68676. });
  68677. exports2.convertToNumber = convertToNumber;
  68678. exports2.roundToFloat16 = roundToFloat16;
  68679. exports2.roundToFloat16Bits = roundToFloat16Bits;
  68680. var _primordials = require_primordials();
  68681. var INVERSE_OF_EPSILON = 1 / _primordials.EPSILON;
  68682. function roundTiesToEven(num) {
  68683. return num + INVERSE_OF_EPSILON - INVERSE_OF_EPSILON;
  68684. }
  68685. var FLOAT16_MIN_VALUE = 6103515625e-14;
  68686. var FLOAT16_MAX_VALUE = 65504;
  68687. var FLOAT16_EPSILON = 9765625e-10;
  68688. var FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE = FLOAT16_EPSILON * FLOAT16_MIN_VALUE;
  68689. var FLOAT16_EPSILON_DEVIDED_BY_EPSILON = FLOAT16_EPSILON * INVERSE_OF_EPSILON;
  68690. function roundToFloat16(num) {
  68691. const number2 = +num;
  68692. if (!(0, _primordials.NumberIsFinite)(number2) || number2 === 0) {
  68693. return number2;
  68694. }
  68695. const sign = number2 > 0 ? 1 : -1;
  68696. const absolute = (0, _primordials.MathAbs)(number2);
  68697. if (absolute < FLOAT16_MIN_VALUE) {
  68698. return sign * roundTiesToEven(absolute / FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE) * FLOAT16_EPSILON_MULTIPLIED_BY_FLOAT16_MIN_VALUE;
  68699. }
  68700. const temp = (1 + FLOAT16_EPSILON_DEVIDED_BY_EPSILON) * absolute;
  68701. const result = temp - (temp - absolute);
  68702. if (result > FLOAT16_MAX_VALUE || (0, _primordials.NumberIsNaN)(result)) {
  68703. return sign * Infinity;
  68704. }
  68705. return sign * result;
  68706. }
  68707. var buffer = new _primordials.NativeArrayBuffer(4);
  68708. var floatView = new _primordials.NativeFloat32Array(buffer);
  68709. var uint32View = new _primordials.NativeUint32Array(buffer);
  68710. var baseTable = new _primordials.NativeUint16Array(512);
  68711. var shiftTable = new _primordials.NativeUint8Array(512);
  68712. for (let i4 = 0; i4 < 256; ++i4) {
  68713. const e4 = i4 - 127;
  68714. if (e4 < -24) {
  68715. baseTable[i4] = 0;
  68716. baseTable[i4 | 256] = 32768;
  68717. shiftTable[i4] = 24;
  68718. shiftTable[i4 | 256] = 24;
  68719. } else if (e4 < -14) {
  68720. baseTable[i4] = 1024 >> -e4 - 14;
  68721. baseTable[i4 | 256] = 1024 >> -e4 - 14 | 32768;
  68722. shiftTable[i4] = -e4 - 1;
  68723. shiftTable[i4 | 256] = -e4 - 1;
  68724. } else if (e4 <= 15) {
  68725. baseTable[i4] = e4 + 15 << 10;
  68726. baseTable[i4 | 256] = e4 + 15 << 10 | 32768;
  68727. shiftTable[i4] = 13;
  68728. shiftTable[i4 | 256] = 13;
  68729. } else if (e4 < 128) {
  68730. baseTable[i4] = 31744;
  68731. baseTable[i4 | 256] = 64512;
  68732. shiftTable[i4] = 24;
  68733. shiftTable[i4 | 256] = 24;
  68734. } else {
  68735. baseTable[i4] = 31744;
  68736. baseTable[i4 | 256] = 64512;
  68737. shiftTable[i4] = 13;
  68738. shiftTable[i4 | 256] = 13;
  68739. }
  68740. }
  68741. function roundToFloat16Bits(num) {
  68742. floatView[0] = roundToFloat16(num);
  68743. const f5 = uint32View[0];
  68744. const e4 = f5 >> 23 & 511;
  68745. return baseTable[e4] + ((f5 & 8388607) >> shiftTable[e4]);
  68746. }
  68747. var mantissaTable = new _primordials.NativeUint32Array(2048);
  68748. for (let i4 = 1; i4 < 1024; ++i4) {
  68749. let m4 = i4 << 13;
  68750. let e4 = 0;
  68751. while ((m4 & 8388608) === 0) {
  68752. m4 <<= 1;
  68753. e4 -= 8388608;
  68754. }
  68755. m4 &= ~8388608;
  68756. e4 += 947912704;
  68757. mantissaTable[i4] = m4 | e4;
  68758. }
  68759. for (let i4 = 1024; i4 < 2048; ++i4) {
  68760. mantissaTable[i4] = 939524096 + (i4 - 1024 << 13);
  68761. }
  68762. var exponentTable = new _primordials.NativeUint32Array(64);
  68763. for (let i4 = 1; i4 < 31; ++i4) {
  68764. exponentTable[i4] = i4 << 23;
  68765. }
  68766. exponentTable[31] = 1199570944;
  68767. exponentTable[32] = 2147483648;
  68768. for (let i4 = 33; i4 < 63; ++i4) {
  68769. exponentTable[i4] = 2147483648 + (i4 - 32 << 23);
  68770. }
  68771. exponentTable[63] = 3347054592;
  68772. var offsetTable = new _primordials.NativeUint16Array(64);
  68773. for (let i4 = 1; i4 < 64; ++i4) {
  68774. if (i4 !== 32) {
  68775. offsetTable[i4] = 1024;
  68776. }
  68777. }
  68778. function convertToNumber(float16bits) {
  68779. const i4 = float16bits >> 10;
  68780. uint32View[0] = mantissaTable[offsetTable[i4] + (float16bits & 1023)] + exponentTable[i4];
  68781. return floatView[0];
  68782. }
  68783. }
  68784. });
  68785. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/spec.cjs
  68786. var require_spec = __commonJS({
  68787. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/_util/spec.cjs"(exports2) {
  68788. "use strict";
  68789. Object.defineProperty(exports2, "__esModule", {
  68790. value: true
  68791. });
  68792. exports2.IsDetachedBuffer = IsDetachedBuffer;
  68793. exports2.SpeciesConstructor = SpeciesConstructor;
  68794. exports2.ToIntegerOrInfinity = ToIntegerOrInfinity;
  68795. exports2.ToLength = ToLength;
  68796. exports2.defaultCompare = defaultCompare;
  68797. var _is = require_is();
  68798. var _messages = require_messages();
  68799. var _primordials = require_primordials();
  68800. function ToIntegerOrInfinity(target) {
  68801. const number2 = +target;
  68802. if ((0, _primordials.NumberIsNaN)(number2) || number2 === 0) {
  68803. return 0;
  68804. }
  68805. return (0, _primordials.MathTrunc)(number2);
  68806. }
  68807. function ToLength(target) {
  68808. const length = ToIntegerOrInfinity(target);
  68809. if (length < 0) {
  68810. return 0;
  68811. }
  68812. return length < _primordials.MAX_SAFE_INTEGER ? length : _primordials.MAX_SAFE_INTEGER;
  68813. }
  68814. function SpeciesConstructor(target, defaultConstructor) {
  68815. if (!(0, _is.isObject)(target)) {
  68816. throw (0, _primordials.NativeTypeError)(_messages.THIS_IS_NOT_AN_OBJECT);
  68817. }
  68818. const constructor = target.constructor;
  68819. if (constructor === void 0) {
  68820. return defaultConstructor;
  68821. }
  68822. if (!(0, _is.isObject)(constructor)) {
  68823. throw (0, _primordials.NativeTypeError)(_messages.THE_CONSTRUCTOR_PROPERTY_VALUE_IS_NOT_AN_OBJECT);
  68824. }
  68825. const species = constructor[_primordials.SymbolSpecies];
  68826. if (species == null) {
  68827. return defaultConstructor;
  68828. }
  68829. return species;
  68830. }
  68831. function IsDetachedBuffer(buffer) {
  68832. if ((0, _is.isSharedArrayBuffer)(buffer)) {
  68833. return false;
  68834. }
  68835. try {
  68836. (0, _primordials.ArrayBufferPrototypeSlice)(buffer, 0, 0);
  68837. return false;
  68838. } catch (e4) {
  68839. }
  68840. return true;
  68841. }
  68842. function defaultCompare(x4, y2) {
  68843. const isXNaN = (0, _primordials.NumberIsNaN)(x4);
  68844. const isYNaN = (0, _primordials.NumberIsNaN)(y2);
  68845. if (isXNaN && isYNaN) {
  68846. return 0;
  68847. }
  68848. if (isXNaN) {
  68849. return 1;
  68850. }
  68851. if (isYNaN) {
  68852. return -1;
  68853. }
  68854. if (x4 < y2) {
  68855. return -1;
  68856. }
  68857. if (x4 > y2) {
  68858. return 1;
  68859. }
  68860. if (x4 === 0 && y2 === 0) {
  68861. const isXPlusZero = (0, _primordials.ObjectIs)(x4, 0);
  68862. const isYPlusZero = (0, _primordials.ObjectIs)(y2, 0);
  68863. if (!isXPlusZero && isYPlusZero) {
  68864. return -1;
  68865. }
  68866. if (isXPlusZero && !isYPlusZero) {
  68867. return 1;
  68868. }
  68869. }
  68870. return 0;
  68871. }
  68872. }
  68873. });
  68874. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/Float16Array.cjs
  68875. var require_Float16Array = __commonJS({
  68876. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/Float16Array.cjs"(exports2) {
  68877. "use strict";
  68878. Object.defineProperty(exports2, "__esModule", {
  68879. value: true
  68880. });
  68881. exports2.isFloat16Array = isFloat16Array;
  68882. var _arrayIterator = require_arrayIterator();
  68883. var _brand = require_brand();
  68884. var _converter = require_converter();
  68885. var _is = require_is();
  68886. var _messages = require_messages();
  68887. var _primordials = require_primordials();
  68888. var _spec = require_spec();
  68889. var BYTES_PER_ELEMENT = 2;
  68890. var float16bitsArrays = new _primordials.NativeWeakMap();
  68891. function isFloat16Array(target) {
  68892. return (0, _primordials.WeakMapPrototypeHas)(float16bitsArrays, target) || !(0, _primordials.ArrayBufferIsView)(target) && (0, _brand.hasFloat16ArrayBrand)(target);
  68893. }
  68894. function assertFloat16Array(target) {
  68895. if (!isFloat16Array(target)) {
  68896. throw (0, _primordials.NativeTypeError)(_messages.THIS_IS_NOT_A_FLOAT16ARRAY_OBJECT);
  68897. }
  68898. }
  68899. function assertSpeciesTypedArray(target, count) {
  68900. const isTargetFloat16Array = isFloat16Array(target);
  68901. const isTargetTypedArray = (0, _is.isNativeTypedArray)(target);
  68902. if (!isTargetFloat16Array && !isTargetTypedArray) {
  68903. throw (0, _primordials.NativeTypeError)(_messages.SPECIES_CONSTRUCTOR_DIDNT_RETURN_TYPEDARRAY_OBJECT);
  68904. }
  68905. if (typeof count === "number") {
  68906. let length;
  68907. if (isTargetFloat16Array) {
  68908. const float16bitsArray = getFloat16BitsArray(target);
  68909. length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  68910. } else {
  68911. length = (0, _primordials.TypedArrayPrototypeGetLength)(target);
  68912. }
  68913. if (length < count) {
  68914. throw (0, _primordials.NativeTypeError)(_messages.DERIVED_CONSTRUCTOR_CREATED_TYPEDARRAY_OBJECT_WHICH_WAS_TOO_SMALL_LENGTH);
  68915. }
  68916. }
  68917. if ((0, _is.isNativeBigIntTypedArray)(target)) {
  68918. throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
  68919. }
  68920. }
  68921. function getFloat16BitsArray(float16) {
  68922. const float16bitsArray = (0, _primordials.WeakMapPrototypeGet)(float16bitsArrays, float16);
  68923. if (float16bitsArray !== void 0) {
  68924. const buffer2 = (0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray);
  68925. if ((0, _spec.IsDetachedBuffer)(buffer2)) {
  68926. throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
  68927. }
  68928. return float16bitsArray;
  68929. }
  68930. const buffer = float16.buffer;
  68931. if ((0, _spec.IsDetachedBuffer)(buffer)) {
  68932. throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
  68933. }
  68934. const cloned = (0, _primordials.ReflectConstruct)(Float16Array, [buffer, float16.byteOffset, float16.length], float16.constructor);
  68935. return (0, _primordials.WeakMapPrototypeGet)(float16bitsArrays, cloned);
  68936. }
  68937. function copyToArray(float16bitsArray) {
  68938. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  68939. const array2 = [];
  68940. for (let i4 = 0; i4 < length; ++i4) {
  68941. array2[i4] = (0, _converter.convertToNumber)(float16bitsArray[i4]);
  68942. }
  68943. return array2;
  68944. }
  68945. var TypedArrayPrototypeGetters = new _primordials.NativeWeakSet();
  68946. for (const key of (0, _primordials.ReflectOwnKeys)(_primordials.TypedArrayPrototype)) {
  68947. if (key === _primordials.SymbolToStringTag) {
  68948. continue;
  68949. }
  68950. const descriptor = (0, _primordials.ReflectGetOwnPropertyDescriptor)(_primordials.TypedArrayPrototype, key);
  68951. if ((0, _primordials.ObjectHasOwn)(descriptor, "get") && typeof descriptor.get === "function") {
  68952. (0, _primordials.WeakSetPrototypeAdd)(TypedArrayPrototypeGetters, descriptor.get);
  68953. }
  68954. }
  68955. var handler = (0, _primordials.ObjectFreeze)({
  68956. get(target, key, receiver) {
  68957. if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
  68958. return (0, _converter.convertToNumber)((0, _primordials.ReflectGet)(target, key));
  68959. }
  68960. if ((0, _primordials.WeakSetPrototypeHas)(TypedArrayPrototypeGetters, (0, _primordials.ObjectPrototype__lookupGetter__)(target, key))) {
  68961. return (0, _primordials.ReflectGet)(target, key);
  68962. }
  68963. return (0, _primordials.ReflectGet)(target, key, receiver);
  68964. },
  68965. set(target, key, value, receiver) {
  68966. if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
  68967. return (0, _primordials.ReflectSet)(target, key, (0, _converter.roundToFloat16Bits)(value));
  68968. }
  68969. return (0, _primordials.ReflectSet)(target, key, value, receiver);
  68970. },
  68971. getOwnPropertyDescriptor(target, key) {
  68972. if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key)) {
  68973. const descriptor = (0, _primordials.ReflectGetOwnPropertyDescriptor)(target, key);
  68974. descriptor.value = (0, _converter.convertToNumber)(descriptor.value);
  68975. return descriptor;
  68976. }
  68977. return (0, _primordials.ReflectGetOwnPropertyDescriptor)(target, key);
  68978. },
  68979. defineProperty(target, key, descriptor) {
  68980. if ((0, _is.isCanonicalIntegerIndexString)(key) && (0, _primordials.ObjectHasOwn)(target, key) && (0, _primordials.ObjectHasOwn)(descriptor, "value")) {
  68981. descriptor.value = (0, _converter.roundToFloat16Bits)(descriptor.value);
  68982. return (0, _primordials.ReflectDefineProperty)(target, key, descriptor);
  68983. }
  68984. return (0, _primordials.ReflectDefineProperty)(target, key, descriptor);
  68985. }
  68986. });
  68987. var Float16Array = class _Float16Array {
  68988. constructor(input, _byteOffset, _length) {
  68989. let float16bitsArray;
  68990. if (isFloat16Array(input)) {
  68991. float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [getFloat16BitsArray(input)], new.target);
  68992. } else if ((0, _is.isObject)(input) && !(0, _is.isAnyArrayBuffer)(input)) {
  68993. let list;
  68994. let length;
  68995. if ((0, _is.isNativeTypedArray)(input)) {
  68996. list = input;
  68997. length = (0, _primordials.TypedArrayPrototypeGetLength)(input);
  68998. const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(input);
  68999. if ((0, _spec.IsDetachedBuffer)(buffer)) {
  69000. throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
  69001. }
  69002. if ((0, _is.isNativeBigIntTypedArray)(input)) {
  69003. throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
  69004. }
  69005. const data = new _primordials.NativeArrayBuffer(length * BYTES_PER_ELEMENT);
  69006. float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [data], new.target);
  69007. } else {
  69008. const iterator = input[_primordials.SymbolIterator];
  69009. if (iterator != null && typeof iterator !== "function") {
  69010. throw (0, _primordials.NativeTypeError)(_messages.ITERATOR_PROPERTY_IS_NOT_CALLABLE);
  69011. }
  69012. if (iterator != null) {
  69013. if ((0, _is.isOrdinaryArray)(input)) {
  69014. list = input;
  69015. length = input.length;
  69016. } else {
  69017. list = [...input];
  69018. length = list.length;
  69019. }
  69020. } else {
  69021. list = input;
  69022. length = (0, _spec.ToLength)(list.length);
  69023. }
  69024. float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, [length], new.target);
  69025. }
  69026. for (let i4 = 0; i4 < length; ++i4) {
  69027. float16bitsArray[i4] = (0, _converter.roundToFloat16Bits)(list[i4]);
  69028. }
  69029. } else {
  69030. float16bitsArray = (0, _primordials.ReflectConstruct)(_primordials.NativeUint16Array, arguments, new.target);
  69031. }
  69032. const proxy = new _primordials.NativeProxy(float16bitsArray, handler);
  69033. (0, _primordials.WeakMapPrototypeSet)(float16bitsArrays, proxy, float16bitsArray);
  69034. return proxy;
  69035. }
  69036. static from(src, ...opts) {
  69037. const Constructor = this;
  69038. if (!(0, _primordials.ReflectHas)(Constructor, _brand.brand)) {
  69039. throw (0, _primordials.NativeTypeError)(_messages.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY);
  69040. }
  69041. if (Constructor === _Float16Array) {
  69042. if (isFloat16Array(src) && opts.length === 0) {
  69043. const float16bitsArray = getFloat16BitsArray(src);
  69044. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  69045. return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
  69046. }
  69047. if (opts.length === 0) {
  69048. return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.Uint16ArrayFrom)(src, _converter.roundToFloat16Bits)));
  69049. }
  69050. const mapFunc = opts[0];
  69051. const thisArg = opts[1];
  69052. return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.Uint16ArrayFrom)(src, function(val2, ...args) {
  69053. return (0, _converter.roundToFloat16Bits)((0, _primordials.ReflectApply)(mapFunc, this, [val2, ...(0, _arrayIterator.safeIfNeeded)(args)]));
  69054. }, thisArg)));
  69055. }
  69056. let list;
  69057. let length;
  69058. const iterator = src[_primordials.SymbolIterator];
  69059. if (iterator != null && typeof iterator !== "function") {
  69060. throw (0, _primordials.NativeTypeError)(_messages.ITERATOR_PROPERTY_IS_NOT_CALLABLE);
  69061. }
  69062. if (iterator != null) {
  69063. if ((0, _is.isOrdinaryArray)(src)) {
  69064. list = src;
  69065. length = src.length;
  69066. } else if ((0, _is.isOrdinaryNativeTypedArray)(src)) {
  69067. list = src;
  69068. length = (0, _primordials.TypedArrayPrototypeGetLength)(src);
  69069. } else {
  69070. list = [...src];
  69071. length = list.length;
  69072. }
  69073. } else {
  69074. if (src == null) {
  69075. throw (0, _primordials.NativeTypeError)(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
  69076. }
  69077. list = (0, _primordials.NativeObject)(src);
  69078. length = (0, _spec.ToLength)(list.length);
  69079. }
  69080. const array2 = new Constructor(length);
  69081. if (opts.length === 0) {
  69082. for (let i4 = 0; i4 < length; ++i4) {
  69083. array2[i4] = list[i4];
  69084. }
  69085. } else {
  69086. const mapFunc = opts[0];
  69087. const thisArg = opts[1];
  69088. for (let i4 = 0; i4 < length; ++i4) {
  69089. array2[i4] = (0, _primordials.ReflectApply)(mapFunc, thisArg, [list[i4], i4]);
  69090. }
  69091. }
  69092. return array2;
  69093. }
  69094. static of(...items) {
  69095. const Constructor = this;
  69096. if (!(0, _primordials.ReflectHas)(Constructor, _brand.brand)) {
  69097. throw (0, _primordials.NativeTypeError)(_messages.THIS_CONSTRUCTOR_IS_NOT_A_SUBCLASS_OF_FLOAT16ARRAY);
  69098. }
  69099. const length = items.length;
  69100. if (Constructor === _Float16Array) {
  69101. const proxy = new _Float16Array(length);
  69102. const float16bitsArray = getFloat16BitsArray(proxy);
  69103. for (let i4 = 0; i4 < length; ++i4) {
  69104. float16bitsArray[i4] = (0, _converter.roundToFloat16Bits)(items[i4]);
  69105. }
  69106. return proxy;
  69107. }
  69108. const array2 = new Constructor(length);
  69109. for (let i4 = 0; i4 < length; ++i4) {
  69110. array2[i4] = items[i4];
  69111. }
  69112. return array2;
  69113. }
  69114. keys() {
  69115. assertFloat16Array(this);
  69116. const float16bitsArray = getFloat16BitsArray(this);
  69117. return (0, _primordials.TypedArrayPrototypeKeys)(float16bitsArray);
  69118. }
  69119. values() {
  69120. assertFloat16Array(this);
  69121. const float16bitsArray = getFloat16BitsArray(this);
  69122. return (0, _arrayIterator.wrap)(function* () {
  69123. for (const val2 of (0, _primordials.TypedArrayPrototypeValues)(float16bitsArray)) {
  69124. yield (0, _converter.convertToNumber)(val2);
  69125. }
  69126. }());
  69127. }
  69128. entries() {
  69129. assertFloat16Array(this);
  69130. const float16bitsArray = getFloat16BitsArray(this);
  69131. return (0, _arrayIterator.wrap)(function* () {
  69132. for (const [i4, val2] of (0, _primordials.TypedArrayPrototypeEntries)(float16bitsArray)) {
  69133. yield [i4, (0, _converter.convertToNumber)(val2)];
  69134. }
  69135. }());
  69136. }
  69137. at(index6) {
  69138. assertFloat16Array(this);
  69139. const float16bitsArray = getFloat16BitsArray(this);
  69140. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69141. const relativeIndex = (0, _spec.ToIntegerOrInfinity)(index6);
  69142. const k3 = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;
  69143. if (k3 < 0 || k3 >= length) {
  69144. return;
  69145. }
  69146. return (0, _converter.convertToNumber)(float16bitsArray[k3]);
  69147. }
  69148. with(index6, value) {
  69149. assertFloat16Array(this);
  69150. const float16bitsArray = getFloat16BitsArray(this);
  69151. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69152. const relativeIndex = (0, _spec.ToIntegerOrInfinity)(index6);
  69153. const k3 = relativeIndex >= 0 ? relativeIndex : length + relativeIndex;
  69154. const number2 = +value;
  69155. if (k3 < 0 || k3 >= length) {
  69156. throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
  69157. }
  69158. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  69159. const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
  69160. const array2 = getFloat16BitsArray(cloned);
  69161. array2[k3] = (0, _converter.roundToFloat16Bits)(number2);
  69162. return cloned;
  69163. }
  69164. map(callback, ...opts) {
  69165. assertFloat16Array(this);
  69166. const float16bitsArray = getFloat16BitsArray(this);
  69167. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69168. const thisArg = opts[0];
  69169. const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
  69170. if (Constructor === _Float16Array) {
  69171. const proxy = new _Float16Array(length);
  69172. const array3 = getFloat16BitsArray(proxy);
  69173. for (let i4 = 0; i4 < length; ++i4) {
  69174. const val2 = (0, _converter.convertToNumber)(float16bitsArray[i4]);
  69175. array3[i4] = (0, _converter.roundToFloat16Bits)((0, _primordials.ReflectApply)(callback, thisArg, [val2, i4, this]));
  69176. }
  69177. return proxy;
  69178. }
  69179. const array2 = new Constructor(length);
  69180. assertSpeciesTypedArray(array2, length);
  69181. for (let i4 = 0; i4 < length; ++i4) {
  69182. const val2 = (0, _converter.convertToNumber)(float16bitsArray[i4]);
  69183. array2[i4] = (0, _primordials.ReflectApply)(callback, thisArg, [val2, i4, this]);
  69184. }
  69185. return array2;
  69186. }
  69187. filter(callback, ...opts) {
  69188. assertFloat16Array(this);
  69189. const float16bitsArray = getFloat16BitsArray(this);
  69190. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69191. const thisArg = opts[0];
  69192. const kept = [];
  69193. for (let i4 = 0; i4 < length; ++i4) {
  69194. const val2 = (0, _converter.convertToNumber)(float16bitsArray[i4]);
  69195. if ((0, _primordials.ReflectApply)(callback, thisArg, [val2, i4, this])) {
  69196. (0, _primordials.ArrayPrototypePush)(kept, val2);
  69197. }
  69198. }
  69199. const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
  69200. const array2 = new Constructor(kept);
  69201. assertSpeciesTypedArray(array2);
  69202. return array2;
  69203. }
  69204. reduce(callback, ...opts) {
  69205. assertFloat16Array(this);
  69206. const float16bitsArray = getFloat16BitsArray(this);
  69207. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69208. if (length === 0 && opts.length === 0) {
  69209. throw (0, _primordials.NativeTypeError)(_messages.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE);
  69210. }
  69211. let accumulator, start;
  69212. if (opts.length === 0) {
  69213. accumulator = (0, _converter.convertToNumber)(float16bitsArray[0]);
  69214. start = 1;
  69215. } else {
  69216. accumulator = opts[0];
  69217. start = 0;
  69218. }
  69219. for (let i4 = start; i4 < length; ++i4) {
  69220. accumulator = callback(accumulator, (0, _converter.convertToNumber)(float16bitsArray[i4]), i4, this);
  69221. }
  69222. return accumulator;
  69223. }
  69224. reduceRight(callback, ...opts) {
  69225. assertFloat16Array(this);
  69226. const float16bitsArray = getFloat16BitsArray(this);
  69227. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69228. if (length === 0 && opts.length === 0) {
  69229. throw (0, _primordials.NativeTypeError)(_messages.REDUCE_OF_EMPTY_ARRAY_WITH_NO_INITIAL_VALUE);
  69230. }
  69231. let accumulator, start;
  69232. if (opts.length === 0) {
  69233. accumulator = (0, _converter.convertToNumber)(float16bitsArray[length - 1]);
  69234. start = length - 2;
  69235. } else {
  69236. accumulator = opts[0];
  69237. start = length - 1;
  69238. }
  69239. for (let i4 = start; i4 >= 0; --i4) {
  69240. accumulator = callback(accumulator, (0, _converter.convertToNumber)(float16bitsArray[i4]), i4, this);
  69241. }
  69242. return accumulator;
  69243. }
  69244. forEach(callback, ...opts) {
  69245. assertFloat16Array(this);
  69246. const float16bitsArray = getFloat16BitsArray(this);
  69247. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69248. const thisArg = opts[0];
  69249. for (let i4 = 0; i4 < length; ++i4) {
  69250. (0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i4]), i4, this]);
  69251. }
  69252. }
  69253. find(callback, ...opts) {
  69254. assertFloat16Array(this);
  69255. const float16bitsArray = getFloat16BitsArray(this);
  69256. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69257. const thisArg = opts[0];
  69258. for (let i4 = 0; i4 < length; ++i4) {
  69259. const value = (0, _converter.convertToNumber)(float16bitsArray[i4]);
  69260. if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i4, this])) {
  69261. return value;
  69262. }
  69263. }
  69264. }
  69265. findIndex(callback, ...opts) {
  69266. assertFloat16Array(this);
  69267. const float16bitsArray = getFloat16BitsArray(this);
  69268. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69269. const thisArg = opts[0];
  69270. for (let i4 = 0; i4 < length; ++i4) {
  69271. const value = (0, _converter.convertToNumber)(float16bitsArray[i4]);
  69272. if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i4, this])) {
  69273. return i4;
  69274. }
  69275. }
  69276. return -1;
  69277. }
  69278. findLast(callback, ...opts) {
  69279. assertFloat16Array(this);
  69280. const float16bitsArray = getFloat16BitsArray(this);
  69281. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69282. const thisArg = opts[0];
  69283. for (let i4 = length - 1; i4 >= 0; --i4) {
  69284. const value = (0, _converter.convertToNumber)(float16bitsArray[i4]);
  69285. if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i4, this])) {
  69286. return value;
  69287. }
  69288. }
  69289. }
  69290. findLastIndex(callback, ...opts) {
  69291. assertFloat16Array(this);
  69292. const float16bitsArray = getFloat16BitsArray(this);
  69293. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69294. const thisArg = opts[0];
  69295. for (let i4 = length - 1; i4 >= 0; --i4) {
  69296. const value = (0, _converter.convertToNumber)(float16bitsArray[i4]);
  69297. if ((0, _primordials.ReflectApply)(callback, thisArg, [value, i4, this])) {
  69298. return i4;
  69299. }
  69300. }
  69301. return -1;
  69302. }
  69303. every(callback, ...opts) {
  69304. assertFloat16Array(this);
  69305. const float16bitsArray = getFloat16BitsArray(this);
  69306. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69307. const thisArg = opts[0];
  69308. for (let i4 = 0; i4 < length; ++i4) {
  69309. if (!(0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i4]), i4, this])) {
  69310. return false;
  69311. }
  69312. }
  69313. return true;
  69314. }
  69315. some(callback, ...opts) {
  69316. assertFloat16Array(this);
  69317. const float16bitsArray = getFloat16BitsArray(this);
  69318. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69319. const thisArg = opts[0];
  69320. for (let i4 = 0; i4 < length; ++i4) {
  69321. if ((0, _primordials.ReflectApply)(callback, thisArg, [(0, _converter.convertToNumber)(float16bitsArray[i4]), i4, this])) {
  69322. return true;
  69323. }
  69324. }
  69325. return false;
  69326. }
  69327. set(input, ...opts) {
  69328. assertFloat16Array(this);
  69329. const float16bitsArray = getFloat16BitsArray(this);
  69330. const targetOffset = (0, _spec.ToIntegerOrInfinity)(opts[0]);
  69331. if (targetOffset < 0) {
  69332. throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
  69333. }
  69334. if (input == null) {
  69335. throw (0, _primordials.NativeTypeError)(_messages.CANNOT_CONVERT_UNDEFINED_OR_NULL_TO_OBJECT);
  69336. }
  69337. if ((0, _is.isNativeBigIntTypedArray)(input)) {
  69338. throw (0, _primordials.NativeTypeError)(_messages.CANNOT_MIX_BIGINT_AND_OTHER_TYPES);
  69339. }
  69340. if (isFloat16Array(input)) {
  69341. return (0, _primordials.TypedArrayPrototypeSet)(getFloat16BitsArray(this), getFloat16BitsArray(input), targetOffset);
  69342. }
  69343. if ((0, _is.isNativeTypedArray)(input)) {
  69344. const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(input);
  69345. if ((0, _spec.IsDetachedBuffer)(buffer)) {
  69346. throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
  69347. }
  69348. }
  69349. const targetLength = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69350. const src = (0, _primordials.NativeObject)(input);
  69351. const srcLength = (0, _spec.ToLength)(src.length);
  69352. if (targetOffset === Infinity || srcLength + targetOffset > targetLength) {
  69353. throw (0, _primordials.NativeRangeError)(_messages.OFFSET_IS_OUT_OF_BOUNDS);
  69354. }
  69355. for (let i4 = 0; i4 < srcLength; ++i4) {
  69356. float16bitsArray[i4 + targetOffset] = (0, _converter.roundToFloat16Bits)(src[i4]);
  69357. }
  69358. }
  69359. reverse() {
  69360. assertFloat16Array(this);
  69361. const float16bitsArray = getFloat16BitsArray(this);
  69362. (0, _primordials.TypedArrayPrototypeReverse)(float16bitsArray);
  69363. return this;
  69364. }
  69365. toReversed() {
  69366. assertFloat16Array(this);
  69367. const float16bitsArray = getFloat16BitsArray(this);
  69368. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  69369. const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
  69370. const clonedFloat16bitsArray = getFloat16BitsArray(cloned);
  69371. (0, _primordials.TypedArrayPrototypeReverse)(clonedFloat16bitsArray);
  69372. return cloned;
  69373. }
  69374. fill(value, ...opts) {
  69375. assertFloat16Array(this);
  69376. const float16bitsArray = getFloat16BitsArray(this);
  69377. (0, _primordials.TypedArrayPrototypeFill)(float16bitsArray, (0, _converter.roundToFloat16Bits)(value), ...(0, _arrayIterator.safeIfNeeded)(opts));
  69378. return this;
  69379. }
  69380. copyWithin(target, start, ...opts) {
  69381. assertFloat16Array(this);
  69382. const float16bitsArray = getFloat16BitsArray(this);
  69383. (0, _primordials.TypedArrayPrototypeCopyWithin)(float16bitsArray, target, start, ...(0, _arrayIterator.safeIfNeeded)(opts));
  69384. return this;
  69385. }
  69386. sort(compareFn) {
  69387. assertFloat16Array(this);
  69388. const float16bitsArray = getFloat16BitsArray(this);
  69389. const sortCompare = compareFn !== void 0 ? compareFn : _spec.defaultCompare;
  69390. (0, _primordials.TypedArrayPrototypeSort)(float16bitsArray, (x4, y2) => {
  69391. return sortCompare((0, _converter.convertToNumber)(x4), (0, _converter.convertToNumber)(y2));
  69392. });
  69393. return this;
  69394. }
  69395. toSorted(compareFn) {
  69396. assertFloat16Array(this);
  69397. const float16bitsArray = getFloat16BitsArray(this);
  69398. if (compareFn !== void 0 && typeof compareFn !== "function") {
  69399. throw new _primordials.NativeTypeError(_messages.THE_COMPARISON_FUNCTION_MUST_BE_EITHER_A_FUNCTION_OR_UNDEFINED);
  69400. }
  69401. const sortCompare = compareFn !== void 0 ? compareFn : _spec.defaultCompare;
  69402. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  69403. const cloned = new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16)));
  69404. const clonedFloat16bitsArray = getFloat16BitsArray(cloned);
  69405. (0, _primordials.TypedArrayPrototypeSort)(clonedFloat16bitsArray, (x4, y2) => {
  69406. return sortCompare((0, _converter.convertToNumber)(x4), (0, _converter.convertToNumber)(y2));
  69407. });
  69408. return cloned;
  69409. }
  69410. slice(start, end) {
  69411. assertFloat16Array(this);
  69412. const float16bitsArray = getFloat16BitsArray(this);
  69413. const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
  69414. if (Constructor === _Float16Array) {
  69415. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  69416. return new _Float16Array((0, _primordials.TypedArrayPrototypeGetBuffer)((0, _primordials.TypedArrayPrototypeSlice)(uint16, start, end)));
  69417. }
  69418. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69419. const relativeStart = (0, _spec.ToIntegerOrInfinity)(start);
  69420. const relativeEnd = end === void 0 ? length : (0, _spec.ToIntegerOrInfinity)(end);
  69421. let k3;
  69422. if (relativeStart === -Infinity) {
  69423. k3 = 0;
  69424. } else if (relativeStart < 0) {
  69425. k3 = length + relativeStart > 0 ? length + relativeStart : 0;
  69426. } else {
  69427. k3 = length < relativeStart ? length : relativeStart;
  69428. }
  69429. let final;
  69430. if (relativeEnd === -Infinity) {
  69431. final = 0;
  69432. } else if (relativeEnd < 0) {
  69433. final = length + relativeEnd > 0 ? length + relativeEnd : 0;
  69434. } else {
  69435. final = length < relativeEnd ? length : relativeEnd;
  69436. }
  69437. const count = final - k3 > 0 ? final - k3 : 0;
  69438. const array2 = new Constructor(count);
  69439. assertSpeciesTypedArray(array2, count);
  69440. if (count === 0) {
  69441. return array2;
  69442. }
  69443. const buffer = (0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray);
  69444. if ((0, _spec.IsDetachedBuffer)(buffer)) {
  69445. throw (0, _primordials.NativeTypeError)(_messages.ATTEMPTING_TO_ACCESS_DETACHED_ARRAYBUFFER);
  69446. }
  69447. let n3 = 0;
  69448. while (k3 < final) {
  69449. array2[n3] = (0, _converter.convertToNumber)(float16bitsArray[k3]);
  69450. ++k3;
  69451. ++n3;
  69452. }
  69453. return array2;
  69454. }
  69455. subarray(begin, end) {
  69456. assertFloat16Array(this);
  69457. const float16bitsArray = getFloat16BitsArray(this);
  69458. const Constructor = (0, _spec.SpeciesConstructor)(float16bitsArray, _Float16Array);
  69459. const uint16 = new _primordials.NativeUint16Array((0, _primordials.TypedArrayPrototypeGetBuffer)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(float16bitsArray), (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray));
  69460. const uint16Subarray = (0, _primordials.TypedArrayPrototypeSubarray)(uint16, begin, end);
  69461. const array2 = new Constructor((0, _primordials.TypedArrayPrototypeGetBuffer)(uint16Subarray), (0, _primordials.TypedArrayPrototypeGetByteOffset)(uint16Subarray), (0, _primordials.TypedArrayPrototypeGetLength)(uint16Subarray));
  69462. assertSpeciesTypedArray(array2);
  69463. return array2;
  69464. }
  69465. indexOf(element, ...opts) {
  69466. assertFloat16Array(this);
  69467. const float16bitsArray = getFloat16BitsArray(this);
  69468. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69469. let from = (0, _spec.ToIntegerOrInfinity)(opts[0]);
  69470. if (from === Infinity) {
  69471. return -1;
  69472. }
  69473. if (from < 0) {
  69474. from += length;
  69475. if (from < 0) {
  69476. from = 0;
  69477. }
  69478. }
  69479. for (let i4 = from; i4 < length; ++i4) {
  69480. if ((0, _primordials.ObjectHasOwn)(float16bitsArray, i4) && (0, _converter.convertToNumber)(float16bitsArray[i4]) === element) {
  69481. return i4;
  69482. }
  69483. }
  69484. return -1;
  69485. }
  69486. lastIndexOf(element, ...opts) {
  69487. assertFloat16Array(this);
  69488. const float16bitsArray = getFloat16BitsArray(this);
  69489. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69490. let from = opts.length >= 1 ? (0, _spec.ToIntegerOrInfinity)(opts[0]) : length - 1;
  69491. if (from === -Infinity) {
  69492. return -1;
  69493. }
  69494. if (from >= 0) {
  69495. from = from < length - 1 ? from : length - 1;
  69496. } else {
  69497. from += length;
  69498. }
  69499. for (let i4 = from; i4 >= 0; --i4) {
  69500. if ((0, _primordials.ObjectHasOwn)(float16bitsArray, i4) && (0, _converter.convertToNumber)(float16bitsArray[i4]) === element) {
  69501. return i4;
  69502. }
  69503. }
  69504. return -1;
  69505. }
  69506. includes(element, ...opts) {
  69507. assertFloat16Array(this);
  69508. const float16bitsArray = getFloat16BitsArray(this);
  69509. const length = (0, _primordials.TypedArrayPrototypeGetLength)(float16bitsArray);
  69510. let from = (0, _spec.ToIntegerOrInfinity)(opts[0]);
  69511. if (from === Infinity) {
  69512. return false;
  69513. }
  69514. if (from < 0) {
  69515. from += length;
  69516. if (from < 0) {
  69517. from = 0;
  69518. }
  69519. }
  69520. const isNaN2 = (0, _primordials.NumberIsNaN)(element);
  69521. for (let i4 = from; i4 < length; ++i4) {
  69522. const value = (0, _converter.convertToNumber)(float16bitsArray[i4]);
  69523. if (isNaN2 && (0, _primordials.NumberIsNaN)(value)) {
  69524. return true;
  69525. }
  69526. if (value === element) {
  69527. return true;
  69528. }
  69529. }
  69530. return false;
  69531. }
  69532. join(separator) {
  69533. assertFloat16Array(this);
  69534. const float16bitsArray = getFloat16BitsArray(this);
  69535. const array2 = copyToArray(float16bitsArray);
  69536. return (0, _primordials.ArrayPrototypeJoin)(array2, separator);
  69537. }
  69538. toLocaleString(...opts) {
  69539. assertFloat16Array(this);
  69540. const float16bitsArray = getFloat16BitsArray(this);
  69541. const array2 = copyToArray(float16bitsArray);
  69542. return (0, _primordials.ArrayPrototypeToLocaleString)(array2, ...(0, _arrayIterator.safeIfNeeded)(opts));
  69543. }
  69544. get [_primordials.SymbolToStringTag]() {
  69545. if (isFloat16Array(this)) {
  69546. return "Float16Array";
  69547. }
  69548. }
  69549. };
  69550. exports2.Float16Array = Float16Array;
  69551. (0, _primordials.ObjectDefineProperty)(Float16Array, "BYTES_PER_ELEMENT", {
  69552. value: BYTES_PER_ELEMENT
  69553. });
  69554. (0, _primordials.ObjectDefineProperty)(Float16Array, _brand.brand, {});
  69555. (0, _primordials.ReflectSetPrototypeOf)(Float16Array, _primordials.TypedArray);
  69556. var Float16ArrayPrototype = Float16Array.prototype;
  69557. (0, _primordials.ObjectDefineProperty)(Float16ArrayPrototype, "BYTES_PER_ELEMENT", {
  69558. value: BYTES_PER_ELEMENT
  69559. });
  69560. (0, _primordials.ObjectDefineProperty)(Float16ArrayPrototype, _primordials.SymbolIterator, {
  69561. value: Float16ArrayPrototype.values,
  69562. writable: true,
  69563. configurable: true
  69564. });
  69565. (0, _primordials.ReflectSetPrototypeOf)(Float16ArrayPrototype, _primordials.TypedArrayPrototype);
  69566. }
  69567. });
  69568. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/isTypedArray.cjs
  69569. var require_isTypedArray = __commonJS({
  69570. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/isTypedArray.cjs"(exports2) {
  69571. "use strict";
  69572. Object.defineProperty(exports2, "__esModule", {
  69573. value: true
  69574. });
  69575. exports2.isTypedArray = isTypedArray;
  69576. var _Float16Array = require_Float16Array();
  69577. var _is = require_is();
  69578. function isTypedArray(target) {
  69579. return (0, _is.isNativeTypedArray)(target) || (0, _Float16Array.isFloat16Array)(target);
  69580. }
  69581. }
  69582. });
  69583. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/DataView.cjs
  69584. var require_DataView = __commonJS({
  69585. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/DataView.cjs"(exports2) {
  69586. "use strict";
  69587. Object.defineProperty(exports2, "__esModule", {
  69588. value: true
  69589. });
  69590. exports2.getFloat16 = getFloat16;
  69591. exports2.setFloat16 = setFloat16;
  69592. var _arrayIterator = require_arrayIterator();
  69593. var _converter = require_converter();
  69594. var _primordials = require_primordials();
  69595. function getFloat16(dataView, byteOffset, ...opts) {
  69596. return (0, _converter.convertToNumber)((0, _primordials.DataViewPrototypeGetUint16)(dataView, byteOffset, ...(0, _arrayIterator.safeIfNeeded)(opts)));
  69597. }
  69598. function setFloat16(dataView, byteOffset, value, ...opts) {
  69599. return (0, _primordials.DataViewPrototypeSetUint16)(dataView, byteOffset, (0, _converter.roundToFloat16Bits)(value), ...(0, _arrayIterator.safeIfNeeded)(opts));
  69600. }
  69601. }
  69602. });
  69603. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/f16round.cjs
  69604. var require_f16round = __commonJS({
  69605. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/f16round.cjs"(exports2) {
  69606. "use strict";
  69607. Object.defineProperty(exports2, "__esModule", {
  69608. value: true
  69609. });
  69610. exports2.f16round = f16round;
  69611. var _converter = require_converter();
  69612. function f16round(x4) {
  69613. return (0, _converter.roundToFloat16)(x4);
  69614. }
  69615. }
  69616. });
  69617. // ../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/index.cjs
  69618. var require_lib2 = __commonJS({
  69619. "../node_modules/.pnpm/@petamoriken+float16@3.9.2/node_modules/@petamoriken/float16/lib/index.cjs"(exports2) {
  69620. "use strict";
  69621. Object.defineProperty(exports2, "__esModule", {
  69622. value: true
  69623. });
  69624. var _Float16Array = require_Float16Array();
  69625. exports2.Float16Array = _Float16Array.Float16Array;
  69626. exports2.isFloat16Array = _Float16Array.isFloat16Array;
  69627. var _isTypedArray = require_isTypedArray();
  69628. exports2.isTypedArray = _isTypedArray.isTypedArray;
  69629. var _DataView = require_DataView();
  69630. exports2.getFloat16 = _DataView.getFloat16;
  69631. exports2.setFloat16 = _DataView.setFloat16;
  69632. var _f16round = require_f16round();
  69633. exports2.f16round = _f16round.f16round;
  69634. exports2.hfround = _f16round.f16round;
  69635. }
  69636. });
  69637. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/utils.js
  69638. var require_utils2 = __commonJS({
  69639. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/utils.js"(exports2) {
  69640. "use strict";
  69641. Object.defineProperty(exports2, "__esModule", { value: true });
  69642. exports2.setFloat16 = exports2.isFloat16Array = exports2.getFloat16 = exports2.Float16Array = void 0;
  69643. exports2.getUniqueId = getUniqueId;
  69644. exports2.sleep = sleep;
  69645. exports2.versionEqual = versionEqual;
  69646. exports2.versionGreaterThan = versionGreaterThan;
  69647. exports2.versionGreaterThanOrEqual = versionGreaterThanOrEqual;
  69648. exports2.getAuthenticatedFetch = getAuthenticatedFetch;
  69649. var float16_1 = require_lib2();
  69650. Object.defineProperty(exports2, "Float16Array", { enumerable: true, get: function() {
  69651. return float16_1.Float16Array;
  69652. } });
  69653. Object.defineProperty(exports2, "getFloat16", { enumerable: true, get: function() {
  69654. return float16_1.getFloat16;
  69655. } });
  69656. Object.defineProperty(exports2, "isFloat16Array", { enumerable: true, get: function() {
  69657. return float16_1.isFloat16Array;
  69658. } });
  69659. Object.defineProperty(exports2, "setFloat16", { enumerable: true, get: function() {
  69660. return float16_1.setFloat16;
  69661. } });
  69662. var idCounter = {};
  69663. function getUniqueId(prefix2 = "") {
  69664. if (!idCounter[prefix2]) {
  69665. idCounter[prefix2] = 0;
  69666. }
  69667. const id = ++idCounter[prefix2];
  69668. return `_gel_${prefix2}_${id.toString(16)}_`;
  69669. }
  69670. function sleep(durationMillis) {
  69671. return new Promise((accept) => {
  69672. setTimeout(() => accept(), durationMillis);
  69673. });
  69674. }
  69675. function versionEqual(left, right) {
  69676. return left[0] === right[0] && left[1] === right[1];
  69677. }
  69678. function versionGreaterThan(left, right) {
  69679. if (left[0] > right[0]) {
  69680. return true;
  69681. }
  69682. if (left[0] < right[0]) {
  69683. return false;
  69684. }
  69685. return left[1] > right[1];
  69686. }
  69687. function versionGreaterThanOrEqual(left, right) {
  69688. if (left[0] === right[0] && left[1] === right[1]) {
  69689. return true;
  69690. }
  69691. return versionGreaterThan(left, right);
  69692. }
  69693. var _tokens = /* @__PURE__ */ new WeakMap();
  69694. async function getAuthenticatedFetch(config, httpSCRAMAuth, basePath) {
  69695. let token = config.secretKey ?? _tokens.get(config);
  69696. const { address, tlsSecurity, database } = config;
  69697. const protocol = tlsSecurity === "insecure" ? "http" : "https";
  69698. const baseUrl = `${protocol}://${address[0]}:${address[1]}`;
  69699. const databaseUrl = `${baseUrl}/db/${database}/${basePath ?? ""}`;
  69700. if (!token && config.password != null) {
  69701. token = await httpSCRAMAuth(baseUrl, config.user, config.password);
  69702. _tokens.set(config, token);
  69703. }
  69704. return (input, init2) => {
  69705. let path4;
  69706. if (typeof input === "string") {
  69707. path4 = input;
  69708. } else if (input instanceof Request) {
  69709. path4 = input.url;
  69710. } else
  69711. path4 = input.toString();
  69712. const url = new URL(path4, databaseUrl);
  69713. const headers = new Headers(init2 == null ? void 0 : init2.headers);
  69714. if (config.user !== void 0) {
  69715. headers.append("X-EdgeDB-User", config.user);
  69716. }
  69717. if (token !== void 0) {
  69718. headers.append("Authorization", `Bearer ${token}`);
  69719. }
  69720. return fetch(url, {
  69721. ...init2,
  69722. headers
  69723. });
  69724. };
  69725. }
  69726. }
  69727. });
  69728. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/pgvector.js
  69729. var require_pgvector = __commonJS({
  69730. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/pgvector.js"(exports2) {
  69731. "use strict";
  69732. Object.defineProperty(exports2, "__esModule", { value: true });
  69733. exports2.SparseVector = void 0;
  69734. var SparseVector = class {
  69735. length;
  69736. indexes;
  69737. values;
  69738. constructor(length, indexesOrMap, values) {
  69739. this.length = length;
  69740. if (indexesOrMap instanceof Uint32Array) {
  69741. if (indexesOrMap.length !== (values == null ? void 0 : values.length)) {
  69742. throw new Error("indexes array must be the same length as the data array");
  69743. }
  69744. if (indexesOrMap.length > length) {
  69745. throw new Error("length of data cannot be larger than length of sparse vector");
  69746. }
  69747. this.values = values;
  69748. this.indexes = indexesOrMap;
  69749. } else {
  69750. const entries = Object.entries(indexesOrMap);
  69751. if (entries.length > length) {
  69752. throw new Error("length of data cannot be larger than length of sparse vector");
  69753. }
  69754. this.indexes = new Uint32Array(entries.length);
  69755. this.values = new Float32Array(entries.length);
  69756. for (let i4 = 0; i4 < entries.length; i4++) {
  69757. const index6 = parseInt(entries[i4][0], 10);
  69758. const val2 = entries[i4][1];
  69759. if (Number.isNaN(index6)) {
  69760. throw new Error(`key ${entries[i4][0]} in data map is not an integer`);
  69761. }
  69762. if (index6 < 0 || index6 >= length) {
  69763. throw new Error(`index ${index6} is out of range of sparse vector length`);
  69764. }
  69765. this.indexes[i4] = index6;
  69766. if (typeof val2 !== "number") {
  69767. throw new Error(`expected value at index ${index6} to be number, got ${typeof val2} ${val2}`);
  69768. }
  69769. if (val2 === 0) {
  69770. throw new Error("elements in sparse vector cannot be 0");
  69771. }
  69772. this.values[i4] = val2;
  69773. }
  69774. }
  69775. return new Proxy(this, {
  69776. get(target, p3) {
  69777. const index6 = typeof p3 === "string" ? parseInt(p3, 10) : NaN;
  69778. if (!Number.isNaN(index6)) {
  69779. if (index6 < 0 || index6 >= target.length)
  69780. return void 0;
  69781. const dataIndex = target.indexes.indexOf(index6);
  69782. return dataIndex === -1 ? 0 : target.values[dataIndex];
  69783. }
  69784. return target[p3];
  69785. }
  69786. });
  69787. }
  69788. *[Symbol.iterator]() {
  69789. let nextIndex = 0;
  69790. for (let i4 = 0; i4 < this.length; i4++) {
  69791. yield this.indexes[nextIndex] === i4 ? this.values[nextIndex++] : 0;
  69792. }
  69793. }
  69794. };
  69795. exports2.SparseVector = SparseVector;
  69796. }
  69797. });
  69798. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/pgvector.js
  69799. var require_pgvector2 = __commonJS({
  69800. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/pgvector.js"(exports2) {
  69801. "use strict";
  69802. Object.defineProperty(exports2, "__esModule", { value: true });
  69803. exports2.PgVectorSparseVecCodec = exports2.PgVectorHalfVecCodec = exports2.PgVectorCodec = exports2.PG_VECTOR_MAX_DIM = void 0;
  69804. var ifaces_1 = require_ifaces();
  69805. var errors_1 = require_errors();
  69806. var utils_1 = require_utils2();
  69807. var pgvector_1 = require_pgvector();
  69808. exports2.PG_VECTOR_MAX_DIM = (1 << 16) - 1;
  69809. var PgVectorCodec = class extends ifaces_1.ScalarCodec {
  69810. tsType = "Float32Array";
  69811. encode(buf, object, ctx) {
  69812. object = ctx.preEncode(this, object);
  69813. if (!(object instanceof Float32Array || Array.isArray(object))) {
  69814. throw new errors_1.InvalidArgumentError(`a Float32Array or array of numbers was expected, got "${object}"`);
  69815. }
  69816. if (object.length > exports2.PG_VECTOR_MAX_DIM) {
  69817. throw new errors_1.InvalidArgumentError("too many elements in array to encode into pgvector");
  69818. }
  69819. buf.writeInt32(4 + object.length * 4).writeUInt16(object.length).writeUInt16(0);
  69820. if (object instanceof Float32Array) {
  69821. for (const el of object) {
  69822. buf.writeFloat32(el);
  69823. }
  69824. } else {
  69825. for (const el of object) {
  69826. if (typeof el !== "number") {
  69827. throw new errors_1.InvalidArgumentError(`elements of vector array expected to be a numbers, got "${el}"`);
  69828. }
  69829. buf.writeFloat32(el);
  69830. }
  69831. }
  69832. }
  69833. decode(buf, ctx) {
  69834. const dim = buf.readUInt16();
  69835. buf.discard(2);
  69836. const vecBuf = buf.readBuffer(dim * 4);
  69837. const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
  69838. const vec = new Float32Array(dim);
  69839. for (let i4 = 0; i4 < dim; i4++) {
  69840. vec[i4] = data.getFloat32(i4 * 4);
  69841. }
  69842. return ctx.postDecode(this, vec);
  69843. }
  69844. };
  69845. exports2.PgVectorCodec = PgVectorCodec;
  69846. var PgVectorHalfVecCodec = class extends ifaces_1.ScalarCodec {
  69847. tsType = "Float16Array";
  69848. tsModule = "gel";
  69849. encode(buf, object, ctx) {
  69850. object = ctx.preEncode(this, object);
  69851. if (!((0, utils_1.isFloat16Array)(object) || Array.isArray(object))) {
  69852. throw new errors_1.InvalidArgumentError(`a Float16Array or array of numbers was expected, got "${object}"`);
  69853. }
  69854. if (object.length > exports2.PG_VECTOR_MAX_DIM) {
  69855. throw new errors_1.InvalidArgumentError("too many elements in array to encode into pgvector");
  69856. }
  69857. buf.writeInt32(4 + object.length * 2).writeUInt16(object.length).writeUInt16(0);
  69858. const vecBuf = new Uint8Array(object.length * 2);
  69859. const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
  69860. if ((0, utils_1.isFloat16Array)(object)) {
  69861. for (let i4 = 0; i4 < object.length; i4++) {
  69862. (0, utils_1.setFloat16)(data, i4 * 2, object[i4]);
  69863. }
  69864. } else {
  69865. for (let i4 = 0; i4 < object.length; i4++) {
  69866. if (typeof object[i4] !== "number") {
  69867. throw new errors_1.InvalidArgumentError(`elements of vector array expected to be a numbers, got "${object[i4]}"`);
  69868. }
  69869. (0, utils_1.setFloat16)(data, i4 * 2, object[i4]);
  69870. }
  69871. }
  69872. buf.writeBuffer(vecBuf);
  69873. }
  69874. decode(buf, ctx) {
  69875. const dim = buf.readUInt16();
  69876. buf.discard(2);
  69877. const vecBuf = buf.readBuffer(dim * 2);
  69878. const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
  69879. const vec = new utils_1.Float16Array(dim);
  69880. for (let i4 = 0; i4 < dim; i4++) {
  69881. vec[i4] = (0, utils_1.getFloat16)(data, i4 * 2);
  69882. }
  69883. return ctx.postDecode(this, vec);
  69884. }
  69885. };
  69886. exports2.PgVectorHalfVecCodec = PgVectorHalfVecCodec;
  69887. var PgVectorSparseVecCodec = class extends ifaces_1.ScalarCodec {
  69888. tsType = "SparseVector";
  69889. tsModule = "gel";
  69890. encode(buf, object, ctx) {
  69891. let dims;
  69892. let indexes;
  69893. let values;
  69894. if (ctx.hasOverload(this)) {
  69895. [dims, indexes, values] = ctx.preEncode(this, object);
  69896. } else {
  69897. if (!(object instanceof pgvector_1.SparseVector)) {
  69898. throw new errors_1.InvalidArgumentError(`a SparseVector was expected, got "${object}"`);
  69899. }
  69900. dims = object.length;
  69901. indexes = object.indexes;
  69902. values = object.values;
  69903. }
  69904. const indexesLength = indexes.length;
  69905. if (indexesLength > exports2.PG_VECTOR_MAX_DIM || indexesLength > dims) {
  69906. throw new errors_1.InvalidArgumentError("too many elements in sparse vector value");
  69907. }
  69908. buf.writeUInt32(4 * (3 + indexesLength * 2)).writeUInt32(dims).writeUInt32(indexesLength).writeUInt32(0);
  69909. const vecBuf = new Uint8Array(indexesLength * 8);
  69910. const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
  69911. for (let i4 = 0; i4 < indexesLength; i4++) {
  69912. data.setUint32(i4 * 4, indexes[i4]);
  69913. }
  69914. for (let i4 = 0; i4 < indexesLength; i4++) {
  69915. data.setFloat32((indexesLength + i4) * 4, values[i4]);
  69916. }
  69917. buf.writeBuffer(vecBuf);
  69918. }
  69919. decode(buf, ctx) {
  69920. const dim = buf.readUInt32();
  69921. const nnz = buf.readUInt32();
  69922. buf.discard(4);
  69923. const vecBuf = buf.readBuffer(nnz * 8);
  69924. const data = new DataView(vecBuf.buffer, vecBuf.byteOffset, vecBuf.byteLength);
  69925. const indexes = new Uint32Array(nnz);
  69926. for (let i4 = 0; i4 < nnz; i4++) {
  69927. indexes[i4] = data.getUint32(i4 * 4);
  69928. }
  69929. const vecData = new Float32Array(nnz);
  69930. for (let i4 = 0; i4 < nnz; i4++) {
  69931. vecData[i4] = data.getFloat32((i4 + nnz) * 4);
  69932. }
  69933. if (ctx.hasOverload(this)) {
  69934. return ctx.postDecode(this, [
  69935. dim,
  69936. indexes,
  69937. vecData
  69938. ]);
  69939. }
  69940. return new pgvector_1.SparseVector(dim, indexes, vecData);
  69941. }
  69942. };
  69943. exports2.PgVectorSparseVecCodec = PgVectorSparseVecCodec;
  69944. }
  69945. });
  69946. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/postgis.js
  69947. var require_postgis = __commonJS({
  69948. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/postgis.js"(exports2) {
  69949. "use strict";
  69950. Object.defineProperty(exports2, "__esModule", { value: true });
  69951. exports2.Box3D = exports2.Box2D = exports2.GeometryCollection = exports2.MultiSurface = exports2.TriangulatedIrregularNetwork = exports2.PolyhedralSurface = exports2.MultiPolygon = exports2.CurvePolygon = exports2.Triangle = exports2.Polygon = exports2.MultiCurve = exports2.CompoundCurve = exports2.MultiLineString = exports2.CircularString = exports2.LineString = exports2.MultiPoint = exports2.Point = exports2.Geometry = void 0;
  69952. var Geometry = class {
  69953. };
  69954. exports2.Geometry = Geometry;
  69955. function _pointToWKT(p3) {
  69956. return `${p3.x} ${p3.y}${p3.z !== null ? ` ${p3.z}` : ""}${p3.m !== null ? ` ${p3.m}` : ""}`;
  69957. }
  69958. function _flagsToWKT(z2, m4) {
  69959. return (z2 || m4 ? " " : "") + (z2 ? "Z" : "") + (m4 ? "M" : "");
  69960. }
  69961. function _sridWKTPrefix(srid, depth) {
  69962. return srid !== null && depth === 0 ? `SRID=${srid}; ` : "";
  69963. }
  69964. function _indent(indent, depth) {
  69965. if (!indent)
  69966. return "";
  69967. return "\n" + " ".repeat(indent * depth);
  69968. }
  69969. var Point = class extends Geometry {
  69970. x;
  69971. y;
  69972. z;
  69973. m;
  69974. srid;
  69975. constructor(x4, y2, z2 = null, m4 = null, srid = null) {
  69976. super();
  69977. this.x = x4;
  69978. this.y = y2;
  69979. this.z = z2;
  69980. this.m = m4;
  69981. this.srid = srid;
  69982. }
  69983. get hasZ() {
  69984. return this.z !== null;
  69985. }
  69986. get hasM() {
  69987. return this.m !== null;
  69988. }
  69989. toWKT(_indent2, _truncate = Infinity, depth = 0) {
  69990. return `${_sridWKTPrefix(this.srid, depth)}POINT${_flagsToWKT(this.z !== null, this.m !== null)} ${Number.isNaN(this.x) ? "EMPTY" : "(" + _pointToWKT(this) + ")"}`;
  69991. }
  69992. equals(other) {
  69993. return this.srid === other.srid && (Number.isNaN(this.x) ? this.hasZ === other.hasZ && this.hasM === other.hasM : this.x === other.x && this.y === other.y && this.z === other.z && this.m === other.m);
  69994. }
  69995. };
  69996. exports2.Point = Point;
  69997. var MultiPoint = class extends Geometry {
  69998. geometries;
  69999. hasZ;
  70000. hasM;
  70001. srid;
  70002. constructor(geometries, hasZ, hasM, srid) {
  70003. super();
  70004. this.geometries = geometries;
  70005. this.hasZ = hasZ;
  70006. this.hasM = hasM;
  70007. this.srid = srid;
  70008. }
  70009. toWKT(indent, truncate = Infinity, depth = 0) {
  70010. let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTIPOINT${_flagsToWKT(this.hasZ, this.hasM)} `;
  70011. if (this.geometries.length === 0) {
  70012. return wkt + "EMPTY";
  70013. }
  70014. wkt += `(`;
  70015. let i4 = 0;
  70016. while (i4 < this.geometries.length && wkt.length < truncate) {
  70017. wkt += _indent(indent, depth + 1) + "(" + _pointToWKT(this.geometries[i4++]) + (i4 < this.geometries.length ? "), " : ")");
  70018. }
  70019. return wkt + _indent(indent, depth) + ")";
  70020. }
  70021. };
  70022. exports2.MultiPoint = MultiPoint;
  70023. function _linestringToWKT(points, indent, truncate = Infinity, depth = 0) {
  70024. let wkt = `(`;
  70025. let i4 = 0;
  70026. while (i4 < points.length && wkt.length < truncate) {
  70027. wkt += _indent(indent, depth + 1) + _pointToWKT(points[i4++]) + (i4 < points.length ? ", " : "");
  70028. }
  70029. return wkt + _indent(indent, depth) + ")";
  70030. }
  70031. var LineString = class extends Geometry {
  70032. points;
  70033. hasZ;
  70034. hasM;
  70035. srid;
  70036. constructor(points, hasZ, hasM, srid) {
  70037. super();
  70038. this.points = points;
  70039. this.hasZ = hasZ;
  70040. this.hasM = hasM;
  70041. this.srid = srid;
  70042. this._validate();
  70043. }
  70044. _validate() {
  70045. if (this.points.length === 1) {
  70046. throw new Error(`expected zero, or 2 or more points in LineString`);
  70047. }
  70048. }
  70049. static _wktName = "LINESTRING";
  70050. toWKT(indent, truncate = Infinity, depth = 0) {
  70051. const wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
  70052. if (this.points.length === 0) {
  70053. return wkt + "EMPTY";
  70054. }
  70055. return wkt + _linestringToWKT(this.points, indent, truncate - wkt.length, depth);
  70056. }
  70057. };
  70058. exports2.LineString = LineString;
  70059. var CircularString = class extends LineString {
  70060. static _wktName = "CIRCULARSTRING";
  70061. _validate() {
  70062. if (this.points.length !== 0 && (this.points.length <= 1 || this.points.length % 2 !== 1)) {
  70063. throw new Error(`expected zero points, or odd number of points greater than 1 in CircularString`);
  70064. }
  70065. }
  70066. };
  70067. exports2.CircularString = CircularString;
  70068. function _multilinestringToWKT(lineStrings, indent, truncate = Infinity, depth = 0) {
  70069. let wkt = `(`;
  70070. let i4 = 0;
  70071. while (i4 < lineStrings.length && wkt.length < truncate) {
  70072. wkt += _indent(indent, depth + 1) + _linestringToWKT(lineStrings[i4++].points, indent, truncate - wkt.length, depth + 1) + (i4 < lineStrings.length ? ", " : "");
  70073. }
  70074. return wkt + _indent(indent, depth) + ")";
  70075. }
  70076. var MultiLineString = class extends Geometry {
  70077. geometries;
  70078. hasZ;
  70079. hasM;
  70080. srid;
  70081. constructor(geometries, hasZ, hasM, srid) {
  70082. super();
  70083. this.geometries = geometries;
  70084. this.hasZ = hasZ;
  70085. this.hasM = hasM;
  70086. this.srid = srid;
  70087. }
  70088. toWKT(indent, truncate = Infinity, depth = 0) {
  70089. const wkt = `${_sridWKTPrefix(this.srid, depth)}MULTILINESTRING${_flagsToWKT(this.hasZ, this.hasM)} `;
  70090. if (this.geometries.length === 0) {
  70091. return wkt + "EMPTY";
  70092. }
  70093. return wkt + _multilinestringToWKT(this.geometries, indent, truncate - wkt.length, depth);
  70094. }
  70095. };
  70096. exports2.MultiLineString = MultiLineString;
  70097. var CompoundCurve = class extends Geometry {
  70098. geometries;
  70099. hasZ;
  70100. hasM;
  70101. srid;
  70102. constructor(geometries, hasZ, hasM, srid) {
  70103. super();
  70104. this.geometries = geometries;
  70105. this.hasZ = hasZ;
  70106. this.hasM = hasM;
  70107. this.srid = srid;
  70108. let lastPoint = null;
  70109. for (const segment of geometries) {
  70110. if (lastPoint && !segment.points[0].equals(lastPoint)) {
  70111. throw new Error("segments in CompoundCurve do not join");
  70112. }
  70113. lastPoint = segment.points[segment.points.length - 1];
  70114. }
  70115. }
  70116. toWKT(indent, truncate = Infinity, depth = 0) {
  70117. let wkt = `${_sridWKTPrefix(this.srid, depth)}COMPOUNDCURVE${_flagsToWKT(this.hasZ, this.hasM)} `;
  70118. if (this.geometries.length === 0) {
  70119. return wkt + "EMPTY";
  70120. }
  70121. wkt += "(";
  70122. let i4 = 0;
  70123. while (i4 < this.geometries.length && wkt.length < truncate) {
  70124. wkt += _indent(indent, depth + 1) + (this.geometries[i4] instanceof CircularString ? "CIRCULARSTRING " : "LINESTRING ") + _linestringToWKT(this.geometries[i4++].points, indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
  70125. }
  70126. return wkt + _indent(indent, depth) + ")";
  70127. }
  70128. };
  70129. exports2.CompoundCurve = CompoundCurve;
  70130. var MultiCurve = class extends Geometry {
  70131. geometries;
  70132. hasZ;
  70133. hasM;
  70134. srid;
  70135. constructor(geometries, hasZ, hasM, srid) {
  70136. super();
  70137. this.geometries = geometries;
  70138. this.hasZ = hasZ;
  70139. this.hasM = hasM;
  70140. this.srid = srid;
  70141. }
  70142. toWKT(indent, truncate = Infinity, depth = 0) {
  70143. let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTICURVE${_flagsToWKT(this.hasZ, this.hasM)} `;
  70144. if (this.geometries.length === 0) {
  70145. return wkt + "EMPTY";
  70146. }
  70147. wkt += `(`;
  70148. let i4 = 0;
  70149. while (i4 < this.geometries.length && wkt.length < truncate) {
  70150. wkt += _indent(indent, depth + 1) + this.geometries[i4++].toWKT(indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
  70151. }
  70152. return wkt + _indent(indent, depth) + ")";
  70153. }
  70154. };
  70155. exports2.MultiCurve = MultiCurve;
  70156. var Polygon = class extends Geometry {
  70157. rings;
  70158. hasZ;
  70159. hasM;
  70160. srid;
  70161. constructor(rings, hasZ, hasM, srid) {
  70162. super();
  70163. this.rings = rings;
  70164. this.hasZ = hasZ;
  70165. this.hasM = hasM;
  70166. this.srid = srid;
  70167. this._validate();
  70168. }
  70169. _validate() {
  70170. if (this.rings.some((ring) => ring.points.length < 4 || !ring.points[0].equals(ring.points[ring.points.length - 1]))) {
  70171. throw new Error("expected rings in Polygon to be closed and to have at least 4 points");
  70172. }
  70173. }
  70174. static _wktName = "POLYGON";
  70175. toWKT(indent, truncate = Infinity, depth = 0) {
  70176. const wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
  70177. if (this.rings.length === 0) {
  70178. return wkt + "EMPTY";
  70179. }
  70180. return wkt + _multilinestringToWKT(this.rings, indent, truncate - wkt.length, depth);
  70181. }
  70182. };
  70183. exports2.Polygon = Polygon;
  70184. var Triangle = class extends Polygon {
  70185. static _wktName = "TRIANGLE";
  70186. _validate() {
  70187. if (this.rings.length > 1) {
  70188. throw new Error("Triangle can only contain a single ring");
  70189. }
  70190. if (this.rings.some((ring) => ring.points.length !== 4 || !ring.points[0].equals(ring.points[ring.points.length - 1]))) {
  70191. throw new Error("expected Triangle to be closed and to have exactly 4 points");
  70192. }
  70193. }
  70194. };
  70195. exports2.Triangle = Triangle;
  70196. var CurvePolygon = class extends Geometry {
  70197. geometries;
  70198. hasZ;
  70199. hasM;
  70200. srid;
  70201. constructor(geometries, hasZ, hasM, srid) {
  70202. super();
  70203. this.geometries = geometries;
  70204. this.hasZ = hasZ;
  70205. this.hasM = hasM;
  70206. this.srid = srid;
  70207. if (this.geometries.some((ring) => ring instanceof LineString && ring.points.length < 4 || (ring instanceof CompoundCurve ? !ring.geometries[0].points[0].equals(ring.geometries[ring.geometries.length - 1].points[ring.geometries[ring.geometries.length - 1].points.length - 1]) : !ring.points[0].equals(ring.points[ring.points.length - 1])))) {
  70208. throw new Error("expected rings in CurvePolygon to be closed and LinearRings to have at least 4 points");
  70209. }
  70210. }
  70211. toWKT(indent, truncate = Infinity, depth = 0) {
  70212. let wkt = `${_sridWKTPrefix(this.srid, depth)}CURVEPOLYGON${_flagsToWKT(this.hasZ, this.hasM)} `;
  70213. if (this.geometries.length === 0) {
  70214. return wkt + "EMPTY";
  70215. }
  70216. wkt += `(`;
  70217. let i4 = 0;
  70218. while (i4 < this.geometries.length && wkt.length < truncate) {
  70219. wkt += _indent(indent, depth + 1) + this.geometries[i4++].toWKT(indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
  70220. }
  70221. return wkt + _indent(indent, depth) + ")";
  70222. }
  70223. };
  70224. exports2.CurvePolygon = CurvePolygon;
  70225. var MultiPolygon = class extends Geometry {
  70226. geometries;
  70227. hasZ;
  70228. hasM;
  70229. srid;
  70230. constructor(geometries, hasZ, hasM, srid) {
  70231. super();
  70232. this.geometries = geometries;
  70233. this.hasZ = hasZ;
  70234. this.hasM = hasM;
  70235. this.srid = srid;
  70236. }
  70237. static _wktName = "MULTIPOLYGON";
  70238. toWKT(indent, truncate = Infinity, depth = 0) {
  70239. let wkt = `${_sridWKTPrefix(this.srid, depth)}${this.constructor._wktName}${_flagsToWKT(this.hasZ, this.hasM)} `;
  70240. if (this.geometries.length === 0) {
  70241. return wkt + "EMPTY";
  70242. }
  70243. wkt += `(`;
  70244. let i4 = 0;
  70245. while (i4 < this.geometries.length && wkt.length < truncate) {
  70246. wkt += _indent(indent, depth + 1) + _multilinestringToWKT(this.geometries[i4++].rings, indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
  70247. }
  70248. return wkt + _indent(indent, depth) + ")";
  70249. }
  70250. };
  70251. exports2.MultiPolygon = MultiPolygon;
  70252. var PolyhedralSurface = class extends MultiPolygon {
  70253. static _wktName = "POLYHEDRALSURFACE";
  70254. };
  70255. exports2.PolyhedralSurface = PolyhedralSurface;
  70256. var TriangulatedIrregularNetwork = class extends MultiPolygon {
  70257. static _wktName = "TIN";
  70258. };
  70259. exports2.TriangulatedIrregularNetwork = TriangulatedIrregularNetwork;
  70260. var MultiSurface = class extends Geometry {
  70261. geometries;
  70262. hasZ;
  70263. hasM;
  70264. srid;
  70265. constructor(geometries, hasZ, hasM, srid) {
  70266. super();
  70267. this.geometries = geometries;
  70268. this.hasZ = hasZ;
  70269. this.hasM = hasM;
  70270. this.srid = srid;
  70271. }
  70272. toWKT(indent, truncate = Infinity, depth = 0) {
  70273. let wkt = `${_sridWKTPrefix(this.srid, depth)}MULTISURFACE${_flagsToWKT(this.hasZ, this.hasM)} `;
  70274. if (this.geometries.length === 0) {
  70275. return wkt + "EMPTY";
  70276. }
  70277. wkt += `(`;
  70278. let i4 = 0;
  70279. while (i4 < this.geometries.length && wkt.length < truncate) {
  70280. wkt += _indent(indent, depth + 1) + this.geometries[i4++].toWKT(indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
  70281. }
  70282. return wkt + _indent(indent, depth) + ")";
  70283. }
  70284. };
  70285. exports2.MultiSurface = MultiSurface;
  70286. var GeometryCollection = class extends Geometry {
  70287. geometries;
  70288. hasZ;
  70289. hasM;
  70290. srid;
  70291. constructor(geometries, hasZ, hasM, srid) {
  70292. super();
  70293. this.geometries = geometries;
  70294. this.hasZ = hasZ;
  70295. this.hasM = hasM;
  70296. this.srid = srid;
  70297. }
  70298. toWKT(indent, truncate = Infinity, depth = 0) {
  70299. let wkt = `${_sridWKTPrefix(this.srid, depth)}GEOMETRYCOLLECTION${_flagsToWKT(this.hasZ, this.hasM)} `;
  70300. if (this.geometries.length === 0) {
  70301. return wkt + "EMPTY";
  70302. }
  70303. wkt += `(`;
  70304. let i4 = 0;
  70305. while (i4 < this.geometries.length && wkt.length < truncate) {
  70306. wkt += _indent(indent, depth + 1) + this.geometries[i4++].toWKT(indent, truncate - wkt.length, depth + 1) + (i4 < this.geometries.length ? ", " : "");
  70307. }
  70308. return wkt + _indent(indent, depth) + ")";
  70309. }
  70310. };
  70311. exports2.GeometryCollection = GeometryCollection;
  70312. var Box2D = class {
  70313. min;
  70314. max;
  70315. constructor(min, max) {
  70316. this.min = min;
  70317. this.max = max;
  70318. }
  70319. toString() {
  70320. return `BOX(${this.min[0]} ${this.min[1]}, ${this.max[0]} ${this.max[1]})`;
  70321. }
  70322. };
  70323. exports2.Box2D = Box2D;
  70324. var Box3D = class {
  70325. min;
  70326. max;
  70327. constructor(min, max) {
  70328. this.min = min;
  70329. this.max = max;
  70330. }
  70331. toString() {
  70332. return `BOX3D(${this.min[0]} ${this.min[1]} ${this.min[2]}, ${this.max[0]} ${this.max[1]} ${this.max[2]})`;
  70333. }
  70334. };
  70335. exports2.Box3D = Box3D;
  70336. }
  70337. });
  70338. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/postgis.js
  70339. var require_postgis2 = __commonJS({
  70340. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/postgis.js"(exports2) {
  70341. "use strict";
  70342. Object.defineProperty(exports2, "__esModule", { value: true });
  70343. exports2.PostgisBox3dCodec = exports2.PostgisBox2dCodec = exports2.PostgisGeometryCodec = void 0;
  70344. var postgis_1 = require_postgis();
  70345. var errors_1 = require_errors();
  70346. var ifaces_1 = require_ifaces();
  70347. var PostgisGeometryCodec = class extends ifaces_1.ScalarCodec {
  70348. encode(buf, object, ctx) {
  70349. if (ctx.hasOverload(this)) {
  70350. const geomBuf = ctx.preEncode(this, object);
  70351. buf.writeBytes(geomBuf);
  70352. } else {
  70353. if (!(object instanceof postgis_1.Geometry)) {
  70354. throw new errors_1.InvalidArgumentError(`a Geometry object was expected, got "${object}"`);
  70355. }
  70356. const finalise = buf.writeDeferredSize();
  70357. _encodeGeometry(buf, object);
  70358. finalise();
  70359. }
  70360. }
  70361. decode(buf, ctx) {
  70362. if (ctx.hasOverload(this)) {
  70363. return ctx.postDecode(this, buf.consumeAsBuffer());
  70364. }
  70365. return _parseGeometry(buf);
  70366. }
  70367. };
  70368. exports2.PostgisGeometryCodec = PostgisGeometryCodec;
  70369. var PostgisBox2dCodec = class extends ifaces_1.ScalarCodec {
  70370. encode(buf, object, ctx) {
  70371. let min;
  70372. let max;
  70373. if (ctx.hasOverload(this)) {
  70374. [min, max] = ctx.preEncode(this, object);
  70375. } else {
  70376. if (!(object instanceof postgis_1.Box2D)) {
  70377. throw new errors_1.InvalidArgumentError(`a Box2D object was expected, got "${object}"`);
  70378. }
  70379. min = object.min;
  70380. max = object.max;
  70381. }
  70382. const finalise = buf.writeDeferredSize();
  70383. _encodeGeometry(buf, new postgis_1.Polygon([
  70384. new postgis_1.LineString([
  70385. new postgis_1.Point(min[0], min[1]),
  70386. new postgis_1.Point(min[0], max[1]),
  70387. new postgis_1.Point(max[0], max[1]),
  70388. new postgis_1.Point(min[0], min[1])
  70389. ], false, false, null)
  70390. ], false, false, null));
  70391. finalise();
  70392. }
  70393. decode(buf, ctx) {
  70394. const poly = _parseGeometry(buf);
  70395. if (poly.constructor !== postgis_1.Polygon || poly.hasZ || poly.rings.length !== 1 || poly.rings[0].points.length !== 5) {
  70396. throw new errors_1.InternalClientError(`failed to decode ext::postgis::box2d type`);
  70397. }
  70398. const points = poly.rings[0].points;
  70399. const min = [points[0].x, points[0].y];
  70400. const max = [points[2].x, points[2].y];
  70401. if (ctx.hasOverload(this)) {
  70402. return ctx.postDecode(this, [min, max]);
  70403. }
  70404. return new postgis_1.Box2D(min, max);
  70405. }
  70406. };
  70407. exports2.PostgisBox2dCodec = PostgisBox2dCodec;
  70408. var PostgisBox3dCodec = class extends ifaces_1.ScalarCodec {
  70409. encode(buf, object, ctx) {
  70410. let min;
  70411. let max;
  70412. if (ctx.hasOverload(this)) {
  70413. [min, max] = ctx.preEncode(this, object);
  70414. } else {
  70415. if (!(object instanceof postgis_1.Box3D)) {
  70416. throw new errors_1.InvalidArgumentError(`a Box3D object was expected, got "${object}"`);
  70417. }
  70418. min = object.min;
  70419. max = object.max;
  70420. }
  70421. const finalise = buf.writeDeferredSize();
  70422. _encodeGeometry(buf, new postgis_1.Polygon([
  70423. new postgis_1.LineString([
  70424. new postgis_1.Point(min[0], min[1], min[2]),
  70425. new postgis_1.Point(min[0], max[1], max[2]),
  70426. new postgis_1.Point(max[0], max[1], max[2]),
  70427. new postgis_1.Point(min[0], min[1], min[2])
  70428. ], true, false, null)
  70429. ], true, false, null));
  70430. finalise();
  70431. }
  70432. decode(buf, ctx) {
  70433. const poly = _parseGeometry(buf);
  70434. let min;
  70435. let max;
  70436. if (poly.constructor === postgis_1.Polygon && poly.rings.length === 1 && poly.rings[0].points.length === 5) {
  70437. const points = poly.rings[0].points;
  70438. min = points[0];
  70439. max = points[2];
  70440. } else if (poly.constructor === postgis_1.PolyhedralSurface && poly.geometries.length === 6 && poly.geometries[0].rings.length === 1 && poly.geometries[0].rings[0].points.length === 5) {
  70441. min = poly.geometries[0].rings[0].points[0];
  70442. max = poly.geometries[5].rings[0].points[2];
  70443. } else {
  70444. throw new errors_1.InternalClientError(`failed to decode ext::postgis::box3d type`);
  70445. }
  70446. if (ctx.hasOverload(this)) {
  70447. return ctx.postDecode(this, [
  70448. [min.x, min.y, min.z ?? 0],
  70449. [max.x, max.y, max.z ?? 0]
  70450. ]);
  70451. }
  70452. return new postgis_1.Box3D([min.x, min.y, min.z ?? 0], [max.x, max.y, max.z ?? 0]);
  70453. }
  70454. };
  70455. exports2.PostgisBox3dCodec = PostgisBox3dCodec;
  70456. var zFlag = 2147483648;
  70457. var mFlag = 1073741824;
  70458. var sridFlag = 536870912;
  70459. var allFlags = zFlag | mFlag | sridFlag;
  70460. function _parseGeometry(buf, srid = null) {
  70461. const le = buf.readUInt8() === 1;
  70462. let type = buf.readUInt32(le);
  70463. const z2 = (type & zFlag) !== 0;
  70464. const m4 = (type & mFlag) !== 0;
  70465. if ((type & sridFlag) !== 0) {
  70466. srid = buf.readUInt32(le);
  70467. }
  70468. type = type & ~allFlags;
  70469. switch (type) {
  70470. case 1:
  70471. return _parsePoint(buf, le, z2, m4, srid);
  70472. case 2:
  70473. return _parseLineString(buf, postgis_1.LineString, le, z2, m4, srid);
  70474. case 3:
  70475. return _parsePolygon(buf, postgis_1.Polygon, le, z2, m4, srid);
  70476. case 4:
  70477. return _parseMultiPoint(buf, le, z2, m4, srid);
  70478. case 5:
  70479. return _parseMultiLineString(buf, le, z2, m4, srid);
  70480. case 6:
  70481. return _parseMultiPolygon(buf, postgis_1.MultiPolygon, le, z2, m4, srid);
  70482. case 7:
  70483. return _parseGeometryCollection(buf, le, z2, m4, srid);
  70484. case 8:
  70485. return _parseLineString(buf, postgis_1.CircularString, le, z2, m4, srid);
  70486. case 9:
  70487. return _parseCompoundCurve(buf, le, z2, m4, srid);
  70488. case 10:
  70489. return _parseMultiCurve(buf, postgis_1.CurvePolygon, le, z2, m4, srid);
  70490. case 11:
  70491. return _parseMultiCurve(buf, postgis_1.MultiCurve, le, z2, m4, srid);
  70492. case 12:
  70493. return _parseMultiSurface(buf, le, z2, m4, srid);
  70494. case 15:
  70495. return _parseMultiPolygon(buf, postgis_1.PolyhedralSurface, le, z2, m4, srid);
  70496. case 16:
  70497. return _parseMultiPolygon(buf, postgis_1.TriangulatedIrregularNetwork, le, z2, m4, srid);
  70498. case 17:
  70499. return _parsePolygon(buf, postgis_1.Triangle, le, z2, m4, srid);
  70500. default:
  70501. throw new Error(`unsupported wkb type: ${type}`);
  70502. }
  70503. }
  70504. function _parsePoint(buf, le, z2, m4, srid) {
  70505. return new postgis_1.Point(buf.readFloat64(le), buf.readFloat64(le), z2 ? buf.readFloat64(le) : null, m4 ? buf.readFloat64(le) : null, srid);
  70506. }
  70507. function _parseLineString(buf, cls, le, z2, m4, srid) {
  70508. const pointCount = buf.readUInt32(le);
  70509. const points = new Array(pointCount);
  70510. for (let i4 = 0; i4 < pointCount; i4++) {
  70511. points[i4] = _parsePoint(buf, le, z2, m4, srid);
  70512. }
  70513. return new cls(points, z2, m4, srid);
  70514. }
  70515. function _parsePolygon(buf, cls, le, z2, m4, srid) {
  70516. const ringCount = buf.readUInt32(le);
  70517. const rings = new Array(ringCount);
  70518. for (let i4 = 0; i4 < ringCount; i4++) {
  70519. rings[i4] = _parseLineString(buf, postgis_1.LineString, le, z2, m4, srid);
  70520. }
  70521. return new cls(rings, z2, m4, srid);
  70522. }
  70523. function _parseMultiPoint(buf, le, z2, m4, srid) {
  70524. const pointCount = buf.readUInt32(le);
  70525. const points = new Array(pointCount);
  70526. for (let i4 = 0; i4 < pointCount; i4++) {
  70527. buf.discard(5);
  70528. points[i4] = _parsePoint(buf, le, z2, m4, srid);
  70529. }
  70530. return new postgis_1.MultiPoint(points, z2, m4, srid);
  70531. }
  70532. function _parseMultiLineString(buf, le, z2, m4, srid) {
  70533. const lineStringCount = buf.readUInt32(le);
  70534. const lineStrings = new Array(lineStringCount);
  70535. for (let i4 = 0; i4 < lineStringCount; i4++) {
  70536. buf.discard(5);
  70537. lineStrings[i4] = _parseLineString(buf, postgis_1.LineString, le, z2, m4, srid);
  70538. }
  70539. return new postgis_1.MultiLineString(lineStrings, z2, m4, srid);
  70540. }
  70541. function _parseCompoundCurve(buf, le, z2, m4, srid) {
  70542. const curveCount = buf.readUInt32(le);
  70543. const curves = new Array(curveCount);
  70544. for (let i4 = 0; i4 < curveCount; i4++) {
  70545. buf.discard(1);
  70546. const type = buf.readUInt32(le) & ~allFlags;
  70547. switch (type) {
  70548. case 2:
  70549. curves[i4] = _parseLineString(buf, postgis_1.LineString, le, z2, m4, srid);
  70550. break;
  70551. case 8:
  70552. curves[i4] = _parseLineString(buf, postgis_1.CircularString, le, z2, m4, srid);
  70553. break;
  70554. default:
  70555. throw new Error(`unexpected type ${type} in CompoundCurve`);
  70556. }
  70557. }
  70558. return new postgis_1.CompoundCurve(curves, z2, m4, srid);
  70559. }
  70560. function _parseMultiCurve(buf, cls, le, z2, m4, srid) {
  70561. const curveCount = buf.readUInt32(le);
  70562. const curves = new Array(curveCount);
  70563. for (let i4 = 0; i4 < curveCount; i4++) {
  70564. buf.discard(1);
  70565. const type = buf.readUInt32(le) & ~allFlags;
  70566. switch (type) {
  70567. case 2:
  70568. curves[i4] = _parseLineString(buf, postgis_1.LineString, le, z2, m4, srid);
  70569. break;
  70570. case 8:
  70571. curves[i4] = _parseLineString(buf, postgis_1.CircularString, le, z2, m4, srid);
  70572. break;
  70573. case 9:
  70574. curves[i4] = _parseCompoundCurve(buf, le, z2, m4, srid);
  70575. break;
  70576. default:
  70577. throw new Error(`unexpected type ${type} in MultiCurve/CurvePolygon`);
  70578. }
  70579. }
  70580. return new cls(curves, z2, m4, srid);
  70581. }
  70582. function _parseMultiPolygon(buf, cls, le, z2, m4, srid) {
  70583. const polyCls = cls === postgis_1.TriangulatedIrregularNetwork ? postgis_1.Triangle : postgis_1.Polygon;
  70584. const polyCount = buf.readUInt32(le);
  70585. const polys = new Array(polyCount);
  70586. for (let i4 = 0; i4 < polyCount; i4++) {
  70587. buf.discard(5);
  70588. polys[i4] = _parsePolygon(buf, polyCls, le, z2, m4, srid);
  70589. }
  70590. return new cls(polys, z2, m4, srid);
  70591. }
  70592. function _parseMultiSurface(buf, le, z2, m4, srid) {
  70593. const surfaceCount = buf.readUInt32(le);
  70594. const surfaces = new Array(surfaceCount);
  70595. for (let i4 = 0; i4 < surfaceCount; i4++) {
  70596. buf.discard(1);
  70597. const type = buf.readUInt32(le) & ~allFlags;
  70598. switch (type) {
  70599. case 3:
  70600. surfaces[i4] = _parsePolygon(buf, postgis_1.Polygon, le, z2, m4, srid);
  70601. break;
  70602. case 10:
  70603. surfaces[i4] = _parseMultiCurve(buf, postgis_1.CurvePolygon, le, z2, m4, srid);
  70604. break;
  70605. default:
  70606. throw new Error(`unexpected type ${type} in MultiSurface`);
  70607. }
  70608. }
  70609. return new postgis_1.MultiSurface(surfaces, z2, m4, srid);
  70610. }
  70611. function _parseGeometryCollection(buf, le, z2, m4, srid) {
  70612. const geometryCount = buf.readUInt32(le);
  70613. const geometries = new Array(geometryCount);
  70614. for (let i4 = 0; i4 < geometryCount; i4++) {
  70615. geometries[i4] = _parseGeometry(buf, srid);
  70616. }
  70617. return new postgis_1.GeometryCollection(geometries, z2, m4, srid);
  70618. }
  70619. var geomTypes = /* @__PURE__ */ new Map([
  70620. [postgis_1.Point, 1],
  70621. [postgis_1.LineString, 2],
  70622. [postgis_1.Polygon, 3],
  70623. [postgis_1.MultiPoint, 4],
  70624. [postgis_1.MultiLineString, 5],
  70625. [postgis_1.MultiPolygon, 6],
  70626. [postgis_1.GeometryCollection, 7],
  70627. [postgis_1.CircularString, 8],
  70628. [postgis_1.CompoundCurve, 9],
  70629. [postgis_1.CurvePolygon, 10],
  70630. [postgis_1.MultiCurve, 11],
  70631. [postgis_1.MultiSurface, 12],
  70632. [postgis_1.PolyhedralSurface, 15],
  70633. [postgis_1.TriangulatedIrregularNetwork, 16],
  70634. [postgis_1.Triangle, 17]
  70635. ]);
  70636. function _encodeGeometry(buf, geom) {
  70637. buf.writeUInt8(0);
  70638. const type = geomTypes.get(geom.constructor);
  70639. if (!type) {
  70640. throw new Error(`unknown geometry type ${geom}`);
  70641. }
  70642. buf.writeUInt32(type | (geom.hasZ ? zFlag : 0) | (geom.hasM ? mFlag : 0) | (geom.srid !== null ? sridFlag : 0));
  70643. if (geom.srid !== null) {
  70644. buf.writeUInt32(geom.srid);
  70645. }
  70646. if (geom instanceof postgis_1.Point) {
  70647. _encodePoint(buf, geom);
  70648. return;
  70649. }
  70650. if (geom instanceof postgis_1.LineString) {
  70651. _encodeLineString(buf, geom);
  70652. return;
  70653. }
  70654. if (geom instanceof postgis_1.Polygon) {
  70655. buf.writeUInt32(geom.rings.length);
  70656. for (const ring of geom.rings) {
  70657. _encodeLineString(buf, ring);
  70658. }
  70659. return;
  70660. }
  70661. buf.writeUInt32(geom.geometries.length);
  70662. for (const point of geom.geometries) {
  70663. _encodeGeometry(buf, point);
  70664. }
  70665. }
  70666. function _encodePoint(buf, point) {
  70667. buf.writeFloat64(point.x);
  70668. buf.writeFloat64(point.y);
  70669. if (point.z !== null)
  70670. buf.writeFloat64(point.z);
  70671. if (point.m !== null)
  70672. buf.writeFloat64(point.m);
  70673. }
  70674. function _encodeLineString(buf, linestring) {
  70675. buf.writeUInt32(linestring.points.length);
  70676. for (const point of linestring.points) {
  70677. _encodePoint(buf, point);
  70678. }
  70679. }
  70680. }
  70681. });
  70682. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/codecs.js
  70683. var require_codecs = __commonJS({
  70684. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/codecs.js"(exports2) {
  70685. "use strict";
  70686. Object.defineProperty(exports2, "__esModule", { value: true });
  70687. exports2.INVALID_CODEC = exports2.NULL_CODEC = exports2.SCALAR_CODECS = exports2.NullCodec = void 0;
  70688. var buffer_1 = require_buffer();
  70689. var boolean_1 = require_boolean();
  70690. var ifaces_1 = require_ifaces();
  70691. var numbers_1 = require_numbers();
  70692. var numerics_1 = require_numerics();
  70693. var text_1 = require_text();
  70694. var uuid_1 = require_uuid();
  70695. var bytes_1 = require_bytes();
  70696. var json_1 = require_json();
  70697. var datetime_1 = require_datetime2();
  70698. var memory_1 = require_memory2();
  70699. var pgvector_1 = require_pgvector2();
  70700. var postgis_1 = require_postgis2();
  70701. var errors_1 = require_errors();
  70702. var consts_1 = require_consts();
  70703. var NullCodec = class extends ifaces_1.Codec {
  70704. static BUFFER = new buffer_1.WriteBuffer().writeInt32(0).unwrap();
  70705. encode(_buf, _object) {
  70706. throw new errors_1.InternalClientError("null codec cannot used to encode data");
  70707. }
  70708. decode(_buf, _ctx) {
  70709. throw new errors_1.InternalClientError("null codec cannot used to decode data");
  70710. }
  70711. getSubcodecs() {
  70712. return [];
  70713. }
  70714. getKind() {
  70715. return "scalar";
  70716. }
  70717. };
  70718. exports2.NullCodec = NullCodec;
  70719. exports2.SCALAR_CODECS = /* @__PURE__ */ new Map();
  70720. exports2.NULL_CODEC = new NullCodec(consts_1.NULL_CODEC_ID);
  70721. exports2.INVALID_CODEC = new NullCodec(consts_1.INVALID_CODEC_ID);
  70722. function registerScalarCodecs(codecs) {
  70723. for (const [typename, type] of Object.entries(codecs)) {
  70724. const id = consts_1.KNOWN_TYPENAMES.get(typename);
  70725. if (id == null) {
  70726. throw new errors_1.InternalClientError("unknown type name");
  70727. }
  70728. exports2.SCALAR_CODECS.set(id, new type(id, typename));
  70729. }
  70730. }
  70731. registerScalarCodecs({
  70732. "std::int16": numbers_1.Int16Codec,
  70733. "std::int32": numbers_1.Int32Codec,
  70734. "std::int64": numbers_1.Int64Codec,
  70735. "std::float32": numbers_1.Float32Codec,
  70736. "std::float64": numbers_1.Float64Codec,
  70737. "std::bigint": numerics_1.BigIntCodec,
  70738. "std::decimal": numerics_1.DecimalStringCodec,
  70739. "std::bool": boolean_1.BoolCodec,
  70740. "std::json": json_1.JSONCodec,
  70741. "std::str": text_1.StrCodec,
  70742. "std::bytes": bytes_1.BytesCodec,
  70743. "std::uuid": uuid_1.UUIDCodec,
  70744. "cal::local_date": datetime_1.LocalDateCodec,
  70745. "cal::local_time": datetime_1.LocalTimeCodec,
  70746. "cal::local_datetime": datetime_1.LocalDateTimeCodec,
  70747. "std::datetime": datetime_1.DateTimeCodec,
  70748. "std::duration": datetime_1.DurationCodec,
  70749. "cal::relative_duration": datetime_1.RelativeDurationCodec,
  70750. "cal::date_duration": datetime_1.DateDurationCodec,
  70751. "cfg::memory": memory_1.ConfigMemoryCodec,
  70752. "std::pg::json": json_1.PgTextJSONCodec,
  70753. "std::pg::timestamptz": datetime_1.DateTimeCodec,
  70754. "std::pg::timestamp": datetime_1.LocalDateTimeCodec,
  70755. "std::pg::date": datetime_1.LocalDateCodec,
  70756. "std::pg::interval": datetime_1.RelativeDurationCodec,
  70757. "ext::pgvector::vector": pgvector_1.PgVectorCodec,
  70758. "ext::pgvector::halfvec": pgvector_1.PgVectorHalfVecCodec,
  70759. "ext::pgvector::sparsevec": pgvector_1.PgVectorSparseVecCodec,
  70760. "ext::postgis::geometry": postgis_1.PostgisGeometryCodec,
  70761. "ext::postgis::geography": postgis_1.PostgisGeometryCodec,
  70762. "ext::postgis::box2d": postgis_1.PostgisBox2dCodec,
  70763. "ext::postgis::box3d": postgis_1.PostgisBox3dCodec
  70764. });
  70765. }
  70766. });
  70767. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/tuple.js
  70768. var require_tuple = __commonJS({
  70769. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/tuple.js"(exports2) {
  70770. "use strict";
  70771. Object.defineProperty(exports2, "__esModule", { value: true });
  70772. exports2.EMPTY_TUPLE_CODEC = exports2.EMPTY_TUPLE_CODEC_ID = exports2.EmptyTupleCodec = exports2.TupleCodec = void 0;
  70773. var consts_1 = require_consts();
  70774. var ifaces_1 = require_ifaces();
  70775. var buffer_1 = require_buffer();
  70776. var errors_1 = require_errors();
  70777. var TupleCodec = class extends ifaces_1.Codec {
  70778. subCodecs;
  70779. typeName;
  70780. constructor(tid, typeName, codecs) {
  70781. super(tid);
  70782. this.subCodecs = codecs;
  70783. this.typeName = typeName;
  70784. }
  70785. encode(buf, object, ctx) {
  70786. if (!Array.isArray(object)) {
  70787. throw new errors_1.InvalidArgumentError(`an array was expected, got "${object}"`);
  70788. }
  70789. const codecs = this.subCodecs;
  70790. const codecsLen = codecs.length;
  70791. if (object.length !== codecsLen) {
  70792. throw new errors_1.InvalidArgumentError(`expected ${codecsLen} tuple item${codecsLen === 1 ? "" : "s"}, got ${object.length}`);
  70793. }
  70794. if (!codecsLen) {
  70795. buf.writeBuffer(EmptyTupleCodec.BUFFER);
  70796. }
  70797. const elemData = new buffer_1.WriteBuffer();
  70798. for (let i4 = 0; i4 < codecsLen; i4++) {
  70799. const elem = object[i4];
  70800. elemData.writeInt32(0);
  70801. if (elem == null) {
  70802. throw new errors_1.MissingArgumentError(`element at index ${i4} in tuple cannot be 'null'`);
  70803. } else {
  70804. try {
  70805. codecs[i4].encode(elemData, elem, ctx);
  70806. } catch (e4) {
  70807. if (e4 instanceof errors_1.QueryArgumentError) {
  70808. throw new errors_1.InvalidArgumentError(`invalid element at index ${i4} in tuple: ${e4.message}`);
  70809. } else {
  70810. throw e4;
  70811. }
  70812. }
  70813. }
  70814. }
  70815. const elemBuf = elemData.unwrap();
  70816. buf.writeInt32(4 + elemBuf.length);
  70817. buf.writeInt32(codecsLen);
  70818. buf.writeBuffer(elemBuf);
  70819. }
  70820. decode(buf, ctx) {
  70821. const els = buf.readUInt32();
  70822. const subCodecs = this.subCodecs;
  70823. if (els !== subCodecs.length) {
  70824. throw new errors_1.ProtocolError(`cannot decode Tuple: expected ${subCodecs.length} elements, got ${els}`);
  70825. }
  70826. const elemBuf = buffer_1.ReadBuffer.alloc();
  70827. const result = new Array(els);
  70828. for (let i4 = 0; i4 < els; i4++) {
  70829. buf.discard(4);
  70830. const elemLen = buf.readInt32();
  70831. if (elemLen === -1) {
  70832. result[i4] = null;
  70833. } else {
  70834. buf.sliceInto(elemBuf, elemLen);
  70835. result[i4] = subCodecs[i4].decode(elemBuf, ctx);
  70836. elemBuf.finish();
  70837. }
  70838. }
  70839. return result;
  70840. }
  70841. getSubcodecs() {
  70842. return Array.from(this.subCodecs);
  70843. }
  70844. getKind() {
  70845. return "tuple";
  70846. }
  70847. };
  70848. exports2.TupleCodec = TupleCodec;
  70849. var EmptyTupleCodec = class extends ifaces_1.Codec {
  70850. static BUFFER = new buffer_1.WriteBuffer().writeInt32(4).writeInt32(0).unwrap();
  70851. encode(buf, object, _ctx) {
  70852. if (!Array.isArray(object)) {
  70853. throw new errors_1.InvalidArgumentError("cannot encode empty Tuple: expected an array");
  70854. }
  70855. if (object.length) {
  70856. throw new errors_1.InvalidArgumentError(`cannot encode empty Tuple: expected 0 elements got ${object.length}`);
  70857. }
  70858. buf.writeInt32(4);
  70859. buf.writeInt32(0);
  70860. }
  70861. decode(buf) {
  70862. const els = buf.readInt32();
  70863. if (els !== 0) {
  70864. throw new errors_1.ProtocolError(`cannot decode empty Tuple: expected 0 elements, received ${els}`);
  70865. }
  70866. return [];
  70867. }
  70868. getSubcodecs() {
  70869. return [];
  70870. }
  70871. getKind() {
  70872. return "tuple";
  70873. }
  70874. };
  70875. exports2.EmptyTupleCodec = EmptyTupleCodec;
  70876. exports2.EMPTY_TUPLE_CODEC_ID = consts_1.KNOWN_TYPENAMES.get("empty-tuple");
  70877. exports2.EMPTY_TUPLE_CODEC = new EmptyTupleCodec(exports2.EMPTY_TUPLE_CODEC_ID);
  70878. }
  70879. });
  70880. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/range.js
  70881. var require_range2 = __commonJS({
  70882. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/range.js"(exports2) {
  70883. "use strict";
  70884. Object.defineProperty(exports2, "__esModule", { value: true });
  70885. exports2.MultiRange = exports2.Range = void 0;
  70886. var Range = class _Range {
  70887. _lower;
  70888. _upper;
  70889. _incLower;
  70890. _incUpper;
  70891. _isEmpty = false;
  70892. constructor(_lower, _upper, _incLower = _lower != null, _incUpper = false) {
  70893. this._lower = _lower;
  70894. this._upper = _upper;
  70895. this._incLower = _incLower;
  70896. this._incUpper = _incUpper;
  70897. }
  70898. get lower() {
  70899. return this._lower;
  70900. }
  70901. get upper() {
  70902. return this._upper;
  70903. }
  70904. get incLower() {
  70905. return this._incLower;
  70906. }
  70907. get incUpper() {
  70908. return this._incUpper;
  70909. }
  70910. get isEmpty() {
  70911. return this._isEmpty;
  70912. }
  70913. static empty() {
  70914. const range = new _Range(null, null);
  70915. range._isEmpty = true;
  70916. return range;
  70917. }
  70918. toJSON() {
  70919. return this.isEmpty ? { empty: true } : {
  70920. lower: this._lower,
  70921. upper: this._upper,
  70922. inc_lower: this._incLower,
  70923. inc_upper: this._incUpper
  70924. };
  70925. }
  70926. };
  70927. exports2.Range = Range;
  70928. var MultiRange = class {
  70929. _ranges;
  70930. constructor(ranges = []) {
  70931. this._ranges = [...ranges];
  70932. }
  70933. get length() {
  70934. return this._ranges.length;
  70935. }
  70936. *[Symbol.iterator]() {
  70937. for (const range of this._ranges) {
  70938. yield range;
  70939. }
  70940. }
  70941. toJSON() {
  70942. return [...this._ranges];
  70943. }
  70944. };
  70945. exports2.MultiRange = MultiRange;
  70946. }
  70947. });
  70948. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/range.js
  70949. var require_range3 = __commonJS({
  70950. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/range.js"(exports2) {
  70951. "use strict";
  70952. Object.defineProperty(exports2, "__esModule", { value: true });
  70953. exports2.MultiRangeCodec = exports2.RangeCodec = void 0;
  70954. var ifaces_1 = require_ifaces();
  70955. var buffer_1 = require_buffer();
  70956. var range_1 = require_range2();
  70957. var errors_1 = require_errors();
  70958. var RangeFlags;
  70959. (function(RangeFlags2) {
  70960. RangeFlags2[RangeFlags2["EMPTY"] = 1] = "EMPTY";
  70961. RangeFlags2[RangeFlags2["INC_LOWER"] = 2] = "INC_LOWER";
  70962. RangeFlags2[RangeFlags2["INC_UPPER"] = 4] = "INC_UPPER";
  70963. RangeFlags2[RangeFlags2["EMPTY_LOWER"] = 8] = "EMPTY_LOWER";
  70964. RangeFlags2[RangeFlags2["EMPTY_UPPER"] = 16] = "EMPTY_UPPER";
  70965. })(RangeFlags || (RangeFlags = {}));
  70966. var MAXINT32 = 2147483647;
  70967. function encodeRange(buf, obj, subCodec, ctx) {
  70968. if (!(obj instanceof range_1.Range)) {
  70969. throw new errors_1.InvalidArgumentError("a Range was expected");
  70970. }
  70971. const elemData = new buffer_1.WriteBuffer();
  70972. if (obj.lower !== null) {
  70973. subCodec.encode(elemData, obj.lower, ctx);
  70974. }
  70975. if (obj.upper !== null) {
  70976. subCodec.encode(elemData, obj.upper, ctx);
  70977. }
  70978. const elemBuf = elemData.unwrap();
  70979. buf.writeInt32(1 + elemBuf.length);
  70980. buf.writeUInt8(obj.isEmpty ? RangeFlags.EMPTY : (obj.incLower ? RangeFlags.INC_LOWER : 0) | (obj.incUpper ? RangeFlags.INC_UPPER : 0) | (obj.lower === null ? RangeFlags.EMPTY_LOWER : 0) | (obj.upper === null ? RangeFlags.EMPTY_UPPER : 0));
  70981. buf.writeBuffer(elemBuf);
  70982. }
  70983. function decodeRange(buf, subCodec, ctx) {
  70984. const flags = buf.readUInt8();
  70985. if (flags & RangeFlags.EMPTY) {
  70986. return range_1.Range.empty();
  70987. }
  70988. const elemBuf = buffer_1.ReadBuffer.alloc();
  70989. let lower2 = null;
  70990. let upper = null;
  70991. if (!(flags & RangeFlags.EMPTY_LOWER)) {
  70992. buf.sliceInto(elemBuf, buf.readInt32());
  70993. lower2 = subCodec.decode(elemBuf, ctx);
  70994. elemBuf.finish();
  70995. }
  70996. if (!(flags & RangeFlags.EMPTY_UPPER)) {
  70997. buf.sliceInto(elemBuf, buf.readInt32());
  70998. upper = subCodec.decode(elemBuf, ctx);
  70999. elemBuf.finish();
  71000. }
  71001. return new range_1.Range(lower2, upper, !!(flags & RangeFlags.INC_LOWER), !!(flags & RangeFlags.INC_UPPER));
  71002. }
  71003. var RangeCodec = class extends ifaces_1.Codec {
  71004. tsType = "Range";
  71005. tsModule = "gel";
  71006. subCodec;
  71007. typeName;
  71008. constructor(tid, typeName, subCodec) {
  71009. super(tid);
  71010. this.subCodec = subCodec;
  71011. this.typeName = typeName;
  71012. }
  71013. encode(buf, obj, ctx) {
  71014. return encodeRange(buf, obj, this.subCodec, ctx);
  71015. }
  71016. decode(buf, ctx) {
  71017. return decodeRange(buf, this.subCodec, ctx);
  71018. }
  71019. getSubcodecs() {
  71020. return [this.subCodec];
  71021. }
  71022. getKind() {
  71023. return "range";
  71024. }
  71025. };
  71026. exports2.RangeCodec = RangeCodec;
  71027. var MultiRangeCodec = class extends ifaces_1.Codec {
  71028. tsType = "MultiRange";
  71029. tsModule = "gel";
  71030. subCodec;
  71031. typeName;
  71032. constructor(tid, typeName, subCodec) {
  71033. super(tid);
  71034. this.subCodec = subCodec;
  71035. this.typeName = typeName;
  71036. }
  71037. encode(buf, obj, ctx) {
  71038. if (!(obj instanceof range_1.MultiRange)) {
  71039. throw new TypeError(`a MultiRange expected (got type ${obj.constructor.name})`);
  71040. }
  71041. const objLen = obj.length;
  71042. if (objLen > MAXINT32) {
  71043. throw new errors_1.InvalidArgumentError("too many elements in array");
  71044. }
  71045. const elemData = new buffer_1.WriteBuffer();
  71046. for (const item of obj) {
  71047. try {
  71048. encodeRange(elemData, item, this.subCodec, ctx);
  71049. } catch (e4) {
  71050. if (e4 instanceof errors_1.InvalidArgumentError) {
  71051. throw new errors_1.InvalidArgumentError(`invalid multirange element: ${e4.message}`);
  71052. } else {
  71053. throw e4;
  71054. }
  71055. }
  71056. }
  71057. const elemBuf = elemData.unwrap();
  71058. const elemDataLen = elemBuf.length;
  71059. if (elemDataLen > MAXINT32 - 4) {
  71060. throw new errors_1.InvalidArgumentError(`size of encoded multirange datum exceeds the maximum allowed ${MAXINT32 - 4} bytes`);
  71061. }
  71062. buf.writeInt32(4 + elemDataLen);
  71063. buf.writeInt32(objLen);
  71064. buf.writeBuffer(elemBuf);
  71065. }
  71066. decode(buf, ctx) {
  71067. const elemCount = buf.readInt32();
  71068. const result = new Array(elemCount);
  71069. const elemBuf = buffer_1.ReadBuffer.alloc();
  71070. const subCodec = this.subCodec;
  71071. for (let i4 = 0; i4 < elemCount; i4++) {
  71072. const elemLen = buf.readInt32();
  71073. if (elemLen === -1) {
  71074. throw new errors_1.ProtocolError("unexpected NULL element in multirange value");
  71075. } else {
  71076. buf.sliceInto(elemBuf, elemLen);
  71077. const elem = decodeRange(elemBuf, subCodec, ctx);
  71078. if (elemBuf.length) {
  71079. throw new errors_1.ProtocolError(`unexpected trailing data in buffer after multirange element decoding: ${elemBuf.length}`);
  71080. }
  71081. result[i4] = elem;
  71082. elemBuf.finish();
  71083. }
  71084. }
  71085. return new range_1.MultiRange(result);
  71086. }
  71087. getSubcodecs() {
  71088. return [this.subCodec];
  71089. }
  71090. getKind() {
  71091. return "multirange";
  71092. }
  71093. };
  71094. exports2.MultiRangeCodec = MultiRangeCodec;
  71095. }
  71096. });
  71097. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/namedtuple.js
  71098. var require_namedtuple = __commonJS({
  71099. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/namedtuple.js"(exports2) {
  71100. "use strict";
  71101. Object.defineProperty(exports2, "__esModule", { value: true });
  71102. exports2.NamedTupleCodec = void 0;
  71103. var ifaces_1 = require_ifaces();
  71104. var buffer_1 = require_buffer();
  71105. var errors_1 = require_errors();
  71106. var NamedTupleCodec = class extends ifaces_1.Codec {
  71107. subCodecs;
  71108. names;
  71109. typeName;
  71110. constructor(tid, typeName, codecs, names) {
  71111. super(tid);
  71112. this.subCodecs = codecs;
  71113. this.names = names;
  71114. this.typeName = typeName;
  71115. }
  71116. encode(buf, object, ctx) {
  71117. if (typeof object !== "object" || Array.isArray(object)) {
  71118. throw new errors_1.InvalidArgumentError(`an object was expected, got "${object}"`);
  71119. }
  71120. const codecsLen = this.subCodecs.length;
  71121. if (Object.keys(object).length !== codecsLen) {
  71122. throw new errors_1.QueryArgumentError(`expected ${codecsLen} element${codecsLen === 1 ? "" : "s"} in named tuple, got ${Object.keys(object).length}`);
  71123. }
  71124. const elemData = new buffer_1.WriteBuffer();
  71125. for (let i4 = 0; i4 < codecsLen; i4++) {
  71126. const key = this.names[i4];
  71127. const val2 = object[key];
  71128. if (val2 == null) {
  71129. throw new errors_1.MissingArgumentError(`element '${key}' in named tuple cannot be 'null'`);
  71130. } else {
  71131. elemData.writeInt32(0);
  71132. try {
  71133. this.subCodecs[i4].encode(elemData, val2, ctx);
  71134. } catch (e4) {
  71135. if (e4 instanceof errors_1.QueryArgumentError) {
  71136. throw new errors_1.InvalidArgumentError(`invalid element '${key}' in named tuple: ${e4.message}`);
  71137. } else {
  71138. throw e4;
  71139. }
  71140. }
  71141. }
  71142. }
  71143. const elemBuf = elemData.unwrap();
  71144. buf.writeInt32(4 + elemBuf.length);
  71145. buf.writeInt32(codecsLen);
  71146. buf.writeBuffer(elemBuf);
  71147. }
  71148. decode(buf, ctx) {
  71149. const els = buf.readUInt32();
  71150. const subCodecs = this.subCodecs;
  71151. if (els !== subCodecs.length) {
  71152. throw new errors_1.ProtocolError(`cannot decode NamedTuple: expected ${subCodecs.length} elements, got ${els}`);
  71153. }
  71154. const elemBuf = buffer_1.ReadBuffer.alloc();
  71155. const names = this.names;
  71156. const result = {};
  71157. for (let i4 = 0; i4 < els; i4++) {
  71158. buf.discard(4);
  71159. const elemLen = buf.readInt32();
  71160. let val2 = null;
  71161. if (elemLen !== -1) {
  71162. buf.sliceInto(elemBuf, elemLen);
  71163. val2 = subCodecs[i4].decode(elemBuf, ctx);
  71164. elemBuf.finish();
  71165. }
  71166. result[names[i4]] = val2;
  71167. }
  71168. return result;
  71169. }
  71170. getSubcodecs() {
  71171. return Array.from(this.subCodecs);
  71172. }
  71173. getNames() {
  71174. return Array.from(this.names);
  71175. }
  71176. getKind() {
  71177. return "namedtuple";
  71178. }
  71179. };
  71180. exports2.NamedTupleCodec = NamedTupleCodec;
  71181. }
  71182. });
  71183. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/array.js
  71184. var require_array = __commonJS({
  71185. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/array.js"(exports2) {
  71186. "use strict";
  71187. Object.defineProperty(exports2, "__esModule", { value: true });
  71188. exports2.ArrayCodec = void 0;
  71189. var ifaces_1 = require_ifaces();
  71190. var buffer_1 = require_buffer();
  71191. var tuple_1 = require_tuple();
  71192. var range_1 = require_range3();
  71193. var errors_1 = require_errors();
  71194. var namedtuple_1 = require_namedtuple();
  71195. var ArrayCodec = class extends ifaces_1.Codec {
  71196. subCodec;
  71197. len;
  71198. typeName;
  71199. constructor(tid, typeName, subCodec, len) {
  71200. super(tid);
  71201. this.subCodec = subCodec;
  71202. this.len = len;
  71203. this.typeName = typeName;
  71204. }
  71205. encode(buf, obj, ctx) {
  71206. if (!(this.subCodec instanceof ifaces_1.ScalarCodec || this.subCodec instanceof tuple_1.TupleCodec || this.subCodec instanceof namedtuple_1.NamedTupleCodec || this.subCodec instanceof range_1.RangeCodec || this.subCodec instanceof range_1.MultiRangeCodec)) {
  71207. throw new errors_1.InvalidArgumentError("only arrays of scalars or tuples are supported");
  71208. }
  71209. if (!Array.isArray(obj) && !isTypedArray(obj)) {
  71210. throw new errors_1.InvalidArgumentError(`an array was expected (got type ${obj.constructor.name})`);
  71211. }
  71212. const subCodec = this.subCodec;
  71213. const elemData = new buffer_1.WriteBuffer();
  71214. const objLen = obj.length;
  71215. if (objLen > 2147483647) {
  71216. throw new errors_1.InvalidArgumentError("too many elements in array");
  71217. }
  71218. for (let i4 = 0; i4 < objLen; i4++) {
  71219. const item = obj[i4];
  71220. if (item == null) {
  71221. elemData.writeInt32(-1);
  71222. } else {
  71223. subCodec.encode(elemData, item, ctx);
  71224. }
  71225. }
  71226. const elemBuf = elemData.unwrap();
  71227. buf.writeInt32(12 + 8 + elemBuf.length);
  71228. buf.writeInt32(1);
  71229. buf.writeInt32(0);
  71230. buf.writeInt32(0);
  71231. buf.writeInt32(objLen);
  71232. buf.writeInt32(1);
  71233. buf.writeBuffer(elemBuf);
  71234. }
  71235. decode(buf, ctx) {
  71236. const ndims = buf.readInt32();
  71237. buf.discard(4);
  71238. buf.discard(4);
  71239. if (ndims === 0) {
  71240. return [];
  71241. }
  71242. if (ndims !== 1) {
  71243. throw new errors_1.ProtocolError("only 1-dimensional arrays are supported");
  71244. }
  71245. const len = buf.readUInt32();
  71246. if (this.len !== -1 && len !== this.len) {
  71247. throw new errors_1.ProtocolError(`invalid array size: received ${len}, expected ${this.len}`);
  71248. }
  71249. buf.discard(4);
  71250. const result = new Array(len);
  71251. const elemBuf = buffer_1.ReadBuffer.alloc();
  71252. const subCodec = this.subCodec;
  71253. for (let i4 = 0; i4 < len; i4++) {
  71254. const elemLen = buf.readInt32();
  71255. if (elemLen === -1) {
  71256. result[i4] = null;
  71257. } else {
  71258. buf.sliceInto(elemBuf, elemLen);
  71259. result[i4] = subCodec.decode(elemBuf, ctx);
  71260. elemBuf.finish();
  71261. }
  71262. }
  71263. return result;
  71264. }
  71265. getSubcodecs() {
  71266. return [this.subCodec];
  71267. }
  71268. getKind() {
  71269. return "array";
  71270. }
  71271. };
  71272. exports2.ArrayCodec = ArrayCodec;
  71273. function isTypedArray(obj) {
  71274. return !!(obj.buffer instanceof ArrayBuffer && obj.BYTES_PER_ELEMENT);
  71275. }
  71276. }
  71277. });
  71278. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/enum.js
  71279. var require_enum = __commonJS({
  71280. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/enum.js"(exports2) {
  71281. "use strict";
  71282. Object.defineProperty(exports2, "__esModule", { value: true });
  71283. exports2.EnumCodec = void 0;
  71284. var text_1 = require_text();
  71285. var EnumCodec = class extends text_1.StrCodec {
  71286. values;
  71287. constructor(tid, typeName, values) {
  71288. super(tid, typeName);
  71289. this.values = values;
  71290. }
  71291. };
  71292. exports2.EnumCodec = EnumCodec;
  71293. }
  71294. });
  71295. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/ifaces.js
  71296. var require_ifaces2 = __commonJS({
  71297. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/ifaces.js"(exports2) {
  71298. "use strict";
  71299. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  71300. if (k22 === void 0) k22 = k3;
  71301. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  71302. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  71303. desc = { enumerable: true, get: function() {
  71304. return m4[k3];
  71305. } };
  71306. }
  71307. Object.defineProperty(o3, k22, desc);
  71308. } : function(o3, m4, k3, k22) {
  71309. if (k22 === void 0) k22 = k3;
  71310. o3[k22] = m4[k3];
  71311. });
  71312. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  71313. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  71314. } : function(o3, v6) {
  71315. o3["default"] = v6;
  71316. });
  71317. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  71318. if (mod && mod.__esModule) return mod;
  71319. var result = {};
  71320. if (mod != null) {
  71321. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  71322. }
  71323. __setModuleDefault2(result, mod);
  71324. return result;
  71325. };
  71326. Object.defineProperty(exports2, "__esModule", { value: true });
  71327. exports2.Language = exports2.Cardinality = exports2.OutputFormat = void 0;
  71328. var chars = __importStar2(require_chars());
  71329. var OutputFormat;
  71330. (function(OutputFormat2) {
  71331. OutputFormat2[OutputFormat2["BINARY"] = chars.$b] = "BINARY";
  71332. OutputFormat2[OutputFormat2["JSON"] = chars.$j] = "JSON";
  71333. OutputFormat2[OutputFormat2["NONE"] = chars.$n] = "NONE";
  71334. })(OutputFormat || (exports2.OutputFormat = OutputFormat = {}));
  71335. var Cardinality;
  71336. (function(Cardinality2) {
  71337. Cardinality2[Cardinality2["NO_RESULT"] = chars.$n] = "NO_RESULT";
  71338. Cardinality2[Cardinality2["AT_MOST_ONE"] = chars.$o] = "AT_MOST_ONE";
  71339. Cardinality2[Cardinality2["ONE"] = chars.$A] = "ONE";
  71340. Cardinality2[Cardinality2["MANY"] = chars.$m] = "MANY";
  71341. Cardinality2[Cardinality2["AT_LEAST_ONE"] = chars.$M] = "AT_LEAST_ONE";
  71342. })(Cardinality || (exports2.Cardinality = Cardinality = {}));
  71343. var Language;
  71344. (function(Language2) {
  71345. Language2[Language2["EDGEQL"] = chars.$E] = "EDGEQL";
  71346. Language2[Language2["SQL"] = chars.$S] = "SQL";
  71347. })(Language || (exports2.Language = Language = {}));
  71348. }
  71349. });
  71350. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/object.js
  71351. var require_object = __commonJS({
  71352. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/object.js"(exports2) {
  71353. "use strict";
  71354. Object.defineProperty(exports2, "__esModule", { value: true });
  71355. exports2.ObjectCodec = void 0;
  71356. var ifaces_1 = require_ifaces2();
  71357. var ifaces_2 = require_ifaces();
  71358. var buffer_1 = require_buffer();
  71359. var errors_1 = require_errors();
  71360. var EDGE_POINTER_IS_IMPLICIT = 1 << 0;
  71361. var EDGE_POINTER_IS_LINKPROP = 1 << 1;
  71362. var ObjectCodec = class extends ifaces_2.Codec {
  71363. codecs;
  71364. fields;
  71365. namesSet;
  71366. cardinalities;
  71367. constructor(tid, codecs, names, flags, cards) {
  71368. super(tid);
  71369. this.codecs = codecs;
  71370. this.fields = new Array(names.length);
  71371. this.namesSet = /* @__PURE__ */ new Set();
  71372. this.cardinalities = cards;
  71373. for (let i4 = 0; i4 < names.length; i4++) {
  71374. const isLinkprop = !!(flags[i4] & EDGE_POINTER_IS_LINKPROP);
  71375. const name = isLinkprop ? `@${names[i4]}` : names[i4];
  71376. this.fields[i4] = {
  71377. name,
  71378. implicit: !!(flags[i4] & EDGE_POINTER_IS_IMPLICIT),
  71379. linkprop: isLinkprop,
  71380. cardinality: cards[i4]
  71381. };
  71382. this.namesSet.add(name);
  71383. }
  71384. }
  71385. encode(_buf, _object) {
  71386. throw new errors_1.InvalidArgumentError("Objects cannot be passed as arguments");
  71387. }
  71388. encodeArgs(args, ctx) {
  71389. if (this.fields[0].name === "0" || this.fields[0].name === "1") {
  71390. return this._encodePositionalArgs(args, ctx);
  71391. }
  71392. return this._encodeNamedArgs(args, ctx);
  71393. }
  71394. _encodePositionalArgs(args, ctx) {
  71395. if (!Array.isArray(args)) {
  71396. throw new errors_1.InvalidArgumentError("an array of arguments was expected");
  71397. }
  71398. const codecs = this.codecs;
  71399. const codecsLen = codecs.length;
  71400. if (args.length !== codecsLen) {
  71401. throw new errors_1.QueryArgumentError(`expected ${codecsLen} argument${codecsLen === 1 ? "" : "s"}, got ${args.length}`);
  71402. }
  71403. const elemData = new buffer_1.WriteBuffer();
  71404. for (let i4 = 0; i4 < codecsLen; i4++) {
  71405. elemData.writeInt32(0);
  71406. const arg = args[i4];
  71407. if (arg == null) {
  71408. const card = this.cardinalities[i4];
  71409. if (card === ifaces_1.Cardinality.ONE || card === ifaces_1.Cardinality.AT_LEAST_ONE) {
  71410. throw new errors_1.MissingArgumentError(`argument ${this.fields[i4].name} is required, but received ${arg}`);
  71411. }
  71412. elemData.writeInt32(-1);
  71413. } else {
  71414. const codec = codecs[i4];
  71415. codec.encode(elemData, arg, ctx);
  71416. }
  71417. }
  71418. const elemBuf = elemData.unwrap();
  71419. const buf = new buffer_1.WriteBuffer();
  71420. buf.writeInt32(4 + elemBuf.length);
  71421. buf.writeInt32(codecsLen);
  71422. buf.writeBuffer(elemBuf);
  71423. return buf.unwrap();
  71424. }
  71425. _encodeNamedArgs(args, ctx) {
  71426. if (args == null) {
  71427. throw new errors_1.MissingArgumentError("One or more named arguments expected, received null");
  71428. }
  71429. const keys = Object.keys(args);
  71430. const fields = this.fields;
  71431. const namesSet = this.namesSet;
  71432. const codecs = this.codecs;
  71433. const codecsLen = codecs.length;
  71434. if (keys.length > codecsLen) {
  71435. const extraKeys = keys.filter((key) => !namesSet.has(key));
  71436. throw new errors_1.UnknownArgumentError(`Unused named argument${extraKeys.length === 1 ? "" : "s"}: "${extraKeys.join('", "')}"`);
  71437. }
  71438. const elemData = new buffer_1.WriteBuffer();
  71439. for (let i4 = 0; i4 < codecsLen; i4++) {
  71440. const key = fields[i4].name;
  71441. const val2 = args[key];
  71442. elemData.writeInt32(0);
  71443. if (val2 == null) {
  71444. const card = this.cardinalities[i4];
  71445. if (card === ifaces_1.Cardinality.ONE || card === ifaces_1.Cardinality.AT_LEAST_ONE) {
  71446. throw new errors_1.MissingArgumentError(`argument ${this.fields[i4].name} is required, but received ${val2}`);
  71447. }
  71448. elemData.writeInt32(-1);
  71449. } else {
  71450. const codec = codecs[i4];
  71451. codec.encode(elemData, val2, ctx);
  71452. }
  71453. }
  71454. const elemBuf = elemData.unwrap();
  71455. const buf = new buffer_1.WriteBuffer();
  71456. buf.writeInt32(4 + elemBuf.length);
  71457. buf.writeInt32(codecsLen);
  71458. buf.writeBuffer(elemBuf);
  71459. return buf.unwrap();
  71460. }
  71461. decode(buf, ctx) {
  71462. const codecs = this.codecs;
  71463. const fields = this.fields;
  71464. const els = buf.readUInt32();
  71465. if (els !== codecs.length) {
  71466. throw new errors_1.ProtocolError(`cannot decode Object: expected ${codecs.length} elements, got ${els}`);
  71467. }
  71468. const elemBuf = buffer_1.ReadBuffer.alloc();
  71469. const result = {};
  71470. for (let i4 = 0; i4 < els; i4++) {
  71471. buf.discard(4);
  71472. const elemLen = buf.readInt32();
  71473. const name = fields[i4].name;
  71474. let val2 = null;
  71475. if (elemLen !== -1) {
  71476. buf.sliceInto(elemBuf, elemLen);
  71477. val2 = codecs[i4].decode(elemBuf, ctx);
  71478. elemBuf.finish();
  71479. }
  71480. result[name] = val2;
  71481. }
  71482. return result;
  71483. }
  71484. getSubcodecs() {
  71485. return Array.from(this.codecs);
  71486. }
  71487. getFields() {
  71488. return Array.from(this.fields);
  71489. }
  71490. getKind() {
  71491. return "object";
  71492. }
  71493. };
  71494. exports2.ObjectCodec = ObjectCodec;
  71495. }
  71496. });
  71497. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/set.js
  71498. var require_set = __commonJS({
  71499. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/set.js"(exports2) {
  71500. "use strict";
  71501. Object.defineProperty(exports2, "__esModule", { value: true });
  71502. exports2.SetCodec = void 0;
  71503. var ifaces_1 = require_ifaces();
  71504. var buffer_1 = require_buffer();
  71505. var array_1 = require_array();
  71506. var errors_1 = require_errors();
  71507. var SetCodec = class extends ifaces_1.Codec {
  71508. subCodec;
  71509. constructor(tid, subCodec) {
  71510. super(tid);
  71511. this.subCodec = subCodec;
  71512. }
  71513. encode(_buf, _obj) {
  71514. throw new errors_1.InvalidArgumentError("Sets cannot be passed in query arguments");
  71515. }
  71516. decode(buf, ctx) {
  71517. if (this.subCodec instanceof array_1.ArrayCodec) {
  71518. return this.decodeSetOfArrays(buf, ctx);
  71519. } else {
  71520. return this.decodeSet(buf, ctx);
  71521. }
  71522. }
  71523. decodeSetOfArrays(buf, ctx) {
  71524. const ndims = buf.readInt32();
  71525. buf.discard(4);
  71526. buf.discard(4);
  71527. if (ndims === 0) {
  71528. return [];
  71529. }
  71530. if (ndims !== 1) {
  71531. throw new errors_1.ProtocolError(`expected 1-dimensional array of records of arrays`);
  71532. }
  71533. const len = buf.readUInt32();
  71534. buf.discard(4);
  71535. const result = new Array(len);
  71536. const elemBuf = buffer_1.ReadBuffer.alloc();
  71537. const subCodec = this.subCodec;
  71538. for (let i4 = 0; i4 < len; i4++) {
  71539. buf.discard(4);
  71540. const recSize = buf.readUInt32();
  71541. if (recSize !== 1) {
  71542. throw new errors_1.ProtocolError("expected a record with a single element as an array set element envelope");
  71543. }
  71544. buf.discard(4);
  71545. const elemLen = buf.readInt32();
  71546. if (elemLen === -1) {
  71547. throw new errors_1.ProtocolError("unexpected NULL value in array set element");
  71548. }
  71549. buf.sliceInto(elemBuf, elemLen);
  71550. result[i4] = subCodec.decode(elemBuf, ctx);
  71551. elemBuf.finish();
  71552. }
  71553. return result;
  71554. }
  71555. decodeSet(buf, ctx) {
  71556. const ndims = buf.readInt32();
  71557. buf.discard(4);
  71558. buf.discard(4);
  71559. if (ndims === 0) {
  71560. return [];
  71561. }
  71562. if (ndims !== 1) {
  71563. throw new errors_1.ProtocolError(`invalid set dimensinality: ${ndims}`);
  71564. }
  71565. const len = buf.readUInt32();
  71566. buf.discard(4);
  71567. const result = new Array(len);
  71568. const elemBuf = buffer_1.ReadBuffer.alloc();
  71569. const subCodec = this.subCodec;
  71570. for (let i4 = 0; i4 < len; i4++) {
  71571. const elemLen = buf.readInt32();
  71572. if (elemLen === -1) {
  71573. result[i4] = null;
  71574. } else {
  71575. buf.sliceInto(elemBuf, elemLen);
  71576. result[i4] = subCodec.decode(elemBuf, ctx);
  71577. elemBuf.finish();
  71578. }
  71579. }
  71580. return result;
  71581. }
  71582. getSubcodecs() {
  71583. return [this.subCodec];
  71584. }
  71585. getKind() {
  71586. return "set";
  71587. }
  71588. };
  71589. exports2.SetCodec = SetCodec;
  71590. }
  71591. });
  71592. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/record.js
  71593. var require_record = __commonJS({
  71594. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/record.js"(exports2) {
  71595. "use strict";
  71596. Object.defineProperty(exports2, "__esModule", { value: true });
  71597. exports2.RecordCodec = exports2.SQLRowModeObject = exports2.SQLRowModeArray = void 0;
  71598. var ifaces_1 = require_ifaces();
  71599. var buffer_1 = require_buffer();
  71600. var errors_1 = require_errors();
  71601. var SQLRowArrayCodec = {
  71602. fromDatabase(values, _desc) {
  71603. return values;
  71604. },
  71605. toDatabase() {
  71606. throw new errors_1.InternalClientError("cannot encode SQL record as a query argument");
  71607. }
  71608. };
  71609. var SQLRowObjectCodec = {
  71610. fromDatabase(values, { names }) {
  71611. return Object.fromEntries(names.map((key, index6) => [key, values[index6]]));
  71612. },
  71613. toDatabase() {
  71614. throw new errors_1.InternalClientError("cannot encode SQL record as a query argument");
  71615. }
  71616. };
  71617. exports2.SQLRowModeArray = {
  71618. _private_sql_row: SQLRowArrayCodec
  71619. };
  71620. exports2.SQLRowModeObject = {
  71621. _private_sql_row: SQLRowObjectCodec
  71622. };
  71623. var RecordCodec = class extends ifaces_1.Codec {
  71624. subCodecs;
  71625. names;
  71626. constructor(tid, codecs, names) {
  71627. super(tid);
  71628. this.subCodecs = codecs;
  71629. this.names = names;
  71630. }
  71631. encode(_buf, _object) {
  71632. throw new errors_1.InvalidArgumentError("SQL records cannot be passed as arguments");
  71633. }
  71634. decode(buf, ctx) {
  71635. const els = buf.readUInt32();
  71636. const subCodecs = this.subCodecs;
  71637. if (els !== subCodecs.length) {
  71638. throw new errors_1.ProtocolError(`cannot decode Record: expected ${subCodecs.length} elements, got ${els}`);
  71639. }
  71640. const elemBuf = buffer_1.ReadBuffer.alloc();
  71641. const overload = ctx.getContainerOverload("_private_sql_row");
  71642. if (overload != null && overload !== SQLRowObjectCodec) {
  71643. const result = new Array(els);
  71644. for (let i4 = 0; i4 < els; i4++) {
  71645. buf.discard(4);
  71646. const elemLen = buf.readInt32();
  71647. let val2 = null;
  71648. if (elemLen !== -1) {
  71649. buf.sliceInto(elemBuf, elemLen);
  71650. val2 = subCodecs[i4].decode(elemBuf, ctx);
  71651. elemBuf.finish();
  71652. }
  71653. result[i4] = val2;
  71654. }
  71655. if (overload !== SQLRowArrayCodec) {
  71656. return overload.fromDatabase(result, { names: this.names });
  71657. }
  71658. return result;
  71659. } else {
  71660. const names = this.names;
  71661. const result = {};
  71662. for (let i4 = 0; i4 < els; i4++) {
  71663. buf.discard(4);
  71664. const elemLen = buf.readInt32();
  71665. let val2 = null;
  71666. if (elemLen !== -1) {
  71667. buf.sliceInto(elemBuf, elemLen);
  71668. val2 = subCodecs[i4].decode(elemBuf, ctx);
  71669. elemBuf.finish();
  71670. }
  71671. result[names[i4]] = val2;
  71672. }
  71673. return result;
  71674. }
  71675. }
  71676. getSubcodecs() {
  71677. return Array.from(this.subCodecs);
  71678. }
  71679. getNames() {
  71680. return Array.from(this.names);
  71681. }
  71682. getKind() {
  71683. return "record";
  71684. }
  71685. };
  71686. exports2.RecordCodec = RecordCodec;
  71687. }
  71688. });
  71689. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/sparseObject.js
  71690. var require_sparseObject = __commonJS({
  71691. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/sparseObject.js"(exports2) {
  71692. "use strict";
  71693. Object.defineProperty(exports2, "__esModule", { value: true });
  71694. exports2.SparseObjectCodec = void 0;
  71695. var ifaces_1 = require_ifaces();
  71696. var buffer_1 = require_buffer();
  71697. var errors_1 = require_errors();
  71698. var SparseObjectCodec = class extends ifaces_1.Codec {
  71699. codecs;
  71700. names;
  71701. constructor(tid, codecs, names) {
  71702. super(tid);
  71703. this.codecs = codecs;
  71704. this.names = names;
  71705. }
  71706. encode(buf, object, ctx) {
  71707. const elemBuf = new buffer_1.WriteBuffer();
  71708. let objLen = 0;
  71709. for (const [key, val2] of Object.entries(object)) {
  71710. if (val2 !== void 0) {
  71711. const i4 = this.names.indexOf(key);
  71712. if (i4 === -1) {
  71713. throw new errors_1.UnknownArgumentError(this.names.length ? `invalid global '${key}', valid globals are ${this.names.map((n3) => `'${n3}'`).join(", ")}` : `invalid global '${key}', no valid globals exist`);
  71714. }
  71715. objLen += 1;
  71716. elemBuf.writeInt32(i4);
  71717. if (val2 === null) {
  71718. elemBuf.writeInt32(-1);
  71719. } else {
  71720. this.codecs[i4].encode(elemBuf, val2, ctx);
  71721. }
  71722. }
  71723. }
  71724. const elemData = elemBuf.unwrap();
  71725. buf.writeInt32(4 + elemData.length);
  71726. buf.writeInt32(objLen);
  71727. buf.writeBuffer(elemData);
  71728. }
  71729. decode(buf, ctx) {
  71730. const codecs = this.codecs;
  71731. const names = this.names;
  71732. const els = buf.readUInt32();
  71733. const elemBuf = buffer_1.ReadBuffer.alloc();
  71734. const result = {};
  71735. for (let _3 = 0; _3 < els; _3++) {
  71736. const i4 = buf.readUInt32();
  71737. const elemLen = buf.readInt32();
  71738. const name = names[i4];
  71739. let val2 = null;
  71740. if (elemLen !== -1) {
  71741. buf.sliceInto(elemBuf, elemLen);
  71742. val2 = codecs[i4].decode(elemBuf, ctx);
  71743. elemBuf.finish();
  71744. }
  71745. result[name] = val2;
  71746. }
  71747. return result;
  71748. }
  71749. getSubcodecs() {
  71750. return Array.from(this.codecs);
  71751. }
  71752. getKind() {
  71753. return "sparse_object";
  71754. }
  71755. };
  71756. exports2.SparseObjectCodec = SparseObjectCodec;
  71757. }
  71758. });
  71759. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/registry.js
  71760. var require_registry = __commonJS({
  71761. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/registry.js"(exports2) {
  71762. "use strict";
  71763. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  71764. return mod && mod.__esModule ? mod : { "default": mod };
  71765. };
  71766. Object.defineProperty(exports2, "__esModule", { value: true });
  71767. exports2.CodecsRegistry = void 0;
  71768. var buffer_1 = require_buffer();
  71769. var lru_1 = __importDefault2(require_lru());
  71770. var ifaces_1 = require_ifaces();
  71771. var codecs_1 = require_codecs();
  71772. var consts_1 = require_consts();
  71773. var tuple_1 = require_tuple();
  71774. var array_1 = require_array();
  71775. var namedtuple_1 = require_namedtuple();
  71776. var enum_1 = require_enum();
  71777. var object_1 = require_object();
  71778. var set_1 = require_set();
  71779. var record_1 = require_record();
  71780. var range_1 = require_range3();
  71781. var utils_1 = require_utils2();
  71782. var sparseObject_1 = require_sparseObject();
  71783. var errors_1 = require_errors();
  71784. var CODECS_CACHE_SIZE = 1e3;
  71785. var CODECS_BUILD_CACHE_SIZE = 200;
  71786. var CTYPE_SET = 0;
  71787. var CTYPE_SHAPE = 1;
  71788. var CTYPE_BASE_SCALAR = 2;
  71789. var CTYPE_SCALAR = 3;
  71790. var CTYPE_TUPLE = 4;
  71791. var CTYPE_NAMEDTUPLE = 5;
  71792. var CTYPE_ARRAY = 6;
  71793. var CTYPE_ENUM = 7;
  71794. var CTYPE_INPUT_SHAPE = 8;
  71795. var CTYPE_RANGE = 9;
  71796. var CTYPE_OBJECT = 10;
  71797. var CTYPE_COMPOUND = 11;
  71798. var CTYPE_MULTIRANGE = 12;
  71799. var CTYPE_RECORD = 13;
  71800. var CodecsRegistry = class {
  71801. codecsBuildCache;
  71802. codecs;
  71803. constructor() {
  71804. this.codecs = new lru_1.default({ capacity: CODECS_CACHE_SIZE });
  71805. this.codecsBuildCache = new lru_1.default({ capacity: CODECS_BUILD_CACHE_SIZE });
  71806. }
  71807. hasCodec(typeId) {
  71808. if (this.codecs.has(typeId)) {
  71809. return true;
  71810. }
  71811. return typeId === consts_1.NULL_CODEC_ID || typeId === tuple_1.EMPTY_TUPLE_CODEC_ID;
  71812. }
  71813. getCodec(typeId) {
  71814. const codec = this.codecs.get(typeId);
  71815. if (codec != null) {
  71816. return codec;
  71817. }
  71818. if (typeId === tuple_1.EMPTY_TUPLE_CODEC_ID) {
  71819. return tuple_1.EMPTY_TUPLE_CODEC;
  71820. }
  71821. if (typeId === consts_1.NULL_CODEC_ID) {
  71822. return codecs_1.NULL_CODEC;
  71823. }
  71824. return null;
  71825. }
  71826. buildCodec(spec, protocolVersion) {
  71827. if (!(0, utils_1.versionGreaterThanOrEqual)(protocolVersion, [2, 0])) {
  71828. throw new errors_1.UnsupportedProtocolVersionError("unsupported old protocol version v1; downgrade to the previous version of gel-js");
  71829. }
  71830. const frb = new buffer_1.ReadBuffer(spec);
  71831. const codecsList = [];
  71832. let codec = null;
  71833. while (frb.length) {
  71834. const descLen = frb.readInt32();
  71835. const descBuf = buffer_1.ReadBuffer.alloc();
  71836. frb.sliceInto(descBuf, descLen);
  71837. codec = this._buildCodec(descBuf, codecsList);
  71838. descBuf.finish("unexpected trailing data in type descriptor buffer");
  71839. if (codec == null) {
  71840. continue;
  71841. }
  71842. codecsList.push(codec);
  71843. this.codecs.set(codec.tid, codec);
  71844. }
  71845. if (!codecsList.length) {
  71846. throw new errors_1.InternalClientError("could not build a codec");
  71847. }
  71848. return codecsList[codecsList.length - 1];
  71849. }
  71850. _buildCodec(frb, cl) {
  71851. const t4 = frb.readUInt8();
  71852. const tid = frb.readUUID();
  71853. let res = this.codecs.get(tid);
  71854. if (res == null) {
  71855. res = this.codecsBuildCache.get(tid);
  71856. }
  71857. if (res != null) {
  71858. frb.discard(frb.length);
  71859. return res;
  71860. }
  71861. switch (t4) {
  71862. case CTYPE_BASE_SCALAR: {
  71863. res = codecs_1.SCALAR_CODECS.get(tid);
  71864. if (!res) {
  71865. if (consts_1.KNOWN_TYPES.has(tid)) {
  71866. throw new errors_1.InternalClientError(`no JS codec for ${consts_1.KNOWN_TYPES.get(tid)}`);
  71867. }
  71868. throw new errors_1.InternalClientError(`no JS codec for the type with ID ${tid}`);
  71869. }
  71870. if (!(res instanceof ifaces_1.ScalarCodec)) {
  71871. throw new errors_1.ProtocolError("could not build scalar codec: base scalar is a non-scalar codec");
  71872. }
  71873. break;
  71874. }
  71875. case CTYPE_SHAPE:
  71876. case CTYPE_INPUT_SHAPE: {
  71877. if (t4 === CTYPE_SHAPE) {
  71878. frb.readBoolean();
  71879. frb.readUInt16();
  71880. }
  71881. const els = frb.readUInt16();
  71882. const codecs = new Array(els);
  71883. const names = new Array(els);
  71884. const flags = new Array(els);
  71885. const cards = new Array(els);
  71886. for (let i4 = 0; i4 < els; i4++) {
  71887. const flag = frb.readUInt32();
  71888. const card = frb.readUInt8();
  71889. const name = frb.readString();
  71890. const pos = frb.readUInt16();
  71891. const subCodec = cl[pos];
  71892. if (subCodec == null) {
  71893. throw new errors_1.ProtocolError("could not build object codec: missing subcodec");
  71894. }
  71895. codecs[i4] = subCodec;
  71896. names[i4] = name;
  71897. flags[i4] = flag;
  71898. cards[i4] = card;
  71899. if (t4 === CTYPE_SHAPE) {
  71900. frb.readUInt16();
  71901. }
  71902. }
  71903. res = t4 === CTYPE_INPUT_SHAPE ? new sparseObject_1.SparseObjectCodec(tid, codecs, names) : new object_1.ObjectCodec(tid, codecs, names, flags, cards);
  71904. break;
  71905. }
  71906. case CTYPE_SET: {
  71907. const pos = frb.readUInt16();
  71908. const subCodec = cl[pos];
  71909. if (subCodec == null) {
  71910. throw new errors_1.ProtocolError("could not build set codec: missing subcodec");
  71911. }
  71912. res = new set_1.SetCodec(tid, subCodec);
  71913. break;
  71914. }
  71915. case CTYPE_SCALAR: {
  71916. const typeName = frb.readString();
  71917. frb.readBoolean();
  71918. const ancestorCount = frb.readUInt16();
  71919. const ancestors = [];
  71920. for (let i4 = 0; i4 < ancestorCount; i4++) {
  71921. const ancestorPos = frb.readUInt16();
  71922. const ancestorCodec = cl[ancestorPos];
  71923. if (ancestorCodec == null) {
  71924. throw new errors_1.ProtocolError("could not build scalar codec: missing a codec for base scalar");
  71925. }
  71926. if (!(ancestorCodec instanceof ifaces_1.ScalarCodec)) {
  71927. throw new errors_1.ProtocolError(`a scalar codec expected for base scalar type, got ${ancestorCodec}`);
  71928. }
  71929. ancestors.push(ancestorCodec);
  71930. }
  71931. if (ancestorCount === 0) {
  71932. res = codecs_1.SCALAR_CODECS.get(tid);
  71933. if (res == null) {
  71934. if (consts_1.KNOWN_TYPES.has(tid)) {
  71935. throw new errors_1.InternalClientError(`no JS codec for ${consts_1.KNOWN_TYPES.get(tid)}`);
  71936. }
  71937. throw new errors_1.InternalClientError(`no JS codec for the type with ID ${tid}`);
  71938. }
  71939. } else {
  71940. const baseCodec = ancestors[ancestors.length - 1];
  71941. res = baseCodec.derive(tid, typeName, ancestors);
  71942. }
  71943. break;
  71944. }
  71945. case CTYPE_ARRAY: {
  71946. const typeName = frb.readString();
  71947. frb.readBoolean();
  71948. const ancestorCount = frb.readUInt16();
  71949. for (let i4 = 0; i4 < ancestorCount; i4++) {
  71950. frb.readUInt16();
  71951. }
  71952. const pos = frb.readUInt16();
  71953. const els = frb.readUInt16();
  71954. if (els !== 1) {
  71955. throw new errors_1.ProtocolError("cannot handle arrays with more than one dimension");
  71956. }
  71957. const dimLen = frb.readInt32();
  71958. const subCodec = cl[pos];
  71959. if (subCodec == null) {
  71960. throw new errors_1.ProtocolError("could not build array codec: missing subcodec");
  71961. }
  71962. res = new array_1.ArrayCodec(tid, typeName, subCodec, dimLen);
  71963. break;
  71964. }
  71965. case CTYPE_TUPLE: {
  71966. const typeName = frb.readString();
  71967. frb.readBoolean();
  71968. const ancestorCount = frb.readUInt16();
  71969. for (let i4 = 0; i4 < ancestorCount; i4++) {
  71970. frb.readUInt16();
  71971. }
  71972. const els = frb.readUInt16();
  71973. if (els === 0) {
  71974. res = tuple_1.EMPTY_TUPLE_CODEC;
  71975. } else {
  71976. const codecs = new Array(els);
  71977. for (let i4 = 0; i4 < els; i4++) {
  71978. const pos = frb.readUInt16();
  71979. const subCodec = cl[pos];
  71980. if (subCodec == null) {
  71981. throw new errors_1.ProtocolError("could not build tuple codec: missing subcodec");
  71982. }
  71983. codecs[i4] = subCodec;
  71984. }
  71985. res = new tuple_1.TupleCodec(tid, typeName, codecs);
  71986. }
  71987. break;
  71988. }
  71989. case CTYPE_NAMEDTUPLE: {
  71990. const typeName = frb.readString();
  71991. frb.readBoolean();
  71992. const ancestorCount = frb.readUInt16();
  71993. for (let i4 = 0; i4 < ancestorCount; i4++) {
  71994. frb.readUInt16();
  71995. }
  71996. const els = frb.readUInt16();
  71997. const codecs = new Array(els);
  71998. const names = new Array(els);
  71999. for (let i4 = 0; i4 < els; i4++) {
  72000. names[i4] = frb.readString();
  72001. const pos = frb.readUInt16();
  72002. const subCodec = cl[pos];
  72003. if (subCodec == null) {
  72004. throw new errors_1.ProtocolError("could not build namedtuple codec: missing subcodec");
  72005. }
  72006. codecs[i4] = subCodec;
  72007. }
  72008. res = new namedtuple_1.NamedTupleCodec(tid, typeName, codecs, names);
  72009. break;
  72010. }
  72011. case CTYPE_RECORD: {
  72012. const els = frb.readUInt16();
  72013. const codecs = new Array(els);
  72014. const names = new Array(els);
  72015. for (let i4 = 0; i4 < els; i4++) {
  72016. names[i4] = frb.readString();
  72017. const pos = frb.readUInt16();
  72018. const subCodec = cl[pos];
  72019. if (subCodec == null) {
  72020. throw new errors_1.ProtocolError("could not build record codec: missing subcodec");
  72021. }
  72022. codecs[i4] = subCodec;
  72023. }
  72024. res = new record_1.RecordCodec(tid, codecs, names);
  72025. break;
  72026. }
  72027. case CTYPE_ENUM: {
  72028. const typeName = frb.readString();
  72029. frb.readBoolean();
  72030. const ancestorCount = frb.readUInt16();
  72031. for (let i4 = 0; i4 < ancestorCount; i4++) {
  72032. frb.readUInt16();
  72033. }
  72034. const els = frb.readUInt16();
  72035. const values = [];
  72036. for (let i4 = 0; i4 < els; i4++) {
  72037. values.push(frb.readString());
  72038. }
  72039. res = new enum_1.EnumCodec(tid, typeName, values);
  72040. break;
  72041. }
  72042. case CTYPE_RANGE: {
  72043. const typeName = frb.readString();
  72044. frb.readBoolean();
  72045. const ancestorCount = frb.readUInt16();
  72046. for (let i4 = 0; i4 < ancestorCount; i4++) {
  72047. frb.readUInt16();
  72048. }
  72049. const pos = frb.readUInt16();
  72050. const subCodec = cl[pos];
  72051. if (subCodec == null) {
  72052. throw new errors_1.ProtocolError("could not build range codec: missing subcodec");
  72053. }
  72054. res = new range_1.RangeCodec(tid, typeName, subCodec);
  72055. break;
  72056. }
  72057. case CTYPE_OBJECT: {
  72058. frb.discard(frb.length);
  72059. res = codecs_1.NULL_CODEC;
  72060. break;
  72061. }
  72062. case CTYPE_COMPOUND: {
  72063. frb.discard(frb.length);
  72064. res = codecs_1.NULL_CODEC;
  72065. break;
  72066. }
  72067. case CTYPE_MULTIRANGE: {
  72068. const typeName = frb.readString();
  72069. frb.readBoolean();
  72070. const ancestorCount = frb.readUInt16();
  72071. for (let i4 = 0; i4 < ancestorCount; i4++) {
  72072. frb.readUInt16();
  72073. }
  72074. const pos = frb.readUInt16();
  72075. const subCodec = cl[pos];
  72076. if (subCodec == null) {
  72077. throw new errors_1.ProtocolError("could not build range codec: missing subcodec");
  72078. }
  72079. res = new range_1.MultiRangeCodec(tid, typeName, subCodec);
  72080. break;
  72081. }
  72082. }
  72083. if (res == null) {
  72084. if (consts_1.KNOWN_TYPES.has(tid)) {
  72085. throw new errors_1.InternalClientError(`could not build a codec for ${consts_1.KNOWN_TYPES.get(tid)} type`);
  72086. } else {
  72087. throw new errors_1.InternalClientError(`could not build a codec for ${tid} type`);
  72088. }
  72089. }
  72090. this.codecsBuildCache.set(tid, res);
  72091. return res;
  72092. }
  72093. };
  72094. exports2.CodecsRegistry = CodecsRegistry;
  72095. }
  72096. });
  72097. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/context.js
  72098. var require_context = __commonJS({
  72099. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/codecs/context.js"(exports2) {
  72100. "use strict";
  72101. Object.defineProperty(exports2, "__esModule", { value: true });
  72102. exports2.NOOP_CODEC_CONTEXT = exports2.CodecContext = void 0;
  72103. var NOOP = {
  72104. toDatabase(data) {
  72105. return data;
  72106. },
  72107. fromDatabase(data) {
  72108. return data;
  72109. }
  72110. };
  72111. var CodecContext = class {
  72112. spec;
  72113. map;
  72114. constructor(spec) {
  72115. if (spec === null || spec.size === 0) {
  72116. this.spec = null;
  72117. } else {
  72118. this.spec = spec;
  72119. }
  72120. this.map = /* @__PURE__ */ new Map();
  72121. }
  72122. initCodec(codec) {
  72123. const specMap = this.spec;
  72124. const targetTypeName = codec.typeName;
  72125. const s4 = specMap.get(targetTypeName);
  72126. if (s4 != null) {
  72127. this.map.set(targetTypeName, s4);
  72128. return s4;
  72129. }
  72130. const ancestors = codec.ancestors;
  72131. if (ancestors == null) {
  72132. this.map.set(targetTypeName, NOOP);
  72133. return NOOP;
  72134. }
  72135. for (let i4 = 0; i4 < ancestors.length; i4++) {
  72136. const parent = ancestors[i4];
  72137. const s5 = specMap.get(parent.typeName);
  72138. if (s5 != null) {
  72139. this.map.set(targetTypeName, s5);
  72140. return s5;
  72141. }
  72142. }
  72143. this.map.set(targetTypeName, NOOP);
  72144. return NOOP;
  72145. }
  72146. getContainerOverload(kind) {
  72147. if (this.spec === null || !this.spec.size) {
  72148. return;
  72149. }
  72150. return this.spec.get(kind);
  72151. }
  72152. hasOverload(codec) {
  72153. if (this.spec === null || !this.spec.size) {
  72154. return false;
  72155. }
  72156. const op = this.map.get(codec.typeName);
  72157. if (op === NOOP) {
  72158. return false;
  72159. }
  72160. if (op != null) {
  72161. return true;
  72162. }
  72163. return this.initCodec(codec) !== NOOP;
  72164. }
  72165. postDecode(codec, value) {
  72166. if (this.spec === null || !this.spec.size) {
  72167. return value;
  72168. }
  72169. let op = this.map.get(codec.typeName);
  72170. if (op === NOOP) {
  72171. return value;
  72172. }
  72173. if (op == null) {
  72174. op = this.initCodec(codec);
  72175. }
  72176. return op.fromDatabase(value);
  72177. }
  72178. preEncode(codec, value) {
  72179. if (this.spec === null || !this.spec.size) {
  72180. return value;
  72181. }
  72182. let op = this.map.get(codec.typeName);
  72183. if (op === NOOP) {
  72184. return value;
  72185. }
  72186. if (op == null) {
  72187. op = this.initCodec(codec);
  72188. }
  72189. return op.toDatabase(value);
  72190. }
  72191. };
  72192. exports2.CodecContext = CodecContext;
  72193. exports2.NOOP_CODEC_CONTEXT = new CodecContext(null);
  72194. }
  72195. });
  72196. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/options.js
  72197. var require_options = __commonJS({
  72198. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/options.js"(exports2) {
  72199. "use strict";
  72200. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  72201. if (k22 === void 0) k22 = k3;
  72202. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  72203. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  72204. desc = { enumerable: true, get: function() {
  72205. return m4[k3];
  72206. } };
  72207. }
  72208. Object.defineProperty(o3, k22, desc);
  72209. } : function(o3, m4, k3, k22) {
  72210. if (k22 === void 0) k22 = k3;
  72211. o3[k22] = m4[k3];
  72212. });
  72213. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  72214. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  72215. } : function(o3, v6) {
  72216. o3["default"] = v6;
  72217. });
  72218. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  72219. if (mod && mod.__esModule) return mod;
  72220. var result = {};
  72221. if (mod != null) {
  72222. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  72223. }
  72224. __setModuleDefault2(result, mod);
  72225. return result;
  72226. };
  72227. Object.defineProperty(exports2, "__esModule", { value: true });
  72228. exports2.Options = exports2.TransactionOptions = exports2.RetryOptions = exports2.logWarnings = exports2.throwWarnings = exports2.RetryCondition = exports2.IsolationLevel = void 0;
  72229. exports2.defaultBackoff = defaultBackoff;
  72230. var errors = __importStar2(require_errors());
  72231. var buffer_1 = require_buffer();
  72232. var record_1 = require_record();
  72233. var context_1 = require_context();
  72234. function defaultBackoff(attempt) {
  72235. return 2 ** attempt * 100 + Math.random() * 100;
  72236. }
  72237. var IsolationLevel;
  72238. (function(IsolationLevel2) {
  72239. IsolationLevel2["Serializable"] = "Serializable";
  72240. IsolationLevel2["RepeatableRead"] = "RepeatableRead";
  72241. IsolationLevel2["PreferRepeatableRead"] = "PreferRepeatableRead";
  72242. })(IsolationLevel || (exports2.IsolationLevel = IsolationLevel = {}));
  72243. var RetryCondition;
  72244. (function(RetryCondition2) {
  72245. RetryCondition2[RetryCondition2["TransactionConflict"] = 0] = "TransactionConflict";
  72246. RetryCondition2[RetryCondition2["NetworkError"] = 1] = "NetworkError";
  72247. })(RetryCondition || (exports2.RetryCondition = RetryCondition = {}));
  72248. var RetryRule = class {
  72249. attempts;
  72250. backoff;
  72251. constructor(attempts, backoff) {
  72252. this.attempts = attempts;
  72253. this.backoff = backoff;
  72254. }
  72255. };
  72256. var throwWarnings = (warnings) => {
  72257. throw new AggregateError(warnings, formatWarnings(warnings));
  72258. };
  72259. exports2.throwWarnings = throwWarnings;
  72260. var logWarnings = (warnings) => {
  72261. const merged = new Error(formatWarnings(warnings));
  72262. console.warn(Object.assign(merged, { name: "" }));
  72263. };
  72264. exports2.logWarnings = logWarnings;
  72265. var formatWarnings = (warnings) => `warnings occurred while running query:
  72266. ${warnings.map((warn) => warn.message).join("\n")}`;
  72267. var RetryOptions = class _RetryOptions {
  72268. default;
  72269. overrides;
  72270. constructor(attempts = 3, backoff = defaultBackoff) {
  72271. this.default = new RetryRule(attempts, backoff);
  72272. this.overrides = /* @__PURE__ */ new Map();
  72273. }
  72274. withRule(condition, attempts, backoff) {
  72275. const def = this.default;
  72276. const overrides = new Map(this.overrides);
  72277. overrides.set(condition, new RetryRule(attempts ?? def.attempts, backoff ?? def.backoff));
  72278. const result = Object.create(_RetryOptions.prototype);
  72279. result.default = def;
  72280. result.overrides = overrides;
  72281. return result;
  72282. }
  72283. getRuleForException(err2) {
  72284. let result;
  72285. if (err2 instanceof errors.TransactionConflictError) {
  72286. result = this.overrides.get(RetryCondition.TransactionConflict);
  72287. } else if (err2 instanceof errors.ClientError) {
  72288. result = this.overrides.get(RetryCondition.NetworkError);
  72289. }
  72290. return result ?? this.default;
  72291. }
  72292. static defaults() {
  72293. return _retryOptionsDefault;
  72294. }
  72295. };
  72296. exports2.RetryOptions = RetryOptions;
  72297. var _retryOptionsDefault = new RetryOptions();
  72298. var TransactionOptions = class {
  72299. isolation;
  72300. readonly;
  72301. deferrable;
  72302. constructor({ isolation, readonly, deferrable } = {}) {
  72303. this.isolation = isolation;
  72304. this.readonly = readonly;
  72305. this.deferrable = deferrable;
  72306. }
  72307. isDefault() {
  72308. return this.isolation === void 0 && this.readonly === void 0 && this.deferrable === void 0;
  72309. }
  72310. static defaults() {
  72311. return _defaultTransactionOptions;
  72312. }
  72313. };
  72314. exports2.TransactionOptions = TransactionOptions;
  72315. var _defaultTransactionOptions = new TransactionOptions();
  72316. var TAG_ANNOTATION_KEY = "tag";
  72317. var Options = class _Options {
  72318. static schemaVersion = 0;
  72319. module;
  72320. moduleAliases;
  72321. config;
  72322. globals;
  72323. retryOptions;
  72324. transactionOptions;
  72325. codecs;
  72326. warningHandler;
  72327. annotations = /* @__PURE__ */ new Map();
  72328. cachedCodecContext = null;
  72329. cachedCodecContextVer = -1;
  72330. get tag() {
  72331. return this.annotations.get(TAG_ANNOTATION_KEY) ?? null;
  72332. }
  72333. static signalSchemaChange() {
  72334. this.schemaVersion += 1;
  72335. }
  72336. constructor({ retryOptions = RetryOptions.defaults(), transactionOptions = TransactionOptions.defaults(), warningHandler = exports2.logWarnings, module: module3 = "default", moduleAliases = {}, config = {}, globals = {}, codecs = {} } = {}) {
  72337. this.retryOptions = retryOptions;
  72338. this.transactionOptions = transactionOptions;
  72339. this.warningHandler = warningHandler;
  72340. this.module = module3;
  72341. this.moduleAliases = new Map(Object.entries(moduleAliases));
  72342. this.config = new Map(Object.entries(config));
  72343. this.globals = new Map(Object.entries(globals));
  72344. this.codecs = new Map(Object.entries(codecs));
  72345. }
  72346. makeCodecContext() {
  72347. if (this.codecs.size === 0) {
  72348. return context_1.NOOP_CODEC_CONTEXT;
  72349. }
  72350. if (this.cachedCodecContextVer === _Options.schemaVersion) {
  72351. return this.cachedCodecContext;
  72352. }
  72353. const ctx = new context_1.CodecContext(this.codecs);
  72354. this.cachedCodecContext = ctx;
  72355. this.cachedCodecContextVer = _Options.schemaVersion;
  72356. return ctx;
  72357. }
  72358. _cloneWith(mergeOptions) {
  72359. const clone2 = Object.create(_Options.prototype);
  72360. clone2.annotations = this.annotations;
  72361. clone2.retryOptions = mergeOptions.retryOptions ?? this.retryOptions;
  72362. clone2.transactionOptions = mergeOptions.transactionOptions ?? this.transactionOptions;
  72363. clone2.warningHandler = mergeOptions.warningHandler ?? this.warningHandler;
  72364. if (mergeOptions.config != null) {
  72365. clone2.config = new Map([
  72366. ...this.config,
  72367. ...Object.entries(mergeOptions.config)
  72368. ]);
  72369. } else {
  72370. clone2.config = this.config;
  72371. }
  72372. if (mergeOptions.globals != null) {
  72373. clone2.globals = new Map([
  72374. ...this.globals,
  72375. ...Object.entries(mergeOptions.globals)
  72376. ]);
  72377. } else {
  72378. clone2.globals = this.globals;
  72379. }
  72380. if (mergeOptions.moduleAliases != null) {
  72381. clone2.moduleAliases = new Map([
  72382. ...this.moduleAliases,
  72383. ...Object.entries(mergeOptions.moduleAliases)
  72384. ]);
  72385. } else {
  72386. clone2.moduleAliases = this.moduleAliases;
  72387. }
  72388. if (mergeOptions.codecs != null) {
  72389. clone2.codecs = new Map([
  72390. ...this.codecs,
  72391. ...Object.entries(mergeOptions.codecs)
  72392. ]);
  72393. } else {
  72394. clone2.codecs = this.codecs;
  72395. clone2.cachedCodecContext = this.cachedCodecContext;
  72396. clone2.cachedCodecContextVer = this.cachedCodecContextVer;
  72397. }
  72398. if (mergeOptions._dropSQLRowCodec && clone2.codecs.has("_private_sql_row")) {
  72399. if (clone2.codecs === this.codecs) {
  72400. clone2.codecs = new Map(clone2.codecs);
  72401. clone2.cachedCodecContext = null;
  72402. clone2.cachedCodecContextVer = -1;
  72403. }
  72404. clone2.codecs.delete("_private_sql_row");
  72405. }
  72406. clone2.module = mergeOptions.module ?? this.module;
  72407. return clone2;
  72408. }
  72409. _serialise() {
  72410. const state2 = {};
  72411. if (this.module !== "default") {
  72412. state2.module = this.module;
  72413. }
  72414. if (this.moduleAliases.size) {
  72415. state2.aliases = Array.from(this.moduleAliases.entries());
  72416. }
  72417. if (this.config.size) {
  72418. state2.config = Object.fromEntries(this.config.entries());
  72419. }
  72420. if (this.globals.size) {
  72421. const globs = {};
  72422. for (const [key, val2] of this.globals.entries()) {
  72423. globs[key.includes("::") ? key : `${this.module}::${key}`] = val2;
  72424. }
  72425. state2.globals = globs;
  72426. }
  72427. return state2;
  72428. }
  72429. withModuleAliases({ module: module3, ...aliases }) {
  72430. return this._cloneWith({
  72431. module: module3 ?? this.module,
  72432. moduleAliases: aliases
  72433. });
  72434. }
  72435. withConfig(config) {
  72436. return this._cloneWith({ config });
  72437. }
  72438. withCodecs(codecs) {
  72439. return this._cloneWith({ codecs });
  72440. }
  72441. withSQLRowMode(mode) {
  72442. if (mode === "object") {
  72443. return this._cloneWith({ _dropSQLRowCodec: true });
  72444. } else if (mode === "array") {
  72445. return this._cloneWith({ codecs: record_1.SQLRowModeArray });
  72446. } else {
  72447. throw new errors.InterfaceError(`invalid mode=${mode}`);
  72448. }
  72449. }
  72450. withGlobals(globals) {
  72451. return this._cloneWith({
  72452. globals: { ...this.globals, ...globals }
  72453. });
  72454. }
  72455. withQueryTag(tag) {
  72456. const annos = new Map(this.annotations);
  72457. if (tag != null) {
  72458. if (tag.startsWith("edgedb/")) {
  72459. throw new errors.InterfaceError("reserved tag: edgedb/*");
  72460. }
  72461. if (tag.startsWith("gel/")) {
  72462. throw new errors.InterfaceError("reserved tag: gel/*");
  72463. }
  72464. if (buffer_1.utf8Encoder.encode(tag).length > 128) {
  72465. throw new errors.InterfaceError("tag too long (> 128 bytes)");
  72466. }
  72467. annos.set(TAG_ANNOTATION_KEY, tag);
  72468. } else {
  72469. annos.delete(TAG_ANNOTATION_KEY);
  72470. }
  72471. const clone2 = this._cloneWith({});
  72472. clone2.annotations = annos;
  72473. return clone2;
  72474. }
  72475. withTransactionOptions(opt) {
  72476. return this._cloneWith({
  72477. transactionOptions: opt instanceof TransactionOptions ? opt : new TransactionOptions(opt)
  72478. });
  72479. }
  72480. withRetryOptions(opt) {
  72481. return this._cloneWith({
  72482. retryOptions: opt instanceof RetryOptions ? opt : new RetryOptions(opt.attempts, opt.backoff)
  72483. });
  72484. }
  72485. withWarningHandler(handler) {
  72486. return this._cloneWith({ warningHandler: handler });
  72487. }
  72488. isDefaultSession() {
  72489. return this.config.size === 0 && this.globals.size === 0 && this.moduleAliases.size === 0 && this.module === "default" && this.transactionOptions.isDefault();
  72490. }
  72491. static defaults() {
  72492. return _defaultOptions;
  72493. }
  72494. };
  72495. exports2.Options = Options;
  72496. var _defaultOptions = new Options();
  72497. }
  72498. });
  72499. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/event.js
  72500. var require_event = __commonJS({
  72501. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/event.js"(exports2) {
  72502. "use strict";
  72503. Object.defineProperty(exports2, "__esModule", { value: true });
  72504. var errors_1 = require_errors();
  72505. var Event = class {
  72506. _promise;
  72507. _resolve;
  72508. _reject;
  72509. _done;
  72510. async wait() {
  72511. await this._promise;
  72512. }
  72513. then(..._args) {
  72514. throw new errors_1.InternalClientError("Event objects cannot be awaited on directly; use Event.wait()");
  72515. }
  72516. get done() {
  72517. return this._done;
  72518. }
  72519. set() {
  72520. if (this._done) {
  72521. throw new errors_1.InternalClientError("emit(): the Event is already set");
  72522. }
  72523. this._resolve(true);
  72524. }
  72525. setError(reason) {
  72526. if (this._done) {
  72527. throw new errors_1.InternalClientError("emitError(): the Event is already set");
  72528. }
  72529. this._reject(reason);
  72530. }
  72531. constructor() {
  72532. this._done = false;
  72533. let futReject = null;
  72534. let futResolve = null;
  72535. this._promise = new Promise((resolve2, reject) => {
  72536. futReject = (reason) => {
  72537. this._done = true;
  72538. reject(reason);
  72539. };
  72540. futResolve = (value) => {
  72541. this._done = true;
  72542. resolve2(value);
  72543. };
  72544. });
  72545. if (!futReject || !futResolve) {
  72546. throw new errors_1.InternalClientError("Promise executor was not called synchronously");
  72547. }
  72548. this._reject = futReject;
  72549. this._resolve = futResolve;
  72550. }
  72551. };
  72552. exports2.default = Event;
  72553. }
  72554. });
  72555. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/queues.js
  72556. var require_queues = __commonJS({
  72557. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/queues.js"(exports2) {
  72558. "use strict";
  72559. Object.defineProperty(exports2, "__esModule", { value: true });
  72560. exports2.LifoQueue = void 0;
  72561. var errors_1 = require_errors();
  72562. var LifoQueue = class {
  72563. _promises;
  72564. _resolvers;
  72565. _rejecters;
  72566. constructor() {
  72567. this._resolvers = [];
  72568. this._rejecters = [];
  72569. this._promises = [];
  72570. }
  72571. _add() {
  72572. this._promises.push(new Promise((resolve2, reject) => {
  72573. this._resolvers.push(resolve2);
  72574. this._rejecters.push(reject);
  72575. }));
  72576. }
  72577. push(item) {
  72578. if (!this._resolvers.length) {
  72579. this._add();
  72580. }
  72581. const resolve2 = this._resolvers.shift();
  72582. this._rejecters.shift();
  72583. if (!resolve2) {
  72584. throw new errors_1.InternalClientError("resolve function was null or undefined when attempting to push.");
  72585. }
  72586. resolve2(item);
  72587. }
  72588. get() {
  72589. if (!this._promises.length) {
  72590. this._add();
  72591. }
  72592. const promise = this._promises.pop();
  72593. if (!promise) {
  72594. throw new errors_1.InternalClientError("promise was null or undefined when attempting to get.");
  72595. }
  72596. return promise;
  72597. }
  72598. cancelAllPending(err2) {
  72599. const rejecters = this._rejecters;
  72600. this._rejecters = [];
  72601. this._resolvers = [];
  72602. for (const reject of rejecters) {
  72603. reject(err2);
  72604. }
  72605. }
  72606. get length() {
  72607. return this._promises.length - this._resolvers.length;
  72608. }
  72609. get pending() {
  72610. return Math.max(0, this._resolvers.length - this._promises.length);
  72611. }
  72612. };
  72613. exports2.LifoQueue = LifoQueue;
  72614. }
  72615. });
  72616. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/retry.js
  72617. var require_retry = __commonJS({
  72618. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/retry.js"(exports2) {
  72619. "use strict";
  72620. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  72621. if (k22 === void 0) k22 = k3;
  72622. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  72623. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  72624. desc = { enumerable: true, get: function() {
  72625. return m4[k3];
  72626. } };
  72627. }
  72628. Object.defineProperty(o3, k22, desc);
  72629. } : function(o3, m4, k3, k22) {
  72630. if (k22 === void 0) k22 = k3;
  72631. o3[k22] = m4[k3];
  72632. });
  72633. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  72634. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  72635. } : function(o3, v6) {
  72636. o3["default"] = v6;
  72637. });
  72638. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  72639. if (mod && mod.__esModule) return mod;
  72640. var result = {};
  72641. if (mod != null) {
  72642. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  72643. }
  72644. __setModuleDefault2(result, mod);
  72645. return result;
  72646. };
  72647. Object.defineProperty(exports2, "__esModule", { value: true });
  72648. exports2.retryingConnect = retryingConnect;
  72649. var errors = __importStar2(require_errors());
  72650. var utils_1 = require_utils2();
  72651. var lastLoggingAt = 0;
  72652. async function retryingConnect(connectWithTimeout, config, registry) {
  72653. const maxTime = config.connectionParams.waitUntilAvailable === 0 ? 0 : Date.now() + config.connectionParams.waitUntilAvailable;
  72654. while (true) {
  72655. try {
  72656. return await connectWithTimeout(config, registry);
  72657. } catch (e4) {
  72658. if (e4 instanceof errors.ClientConnectionError) {
  72659. if (e4.hasTag(errors.SHOULD_RECONNECT)) {
  72660. const now = Date.now();
  72661. if (now > maxTime) {
  72662. throw e4;
  72663. }
  72664. if (config.logging && (!lastLoggingAt || now - lastLoggingAt > 5e3)) {
  72665. lastLoggingAt = now;
  72666. const logMsg = [
  72667. `A client connection error occurred; reconnecting because of "waitUntilAvailable=${config.connectionParams.waitUntilAvailable}".`,
  72668. e4
  72669. ];
  72670. if (!config.fromProject && !config.fromEnv && await config.inProject()) {
  72671. logMsg.push(`
  72672. Hint: it looks like the program is running from a directory initialized with "gel project init". Consider calling "gel.connect()" without arguments.
  72673. `);
  72674. }
  72675. console.warn(...logMsg);
  72676. }
  72677. } else {
  72678. throw e4;
  72679. }
  72680. } else {
  72681. console.error("Unexpected connection error:", e4);
  72682. throw e4;
  72683. }
  72684. }
  72685. await (0, utils_1.sleep)(Math.trunc(10 + Math.random() * 200));
  72686. }
  72687. }
  72688. }
  72689. });
  72690. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/enums.js
  72691. var require_enums = __commonJS({
  72692. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/enums.js"(exports2) {
  72693. "use strict";
  72694. Object.defineProperty(exports2, "__esModule", { value: true });
  72695. exports2.OperatorKind = exports2.SelectModifierKind = exports2.ExpressionKind = exports2.TypeKind = exports2.Cardinality = void 0;
  72696. var Cardinality;
  72697. (function(Cardinality2) {
  72698. Cardinality2["AtMostOne"] = "AtMostOne";
  72699. Cardinality2["One"] = "One";
  72700. Cardinality2["Many"] = "Many";
  72701. Cardinality2["AtLeastOne"] = "AtLeastOne";
  72702. Cardinality2["Empty"] = "Empty";
  72703. })(Cardinality || (exports2.Cardinality = Cardinality = {}));
  72704. var TypeKind;
  72705. (function(TypeKind2) {
  72706. TypeKind2["scalar"] = "scalar";
  72707. TypeKind2["enum"] = "enum";
  72708. TypeKind2["object"] = "object";
  72709. TypeKind2["namedtuple"] = "namedtuple";
  72710. TypeKind2["tuple"] = "tuple";
  72711. TypeKind2["array"] = "array";
  72712. TypeKind2["range"] = "range";
  72713. TypeKind2["multirange"] = "multirange";
  72714. })(TypeKind || (exports2.TypeKind = TypeKind = {}));
  72715. var ExpressionKind;
  72716. (function(ExpressionKind2) {
  72717. ExpressionKind2["Set"] = "Set";
  72718. ExpressionKind2["Array"] = "Array";
  72719. ExpressionKind2["Tuple"] = "Tuple";
  72720. ExpressionKind2["NamedTuple"] = "NamedTuple";
  72721. ExpressionKind2["TuplePath"] = "TuplePath";
  72722. ExpressionKind2["PathNode"] = "PathNode";
  72723. ExpressionKind2["PathLeaf"] = "PathLeaf";
  72724. ExpressionKind2["Literal"] = "Literal";
  72725. ExpressionKind2["Cast"] = "Cast";
  72726. ExpressionKind2["Select"] = "Select";
  72727. ExpressionKind2["Update"] = "Update";
  72728. ExpressionKind2["Delete"] = "Delete";
  72729. ExpressionKind2["Insert"] = "Insert";
  72730. ExpressionKind2["InsertUnlessConflict"] = "InsertUnlessConflict";
  72731. ExpressionKind2["Function"] = "Function";
  72732. ExpressionKind2["Operator"] = "Operator";
  72733. ExpressionKind2["For"] = "For";
  72734. ExpressionKind2["ForVar"] = "ForVar";
  72735. ExpressionKind2["TypeIntersection"] = "TypeIntersection";
  72736. ExpressionKind2["Alias"] = "Alias";
  72737. ExpressionKind2["With"] = "With";
  72738. ExpressionKind2["WithParams"] = "WithParams";
  72739. ExpressionKind2["Param"] = "Param";
  72740. ExpressionKind2["OptionalParam"] = "OptionalParam";
  72741. ExpressionKind2["Detached"] = "Detached";
  72742. ExpressionKind2["Global"] = "Global";
  72743. ExpressionKind2["PolyShapeElement"] = "PolyShapeElement";
  72744. ExpressionKind2["Group"] = "Group";
  72745. })(ExpressionKind || (exports2.ExpressionKind = ExpressionKind = {}));
  72746. var SelectModifierKind;
  72747. (function(SelectModifierKind2) {
  72748. SelectModifierKind2["filter"] = "filter";
  72749. SelectModifierKind2["order_by"] = "order_by";
  72750. SelectModifierKind2["offset"] = "offset";
  72751. SelectModifierKind2["limit"] = "limit";
  72752. })(SelectModifierKind || (exports2.SelectModifierKind = SelectModifierKind = {}));
  72753. var OperatorKind;
  72754. (function(OperatorKind2) {
  72755. OperatorKind2["Infix"] = "Infix";
  72756. OperatorKind2["Postfix"] = "Postfix";
  72757. OperatorKind2["Prefix"] = "Prefix";
  72758. OperatorKind2["Ternary"] = "Ternary";
  72759. })(OperatorKind || (exports2.OperatorKind = OperatorKind = {}));
  72760. }
  72761. });
  72762. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/util.js
  72763. var require_util3 = __commonJS({
  72764. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/util.js"(exports2) {
  72765. "use strict";
  72766. Object.defineProperty(exports2, "__esModule", { value: true });
  72767. exports2.util = void 0;
  72768. var ifaces_1 = require_ifaces2();
  72769. var enums_1 = require_enums();
  72770. var util2;
  72771. (function(util3) {
  72772. function assertNever(arg, error2) {
  72773. throw error2 ?? new Error(`${arg} is supposed to be of "never" type`);
  72774. }
  72775. util3.assertNever = assertNever;
  72776. function splitName(name) {
  72777. if (!name.includes("::"))
  72778. throw new Error(`Invalid FQN ${name}`);
  72779. const parts = name.split("::");
  72780. return {
  72781. mod: parts.slice(0, -1).join("::"),
  72782. name: parts[parts.length - 1]
  72783. };
  72784. }
  72785. util3.splitName = splitName;
  72786. function toIdent(name) {
  72787. if (name.includes("::")) {
  72788. throw new Error(`toIdent: invalid name ${name}`);
  72789. }
  72790. return name.replace(/([^a-zA-Z0-9_]+)/g, "_");
  72791. }
  72792. util3.toIdent = toIdent;
  72793. util3.deduplicate = (args) => [...new Set(args)];
  72794. util3.getFromArrayMap = (map2, id) => {
  72795. return map2[id] || [];
  72796. };
  72797. util3.defineProperty = (obj, name, def) => {
  72798. return Object.defineProperty(obj, name, def);
  72799. };
  72800. util3.defineGetter = (obj, name, getter) => {
  72801. return Object.defineProperty(obj, name, {
  72802. get: getter,
  72803. enumerable: true
  72804. });
  72805. };
  72806. util3.defineMethod = (obj, name, method) => {
  72807. obj[name] = method.bind(obj);
  72808. return obj;
  72809. };
  72810. function flatMap(array2, callbackfn) {
  72811. return Array.prototype.concat(...array2.map(callbackfn));
  72812. }
  72813. util3.flatMap = flatMap;
  72814. function omitDollarPrefixed(object) {
  72815. const obj = {};
  72816. for (const key of Object.keys(object)) {
  72817. if (!key.startsWith("$")) {
  72818. obj[key] = object[key];
  72819. }
  72820. }
  72821. return obj;
  72822. }
  72823. util3.omitDollarPrefixed = omitDollarPrefixed;
  72824. util3.parseCardinality = (cardinality) => {
  72825. switch (cardinality) {
  72826. case ifaces_1.Cardinality.MANY:
  72827. return enums_1.Cardinality.Many;
  72828. case ifaces_1.Cardinality.ONE:
  72829. return enums_1.Cardinality.One;
  72830. case ifaces_1.Cardinality.AT_MOST_ONE:
  72831. return enums_1.Cardinality.AtMostOne;
  72832. case ifaces_1.Cardinality.AT_LEAST_ONE:
  72833. return enums_1.Cardinality.AtLeastOne;
  72834. case ifaces_1.Cardinality.NO_RESULT:
  72835. return enums_1.Cardinality.Empty;
  72836. }
  72837. throw new Error(`Unexpected cardinality: ${cardinality}`);
  72838. };
  72839. })(util2 || (exports2.util = util2 = {}));
  72840. }
  72841. });
  72842. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/transaction.js
  72843. var require_transaction = __commonJS({
  72844. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/transaction.js"(exports2) {
  72845. "use strict";
  72846. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  72847. if (k22 === void 0) k22 = k3;
  72848. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  72849. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  72850. desc = { enumerable: true, get: function() {
  72851. return m4[k3];
  72852. } };
  72853. }
  72854. Object.defineProperty(o3, k22, desc);
  72855. } : function(o3, m4, k3, k22) {
  72856. if (k22 === void 0) k22 = k3;
  72857. o3[k22] = m4[k3];
  72858. });
  72859. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  72860. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  72861. } : function(o3, v6) {
  72862. o3["default"] = v6;
  72863. });
  72864. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  72865. if (mod && mod.__esModule) return mod;
  72866. var result = {};
  72867. if (mod != null) {
  72868. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  72869. }
  72870. __setModuleDefault2(result, mod);
  72871. return result;
  72872. };
  72873. Object.defineProperty(exports2, "__esModule", { value: true });
  72874. exports2.Transaction = exports2.TransactionImpl = exports2.TransactionState = void 0;
  72875. var errors = __importStar2(require_errors());
  72876. var ifaces_1 = require_ifaces2();
  72877. var options_1 = require_options();
  72878. var TransactionState;
  72879. (function(TransactionState2) {
  72880. TransactionState2[TransactionState2["ACTIVE"] = 0] = "ACTIVE";
  72881. TransactionState2[TransactionState2["COMMITTED"] = 1] = "COMMITTED";
  72882. TransactionState2[TransactionState2["ROLLEDBACK"] = 2] = "ROLLEDBACK";
  72883. TransactionState2[TransactionState2["FAILED"] = 3] = "FAILED";
  72884. })(TransactionState || (exports2.TransactionState = TransactionState = {}));
  72885. var TransactionImpl = class _TransactionImpl {
  72886. _holder;
  72887. _rawConn;
  72888. _state;
  72889. _opInProgress;
  72890. constructor(holder, rawConn) {
  72891. this._holder = holder;
  72892. this._rawConn = rawConn;
  72893. this._state = TransactionState.ACTIVE;
  72894. this._opInProgress = false;
  72895. }
  72896. static async _startTransaction(holder, optimisticRepeatableRead) {
  72897. const rawConn = await holder._getConnection();
  72898. await rawConn.resetState();
  72899. const options = holder.options.transactionOptions;
  72900. const txOptions = [];
  72901. if (options.isolation === options_1.IsolationLevel.RepeatableRead) {
  72902. txOptions.push(`ISOLATION REPEATABLE READ`);
  72903. } else if (options.isolation === options_1.IsolationLevel.Serializable) {
  72904. txOptions.push(`ISOLATION SERIALIZABLE`);
  72905. } else if (options.isolation === options_1.IsolationLevel.PreferRepeatableRead) {
  72906. if (optimisticRepeatableRead) {
  72907. txOptions.push(`ISOLATION REPEATABLE READ`);
  72908. } else {
  72909. txOptions.push(`ISOLATION SERIALIZABLE`);
  72910. }
  72911. } else if (options.isolation != null) {
  72912. throw new errors.InterfaceError(`Invalid isolation level: ${options.isolation}`);
  72913. }
  72914. if (options.readonly !== void 0) {
  72915. txOptions.push(options.readonly ? "READ ONLY" : "READ WRITE");
  72916. }
  72917. if (options.deferrable !== void 0) {
  72918. txOptions.push(options.deferrable ? "DEFERRABLE" : "NOT DEFERRABLE");
  72919. }
  72920. await rawConn.fetch(`START TRANSACTION ${txOptions.join(", ")};`, void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, holder.options, true);
  72921. return new _TransactionImpl(holder, rawConn);
  72922. }
  72923. async _waitForConnAbort() {
  72924. await this._rawConn.connAbortWaiter.wait();
  72925. const abortError = this._rawConn.getConnAbortError();
  72926. if (abortError instanceof errors.GelError && abortError.cause instanceof errors.TransactionTimeoutError) {
  72927. throw abortError.cause;
  72928. } else {
  72929. throw abortError;
  72930. }
  72931. }
  72932. async _runOp(opname, op, errMessage) {
  72933. if (this._opInProgress) {
  72934. throw new errors.InterfaceError(errMessage ?? "Another query is in progress. Use the query methods on 'Client' to run queries concurrently.");
  72935. }
  72936. if (this._state !== TransactionState.ACTIVE) {
  72937. throw new errors.InterfaceError(`cannot ${opname}; the transaction is ${this._state === TransactionState.COMMITTED ? "already committed" : this._state === TransactionState.ROLLEDBACK ? "already rolled back" : "in error state"}`);
  72938. }
  72939. this._opInProgress = true;
  72940. try {
  72941. return await op();
  72942. } finally {
  72943. this._opInProgress = false;
  72944. }
  72945. }
  72946. async _runFetchOp(opName, ...args) {
  72947. const { result, warnings } = await this._runOp(opName, () => this._rawConn.fetch(...args));
  72948. if (warnings.length) {
  72949. this._holder.options.warningHandler(warnings);
  72950. }
  72951. return result;
  72952. }
  72953. async _commit() {
  72954. await this._runOp("commit", async () => {
  72955. await this._rawConn.fetch("COMMIT", void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this._holder.options, true);
  72956. this._state = TransactionState.COMMITTED;
  72957. }, "A query is still in progress after transaction block has returned.");
  72958. }
  72959. async _rollback() {
  72960. await this._runOp("rollback", async () => {
  72961. await this._rawConn.fetch("ROLLBACK", void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this._holder.options, true);
  72962. this._state = TransactionState.ROLLEDBACK;
  72963. }, "A query is still in progress after transaction block has returned.");
  72964. }
  72965. };
  72966. exports2.TransactionImpl = TransactionImpl;
  72967. var Transaction = class _Transaction {
  72968. impl;
  72969. options;
  72970. constructor(impl, options) {
  72971. this.impl = impl;
  72972. this.options = options;
  72973. }
  72974. withSQLRowMode(mode) {
  72975. return new _Transaction(this.impl, this.options.withSQLRowMode(mode));
  72976. }
  72977. async execute(query, args) {
  72978. await this.impl._runFetchOp("execute", query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this.options);
  72979. }
  72980. async executeSQL(query, args) {
  72981. await this.impl._runFetchOp("execute", query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, this.options, false, ifaces_1.Language.SQL);
  72982. }
  72983. async query(query, args) {
  72984. return this.impl._runFetchOp("query", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options);
  72985. }
  72986. async querySQL(query, args) {
  72987. return this.impl._runFetchOp("query", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options, false, ifaces_1.Language.SQL);
  72988. }
  72989. async queryJSON(query, args) {
  72990. return this.impl._runFetchOp("queryJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.MANY, this.options);
  72991. }
  72992. async querySingle(query, args) {
  72993. return this.impl._runFetchOp("querySingle", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_MOST_ONE, this.options);
  72994. }
  72995. async querySingleJSON(query, args) {
  72996. return this.impl._runFetchOp("querySingleJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_MOST_ONE, this.options);
  72997. }
  72998. async queryRequired(query, args) {
  72999. return this.impl._runFetchOp("queryRequired", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_LEAST_ONE, this.options);
  73000. }
  73001. async queryRequiredJSON(query, args) {
  73002. return this.impl._runFetchOp("queryRequiredJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_LEAST_ONE, this.options);
  73003. }
  73004. async queryRequiredSingle(query, args) {
  73005. return this.impl._runFetchOp("queryRequiredSingle", query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.ONE, this.options);
  73006. }
  73007. async queryRequiredSingleJSON(query, args) {
  73008. return this.impl._runFetchOp("queryRequiredSingleJSON", query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.ONE, this.options);
  73009. }
  73010. };
  73011. exports2.Transaction = Transaction;
  73012. }
  73013. });
  73014. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseClient.js
  73015. var require_baseClient = __commonJS({
  73016. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseClient.js"(exports2) {
  73017. "use strict";
  73018. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  73019. if (k22 === void 0) k22 = k3;
  73020. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  73021. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  73022. desc = { enumerable: true, get: function() {
  73023. return m4[k3];
  73024. } };
  73025. }
  73026. Object.defineProperty(o3, k22, desc);
  73027. } : function(o3, m4, k3, k22) {
  73028. if (k22 === void 0) k22 = k3;
  73029. o3[k22] = m4[k3];
  73030. });
  73031. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  73032. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  73033. } : function(o3, v6) {
  73034. o3["default"] = v6;
  73035. });
  73036. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  73037. if (mod && mod.__esModule) return mod;
  73038. var result = {};
  73039. if (mod != null) {
  73040. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  73041. }
  73042. __setModuleDefault2(result, mod);
  73043. return result;
  73044. };
  73045. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  73046. return mod && mod.__esModule ? mod : { "default": mod };
  73047. };
  73048. Object.defineProperty(exports2, "__esModule", { value: true });
  73049. exports2.Client = exports2.BaseClientPool = exports2.ClientConnectionHolder = void 0;
  73050. var registry_1 = require_registry();
  73051. var errors = __importStar2(require_errors());
  73052. var ifaces_1 = require_ifaces2();
  73053. var options_1 = require_options();
  73054. var event_1 = __importDefault2(require_event());
  73055. var queues_1 = require_queues();
  73056. var retry_1 = require_retry();
  73057. var util_1 = require_util3();
  73058. var transaction_1 = require_transaction();
  73059. var utils_1 = require_utils2();
  73060. var ClientConnectionHolder = class {
  73061. _pool;
  73062. _connection;
  73063. _options;
  73064. _inUse;
  73065. constructor(pool) {
  73066. this._pool = pool;
  73067. this._connection = null;
  73068. this._options = null;
  73069. this._inUse = null;
  73070. }
  73071. get options() {
  73072. return this._options ?? options_1.Options.defaults();
  73073. }
  73074. async _getConnection() {
  73075. if (!this._connection || this._connection.isClosed()) {
  73076. this._connection = await this._pool.getNewConnection();
  73077. }
  73078. return this._connection;
  73079. }
  73080. get connectionOpen() {
  73081. return this._connection !== null && !this._connection.isClosed();
  73082. }
  73083. async acquire(options) {
  73084. if (this._inUse) {
  73085. throw new errors.InternalClientError("ClientConnectionHolder cannot be acquired, already in use");
  73086. }
  73087. this._options = options;
  73088. this._inUse = new event_1.default();
  73089. return this;
  73090. }
  73091. async release() {
  73092. var _a2;
  73093. if (this._inUse === null) {
  73094. throw new errors.ClientError("ClientConnectionHolder.release() called on a free connection holder");
  73095. }
  73096. this._options = null;
  73097. await ((_a2 = this._connection) == null ? void 0 : _a2.resetState());
  73098. if (!this._inUse.done) {
  73099. this._inUse.set();
  73100. }
  73101. this._inUse = null;
  73102. this._pool.enqueue(this);
  73103. }
  73104. async _waitUntilReleasedAndClose() {
  73105. var _a2;
  73106. if (this._inUse) {
  73107. await this._inUse.wait();
  73108. }
  73109. await ((_a2 = this._connection) == null ? void 0 : _a2.close());
  73110. }
  73111. terminate() {
  73112. var _a2;
  73113. (_a2 = this._connection) == null ? void 0 : _a2.close();
  73114. }
  73115. async transaction(action) {
  73116. let result;
  73117. let optimisticRepeatableRead = true;
  73118. for (let iteration = 0; ; ++iteration) {
  73119. const transaction = await transaction_1.TransactionImpl._startTransaction(this, optimisticRepeatableRead);
  73120. const clientTx = new transaction_1.Transaction(transaction, this.options);
  73121. let commitFailed = false;
  73122. try {
  73123. result = await Promise.race([
  73124. action(clientTx),
  73125. transaction._waitForConnAbort()
  73126. ]);
  73127. try {
  73128. await transaction._commit();
  73129. } catch (err2) {
  73130. commitFailed = true;
  73131. throw err2;
  73132. }
  73133. } catch (err2) {
  73134. try {
  73135. if (!commitFailed) {
  73136. await transaction._rollback();
  73137. }
  73138. } catch (rollback_err) {
  73139. if (!(rollback_err instanceof errors.GelError)) {
  73140. throw rollback_err;
  73141. }
  73142. }
  73143. if (err2 instanceof errors.CapabilityError && err2.message && err2.message.includes("REPEATABLE READ") && optimisticRepeatableRead) {
  73144. optimisticRepeatableRead = false;
  73145. iteration--;
  73146. continue;
  73147. }
  73148. if (err2 instanceof errors.GelError && err2.hasTag(errors.SHOULD_RETRY) && !(commitFailed && err2 instanceof errors.ClientConnectionError)) {
  73149. const rule = this.options.retryOptions.getRuleForException(err2);
  73150. if (iteration + 1 >= rule.attempts) {
  73151. throw err2;
  73152. }
  73153. await (0, utils_1.sleep)(rule.backoff(iteration + 1));
  73154. continue;
  73155. }
  73156. throw err2;
  73157. }
  73158. return result;
  73159. }
  73160. }
  73161. async retryingFetch(query, args, outputFormat, expectedCardinality, language = ifaces_1.Language.EDGEQL) {
  73162. for (let iteration = 0; ; ++iteration) {
  73163. const conn = await this._getConnection();
  73164. try {
  73165. const { result, warnings } = await conn.fetch(query, args, outputFormat, expectedCardinality, this.options, false, language);
  73166. if (warnings.length) {
  73167. this.options.warningHandler(warnings);
  73168. }
  73169. return result;
  73170. } catch (err2) {
  73171. if (err2 instanceof errors.GelError && err2.hasTag(errors.SHOULD_RETRY) && (conn.getQueryCapabilities(query, outputFormat, expectedCardinality) === 0 || err2 instanceof errors.TransactionConflictError)) {
  73172. const rule = this.options.retryOptions.getRuleForException(err2);
  73173. if (iteration + 1 >= rule.attempts) {
  73174. throw err2;
  73175. }
  73176. await (0, utils_1.sleep)(rule.backoff(iteration + 1));
  73177. continue;
  73178. }
  73179. throw err2;
  73180. }
  73181. }
  73182. }
  73183. async execute(query, args) {
  73184. await this.retryingFetch(query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT);
  73185. }
  73186. async executeSQL(query, args) {
  73187. await this.retryingFetch(query, args, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, ifaces_1.Language.SQL);
  73188. }
  73189. async query(query, args) {
  73190. return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY);
  73191. }
  73192. async querySQL(query, args) {
  73193. return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, ifaces_1.Language.SQL);
  73194. }
  73195. async queryJSON(query, args) {
  73196. return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.MANY);
  73197. }
  73198. async querySingle(query, args) {
  73199. return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_MOST_ONE);
  73200. }
  73201. async querySingleJSON(query, args) {
  73202. return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_MOST_ONE);
  73203. }
  73204. async queryRequired(query, args) {
  73205. return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.AT_LEAST_ONE);
  73206. }
  73207. async queryRequiredJSON(query, args) {
  73208. return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.AT_LEAST_ONE);
  73209. }
  73210. async queryRequiredSingle(query, args) {
  73211. return this.retryingFetch(query, args, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.ONE);
  73212. }
  73213. async queryRequiredSingleJSON(query, args) {
  73214. return this.retryingFetch(query, args, ifaces_1.OutputFormat.JSON, ifaces_1.Cardinality.ONE);
  73215. }
  73216. };
  73217. exports2.ClientConnectionHolder = ClientConnectionHolder;
  73218. var BaseClientPool = class {
  73219. _parseConnectArguments;
  73220. _closing;
  73221. _queue;
  73222. _holders;
  73223. _userConcurrency;
  73224. _suggestedConcurrency;
  73225. _connectConfig;
  73226. _codecsRegistry;
  73227. constructor(_parseConnectArguments, options) {
  73228. this._parseConnectArguments = _parseConnectArguments;
  73229. this.validateClientOptions(options);
  73230. this._codecsRegistry = new registry_1.CodecsRegistry();
  73231. this._queue = new queues_1.LifoQueue();
  73232. this._holders = [];
  73233. this._userConcurrency = options.concurrency ?? null;
  73234. this._suggestedConcurrency = null;
  73235. this._closing = null;
  73236. this._connectConfig = { ...options };
  73237. this._resizeHolderPool();
  73238. }
  73239. validateClientOptions(opts) {
  73240. if (opts.concurrency != null && (typeof opts.concurrency !== "number" || !Number.isInteger(opts.concurrency) || opts.concurrency < 0)) {
  73241. throw new errors.InterfaceError(`invalid 'concurrency' value: expected integer greater than 0 (got ${JSON.stringify(opts.concurrency)})`);
  73242. }
  73243. }
  73244. _getStats() {
  73245. return {
  73246. queueLength: this._queue.pending,
  73247. openConnections: this._holders.filter((holder) => holder.connectionOpen).length
  73248. };
  73249. }
  73250. async ensureConnected() {
  73251. if (this._closing) {
  73252. throw new errors.InterfaceError(this._closing.done ? "The client is closed" : "The client is closing");
  73253. }
  73254. if (this._getStats().openConnections > 0) {
  73255. return;
  73256. }
  73257. const connHolder = await this._queue.get();
  73258. try {
  73259. await connHolder._getConnection();
  73260. } finally {
  73261. this._queue.push(connHolder);
  73262. }
  73263. }
  73264. get _concurrency() {
  73265. return this._userConcurrency ?? this._suggestedConcurrency ?? 1;
  73266. }
  73267. _resizeHolderPool() {
  73268. const holdersDiff = this._concurrency - this._holders.length;
  73269. if (holdersDiff > 0) {
  73270. for (let i4 = 0; i4 < holdersDiff; i4++) {
  73271. const connectionHolder = new ClientConnectionHolder(this);
  73272. this._holders.push(connectionHolder);
  73273. this._queue.push(connectionHolder);
  73274. }
  73275. } else if (holdersDiff < 0) {
  73276. }
  73277. }
  73278. __normalizedConnectConfig = null;
  73279. _getNormalizedConnectConfig() {
  73280. return this.__normalizedConnectConfig ?? (this.__normalizedConnectConfig = this._parseConnectArguments(this._connectConfig));
  73281. }
  73282. async resolveConnectionParams() {
  73283. const config = await this._getNormalizedConnectConfig();
  73284. return config.connectionParams;
  73285. }
  73286. async getNewConnection() {
  73287. var _a2;
  73288. if ((_a2 = this._closing) == null ? void 0 : _a2.done) {
  73289. throw new errors.InterfaceError("The client is closed");
  73290. }
  73291. const config = await this._getNormalizedConnectConfig();
  73292. const connection = await (0, retry_1.retryingConnect)(this._connectWithTimeout, config, this._codecsRegistry);
  73293. const suggestedConcurrency = connection.serverSettings.suggested_pool_concurrency;
  73294. if (suggestedConcurrency && suggestedConcurrency !== this._suggestedConcurrency) {
  73295. this._suggestedConcurrency = suggestedConcurrency;
  73296. this._resizeHolderPool();
  73297. }
  73298. return connection;
  73299. }
  73300. async acquireHolder(options) {
  73301. if (this._closing) {
  73302. throw new errors.InterfaceError(this._closing.done ? "The client is closed" : "The client is closing");
  73303. }
  73304. const connectionHolder = await this._queue.get();
  73305. try {
  73306. return await connectionHolder.acquire(options);
  73307. } catch (error2) {
  73308. this._queue.push(connectionHolder);
  73309. throw error2;
  73310. }
  73311. }
  73312. enqueue(holder) {
  73313. this._queue.push(holder);
  73314. }
  73315. async close() {
  73316. if (this._closing) {
  73317. return await this._closing.wait();
  73318. }
  73319. this._closing = new event_1.default();
  73320. this._queue.cancelAllPending(new errors.InterfaceError(`The client is closing`));
  73321. const warningTimeoutId = setTimeout(() => {
  73322. console.warn("Client.close() is taking over 60 seconds to complete. Check if you have any unreleased connections left.");
  73323. }, 6e4);
  73324. try {
  73325. await Promise.all(this._holders.map((connectionHolder) => connectionHolder._waitUntilReleasedAndClose()));
  73326. } catch (err2) {
  73327. this._terminate();
  73328. this._closing.setError(err2);
  73329. throw err2;
  73330. } finally {
  73331. clearTimeout(warningTimeoutId);
  73332. }
  73333. this._closing.set();
  73334. }
  73335. _terminate() {
  73336. for (const connectionHolder of this._holders) {
  73337. connectionHolder.terminate();
  73338. }
  73339. }
  73340. terminate() {
  73341. var _a2;
  73342. if ((_a2 = this._closing) == null ? void 0 : _a2.done) {
  73343. return;
  73344. }
  73345. this._queue.cancelAllPending(new errors.InterfaceError(`The client is closed`));
  73346. this._terminate();
  73347. if (!this._closing) {
  73348. this._closing = new event_1.default();
  73349. this._closing.set();
  73350. }
  73351. }
  73352. isClosed() {
  73353. return !!this._closing;
  73354. }
  73355. };
  73356. exports2.BaseClientPool = BaseClientPool;
  73357. var Client = class _Client {
  73358. pool;
  73359. options;
  73360. constructor(pool, options) {
  73361. this.pool = pool;
  73362. this.options = options;
  73363. }
  73364. withTransactionOptions(opts) {
  73365. return new _Client(this.pool, this.options.withTransactionOptions(opts));
  73366. }
  73367. withRetryOptions(opts) {
  73368. return new _Client(this.pool, this.options.withRetryOptions(opts));
  73369. }
  73370. withModuleAliases(aliases) {
  73371. return new _Client(this.pool, this.options.withModuleAliases(aliases));
  73372. }
  73373. withConfig(config) {
  73374. return new _Client(this.pool, this.options.withConfig(config));
  73375. }
  73376. withCodecs(codecs) {
  73377. return new _Client(this.pool, this.options.withCodecs(codecs));
  73378. }
  73379. withSQLRowMode(mode) {
  73380. return new _Client(this.pool, this.options.withSQLRowMode(mode));
  73381. }
  73382. withGlobals(globals) {
  73383. return new _Client(this.pool, this.options.withGlobals(globals));
  73384. }
  73385. withQueryTag(tag) {
  73386. return new _Client(this.pool, this.options.withQueryTag(tag));
  73387. }
  73388. withWarningHandler(handler) {
  73389. return new _Client(this.pool, this.options.withWarningHandler(handler));
  73390. }
  73391. async ensureConnected() {
  73392. await this.pool.ensureConnected();
  73393. return this;
  73394. }
  73395. async resolveConnectionParams() {
  73396. return this.pool.resolveConnectionParams();
  73397. }
  73398. isClosed() {
  73399. return this.pool.isClosed();
  73400. }
  73401. async close() {
  73402. await this.pool.close();
  73403. }
  73404. terminate() {
  73405. this.pool.terminate();
  73406. }
  73407. async transaction(action) {
  73408. if (this.pool.isStateless) {
  73409. throw new errors.GelError(`cannot use 'transaction()' API on HTTP client`);
  73410. }
  73411. const holder = await this.pool.acquireHolder(this.options);
  73412. try {
  73413. return await holder.transaction(action);
  73414. } finally {
  73415. await holder.release();
  73416. }
  73417. }
  73418. async execute(query, args) {
  73419. const holder = await this.pool.acquireHolder(this.options);
  73420. try {
  73421. return await holder.execute(query, args);
  73422. } finally {
  73423. await holder.release();
  73424. }
  73425. }
  73426. async executeSQL(query, args) {
  73427. const holder = await this.pool.acquireHolder(this.options);
  73428. try {
  73429. return await holder.executeSQL(query, args);
  73430. } finally {
  73431. await holder.release();
  73432. }
  73433. }
  73434. async query(query, args) {
  73435. const holder = await this.pool.acquireHolder(this.options);
  73436. try {
  73437. return await holder.query(query, args);
  73438. } finally {
  73439. await holder.release();
  73440. }
  73441. }
  73442. async querySQL(query, args) {
  73443. const holder = await this.pool.acquireHolder(this.options);
  73444. try {
  73445. return await holder.querySQL(query, args);
  73446. } finally {
  73447. await holder.release();
  73448. }
  73449. }
  73450. async queryJSON(query, args) {
  73451. const holder = await this.pool.acquireHolder(this.options);
  73452. try {
  73453. return await holder.queryJSON(query, args);
  73454. } finally {
  73455. await holder.release();
  73456. }
  73457. }
  73458. async querySingle(query, args) {
  73459. const holder = await this.pool.acquireHolder(this.options);
  73460. try {
  73461. return await holder.querySingle(query, args);
  73462. } finally {
  73463. await holder.release();
  73464. }
  73465. }
  73466. async querySingleJSON(query, args) {
  73467. const holder = await this.pool.acquireHolder(this.options);
  73468. try {
  73469. return await holder.querySingleJSON(query, args);
  73470. } finally {
  73471. await holder.release();
  73472. }
  73473. }
  73474. async queryRequired(query, args) {
  73475. const holder = await this.pool.acquireHolder(this.options);
  73476. try {
  73477. return await holder.queryRequired(query, args);
  73478. } finally {
  73479. await holder.release();
  73480. }
  73481. }
  73482. async queryRequiredJSON(query, args) {
  73483. const holder = await this.pool.acquireHolder(this.options);
  73484. try {
  73485. return await holder.queryRequiredJSON(query, args);
  73486. } finally {
  73487. await holder.release();
  73488. }
  73489. }
  73490. async queryRequiredSingle(query, args) {
  73491. const holder = await this.pool.acquireHolder(this.options);
  73492. try {
  73493. return await holder.queryRequiredSingle(query, args);
  73494. } finally {
  73495. await holder.release();
  73496. }
  73497. }
  73498. async queryRequiredSingleJSON(query, args) {
  73499. const holder = await this.pool.acquireHolder(this.options);
  73500. try {
  73501. return await holder.queryRequiredSingleJSON(query, args);
  73502. } finally {
  73503. await holder.release();
  73504. }
  73505. }
  73506. async describe(query) {
  73507. const holder = await this.pool.acquireHolder(this.options);
  73508. try {
  73509. const cxn = await holder._getConnection();
  73510. const result = await cxn._parse(ifaces_1.Language.EDGEQL, query, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, this.options);
  73511. const cardinality = util_1.util.parseCardinality(result[0]);
  73512. return {
  73513. in: result[1],
  73514. out: result[2],
  73515. cardinality,
  73516. capabilities: result[3]
  73517. };
  73518. } finally {
  73519. await holder.release();
  73520. }
  73521. }
  73522. async parse(query) {
  73523. return await this.describe(query);
  73524. }
  73525. };
  73526. exports2.Client = Client;
  73527. }
  73528. });
  73529. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/systemUtils.js
  73530. var require_systemUtils = __commonJS({
  73531. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/systemUtils.js"(exports2) {
  73532. "use strict";
  73533. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  73534. if (k22 === void 0) k22 = k3;
  73535. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  73536. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  73537. desc = { enumerable: true, get: function() {
  73538. return m4[k3];
  73539. } };
  73540. }
  73541. Object.defineProperty(o3, k22, desc);
  73542. } : function(o3, m4, k3, k22) {
  73543. if (k22 === void 0) k22 = k3;
  73544. o3[k22] = m4[k3];
  73545. });
  73546. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  73547. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  73548. } : function(o3, v6) {
  73549. o3["default"] = v6;
  73550. });
  73551. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  73552. if (mod && mod.__esModule) return mod;
  73553. var result = {};
  73554. if (mod != null) {
  73555. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  73556. }
  73557. __setModuleDefault2(result, mod);
  73558. return result;
  73559. };
  73560. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  73561. return mod && mod.__esModule ? mod : { "default": mod };
  73562. };
  73563. Object.defineProperty(exports2, "__esModule", { value: true });
  73564. exports2.readFileUtf8 = readFileUtf8;
  73565. exports2.hasFSReadPermission = hasFSReadPermission;
  73566. exports2.hashSHA1toHex = hashSHA1toHex;
  73567. exports2.walk = walk;
  73568. exports2.exists = exists;
  73569. exports2.input = input;
  73570. var crypto7 = __importStar2(require("node:crypto"));
  73571. var node_fs_1 = require("node:fs");
  73572. var node_path_1 = __importDefault2(require("node:path"));
  73573. var node_process_1 = __importDefault2(require("node:process"));
  73574. var readline = __importStar2(require("node:readline"));
  73575. var node_stream_1 = require("node:stream");
  73576. async function readFileUtf8(...pathParts) {
  73577. return await node_fs_1.promises.readFile(node_path_1.default.join(...pathParts), { encoding: "utf8" });
  73578. }
  73579. function hasFSReadPermission() {
  73580. if (typeof Deno !== "undefined") {
  73581. return Deno.permissions.querySync({ name: "read" }).state === "granted";
  73582. }
  73583. return true;
  73584. }
  73585. function hashSHA1toHex(msg) {
  73586. return crypto7.createHash("sha1").update(msg).digest("hex");
  73587. }
  73588. async function walk(dir, params) {
  73589. const { match: match2, skip = [] } = params || {};
  73590. try {
  73591. await node_fs_1.promises.access(dir);
  73592. } catch (_err) {
  73593. return [];
  73594. }
  73595. const dirents = await node_fs_1.promises.readdir(dir, { withFileTypes: true });
  73596. const files = await Promise.all(dirents.map((dirent) => {
  73597. const fspath = node_path_1.default.resolve(dir, dirent.name);
  73598. if (skip) {
  73599. if (skip.some((re) => re.test(fspath))) {
  73600. return [];
  73601. }
  73602. }
  73603. if (dirent.isDirectory()) {
  73604. return walk(fspath, params);
  73605. }
  73606. if (match2) {
  73607. if (!match2.some((re) => re.test(fspath))) {
  73608. return [];
  73609. }
  73610. }
  73611. return [fspath];
  73612. }));
  73613. return Array.prototype.concat(...files);
  73614. }
  73615. async function exists(filepath) {
  73616. try {
  73617. await node_fs_1.promises.access(filepath);
  73618. return true;
  73619. } catch {
  73620. return false;
  73621. }
  73622. }
  73623. async function input(message, params) {
  73624. let silent = false;
  73625. const output = (params == null ? void 0 : params.silent) ? new node_stream_1.Writable({
  73626. write(chunk, encoding, callback) {
  73627. if (!silent)
  73628. node_process_1.default.stdout.write(chunk, encoding);
  73629. callback();
  73630. }
  73631. }) : node_process_1.default.stdout;
  73632. const rl = readline.createInterface({
  73633. input: node_process_1.default.stdin,
  73634. output
  73635. });
  73636. return new Promise((resolve2) => {
  73637. rl.question(message, (val2) => {
  73638. rl.close();
  73639. resolve2(val2);
  73640. });
  73641. silent = true;
  73642. });
  73643. }
  73644. }
  73645. });
  73646. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/platform.js
  73647. var require_platform = __commonJS({
  73648. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/platform.js"(exports2) {
  73649. "use strict";
  73650. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  73651. return mod && mod.__esModule ? mod : { "default": mod };
  73652. };
  73653. Object.defineProperty(exports2, "__esModule", { value: true });
  73654. exports2.isWindows = void 0;
  73655. exports2.searchConfigDir = searchConfigDir;
  73656. var node_path_1 = __importDefault2(require("node:path"));
  73657. var node_os_1 = __importDefault2(require("node:os"));
  73658. var systemUtils_1 = require_systemUtils();
  73659. exports2.isWindows = process.platform === "win32";
  73660. var homeDir = node_os_1.default.homedir;
  73661. var _configDir;
  73662. if (process.platform === "darwin") {
  73663. _configDir = () => {
  73664. return node_path_1.default.join(homeDir(), "Library", "Application Support", "edgedb");
  73665. };
  73666. } else if (process.platform === "win32") {
  73667. _configDir = () => {
  73668. const localAppDataDir = process.env.LOCALAPPDATA ?? node_path_1.default.join(homeDir(), "AppData", "Local");
  73669. return node_path_1.default.join(localAppDataDir, "EdgeDB", "config");
  73670. };
  73671. } else {
  73672. _configDir = () => {
  73673. let xdgConfigDir = process.env.XDG_CONFIG_HOME;
  73674. if (!xdgConfigDir || !node_path_1.default.isAbsolute(xdgConfigDir)) {
  73675. xdgConfigDir = node_path_1.default.join(homeDir(), ".config");
  73676. }
  73677. return node_path_1.default.join(xdgConfigDir, "edgedb");
  73678. };
  73679. }
  73680. async function searchConfigDir(...configPath) {
  73681. const filePath = node_path_1.default.join(_configDir(), ...configPath);
  73682. if (await (0, systemUtils_1.exists)(filePath)) {
  73683. return filePath;
  73684. }
  73685. const fallbackPath = node_path_1.default.join(homeDir(), ".edgedb", ...configPath);
  73686. if (await (0, systemUtils_1.exists)(fallbackPath)) {
  73687. return fallbackPath;
  73688. }
  73689. return filePath;
  73690. }
  73691. }
  73692. });
  73693. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/credentials.js
  73694. var require_credentials = __commonJS({
  73695. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/credentials.js"(exports2) {
  73696. "use strict";
  73697. Object.defineProperty(exports2, "__esModule", { value: true });
  73698. exports2.getCredentialsPath = getCredentialsPath;
  73699. exports2.readCredentialsFile = readCredentialsFile;
  73700. exports2.validateCredentials = validateCredentials;
  73701. var conUtils_1 = require_conUtils();
  73702. var errors_1 = require_errors();
  73703. async function getCredentialsPath(instanceName, serverUtils) {
  73704. return serverUtils.searchConfigDir("credentials", instanceName + ".json");
  73705. }
  73706. async function readCredentialsFile(file, serverUtils) {
  73707. try {
  73708. const data = await serverUtils.readFileUtf8(file);
  73709. return validateCredentials(JSON.parse(data));
  73710. } catch (e4) {
  73711. throw new errors_1.InterfaceError(`cannot read credentials file ${file}: ${e4}`);
  73712. }
  73713. }
  73714. function validateCredentials(data) {
  73715. const port = data.port;
  73716. if (port != null && (typeof port !== "number" || port < 1 || port > 65535)) {
  73717. throw new errors_1.InterfaceError("invalid `port` value");
  73718. }
  73719. const user = data.user;
  73720. if (user == null) {
  73721. throw new errors_1.InterfaceError("`user` key is required");
  73722. }
  73723. if (typeof user !== "string") {
  73724. throw new errors_1.InterfaceError("`user` must be string");
  73725. }
  73726. const result = { user, port };
  73727. const host = data.host;
  73728. if (host != null) {
  73729. if (typeof host !== "string") {
  73730. throw new errors_1.InterfaceError("`host` must be string");
  73731. }
  73732. result.host = host;
  73733. }
  73734. const database = data.database;
  73735. if (database != null) {
  73736. if (typeof database !== "string") {
  73737. throw new errors_1.InterfaceError("`database` must be string");
  73738. }
  73739. result.database = database;
  73740. }
  73741. const branch = data.branch;
  73742. if (branch != null) {
  73743. if (typeof branch !== "string") {
  73744. throw new errors_1.InterfaceError("`branch` must be string");
  73745. }
  73746. if (database != null && branch !== database) {
  73747. throw new errors_1.InterfaceError("`database` and `branch` cannot both be set");
  73748. }
  73749. result.branch = branch;
  73750. }
  73751. const password = data.password;
  73752. if (password != null) {
  73753. if (typeof password !== "string") {
  73754. throw new errors_1.InterfaceError("`password` must be string");
  73755. }
  73756. result.password = password;
  73757. }
  73758. const caData = data.tls_ca;
  73759. if (caData != null) {
  73760. if (typeof caData !== "string") {
  73761. throw new errors_1.InterfaceError("`tls_ca` must be string");
  73762. }
  73763. result.tlsCAData = caData;
  73764. }
  73765. const certData = data.tls_cert_data;
  73766. if (certData != null) {
  73767. if (typeof certData !== "string") {
  73768. throw new errors_1.InterfaceError("`tls_cert_data` must be string");
  73769. }
  73770. if (caData != null && certData !== caData) {
  73771. throw new errors_1.InterfaceError(`both 'tls_ca' and 'tls_cert_data' are defined, and are not in agreement`);
  73772. }
  73773. result.tlsCAData = certData;
  73774. }
  73775. let verifyHostname = data.tls_verify_hostname;
  73776. const tlsSecurity = data.tls_security;
  73777. if (verifyHostname != null) {
  73778. if (typeof verifyHostname === "boolean") {
  73779. verifyHostname = verifyHostname ? "strict" : "no_host_verification";
  73780. } else {
  73781. throw new errors_1.InterfaceError("`tls_verify_hostname` must be boolean");
  73782. }
  73783. }
  73784. if (tlsSecurity != null && (typeof tlsSecurity !== "string" || !conUtils_1.validTlsSecurityValues.includes(tlsSecurity))) {
  73785. throw new errors_1.InterfaceError(`\`tls_security\` must be one of ${conUtils_1.validTlsSecurityValues.map((val2) => `"${val2}"`).join(", ")}`);
  73786. }
  73787. if (verifyHostname && tlsSecurity && verifyHostname !== tlsSecurity && !(verifyHostname === "no_host_verification" && tlsSecurity === "insecure")) {
  73788. throw new errors_1.InterfaceError(`both 'tls_security' and 'tls_verify_hostname' are defined, and are not in agreement`);
  73789. }
  73790. if (tlsSecurity || verifyHostname) {
  73791. result.tlsSecurity = tlsSecurity ?? verifyHostname;
  73792. }
  73793. return result;
  73794. }
  73795. }
  73796. });
  73797. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/crcHqx.js
  73798. var require_crcHqx = __commonJS({
  73799. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/primitives/crcHqx.js"(exports2) {
  73800. "use strict";
  73801. Object.defineProperty(exports2, "__esModule", { value: true });
  73802. exports2.crcHqx = crcHqx;
  73803. var crctabHqx = new Uint16Array([
  73804. 0,
  73805. 4129,
  73806. 8258,
  73807. 12387,
  73808. 16516,
  73809. 20645,
  73810. 24774,
  73811. 28903,
  73812. 33032,
  73813. 37161,
  73814. 41290,
  73815. 45419,
  73816. 49548,
  73817. 53677,
  73818. 57806,
  73819. 61935,
  73820. 4657,
  73821. 528,
  73822. 12915,
  73823. 8786,
  73824. 21173,
  73825. 17044,
  73826. 29431,
  73827. 25302,
  73828. 37689,
  73829. 33560,
  73830. 45947,
  73831. 41818,
  73832. 54205,
  73833. 50076,
  73834. 62463,
  73835. 58334,
  73836. 9314,
  73837. 13379,
  73838. 1056,
  73839. 5121,
  73840. 25830,
  73841. 29895,
  73842. 17572,
  73843. 21637,
  73844. 42346,
  73845. 46411,
  73846. 34088,
  73847. 38153,
  73848. 58862,
  73849. 62927,
  73850. 50604,
  73851. 54669,
  73852. 13907,
  73853. 9842,
  73854. 5649,
  73855. 1584,
  73856. 30423,
  73857. 26358,
  73858. 22165,
  73859. 18100,
  73860. 46939,
  73861. 42874,
  73862. 38681,
  73863. 34616,
  73864. 63455,
  73865. 59390,
  73866. 55197,
  73867. 51132,
  73868. 18628,
  73869. 22757,
  73870. 26758,
  73871. 30887,
  73872. 2112,
  73873. 6241,
  73874. 10242,
  73875. 14371,
  73876. 51660,
  73877. 55789,
  73878. 59790,
  73879. 63919,
  73880. 35144,
  73881. 39273,
  73882. 43274,
  73883. 47403,
  73884. 23285,
  73885. 19156,
  73886. 31415,
  73887. 27286,
  73888. 6769,
  73889. 2640,
  73890. 14899,
  73891. 10770,
  73892. 56317,
  73893. 52188,
  73894. 64447,
  73895. 60318,
  73896. 39801,
  73897. 35672,
  73898. 47931,
  73899. 43802,
  73900. 27814,
  73901. 31879,
  73902. 19684,
  73903. 23749,
  73904. 11298,
  73905. 15363,
  73906. 3168,
  73907. 7233,
  73908. 60846,
  73909. 64911,
  73910. 52716,
  73911. 56781,
  73912. 44330,
  73913. 48395,
  73914. 36200,
  73915. 40265,
  73916. 32407,
  73917. 28342,
  73918. 24277,
  73919. 20212,
  73920. 15891,
  73921. 11826,
  73922. 7761,
  73923. 3696,
  73924. 65439,
  73925. 61374,
  73926. 57309,
  73927. 53244,
  73928. 48923,
  73929. 44858,
  73930. 40793,
  73931. 36728,
  73932. 37256,
  73933. 33193,
  73934. 45514,
  73935. 41451,
  73936. 53516,
  73937. 49453,
  73938. 61774,
  73939. 57711,
  73940. 4224,
  73941. 161,
  73942. 12482,
  73943. 8419,
  73944. 20484,
  73945. 16421,
  73946. 28742,
  73947. 24679,
  73948. 33721,
  73949. 37784,
  73950. 41979,
  73951. 46042,
  73952. 49981,
  73953. 54044,
  73954. 58239,
  73955. 62302,
  73956. 689,
  73957. 4752,
  73958. 8947,
  73959. 13010,
  73960. 16949,
  73961. 21012,
  73962. 25207,
  73963. 29270,
  73964. 46570,
  73965. 42443,
  73966. 38312,
  73967. 34185,
  73968. 62830,
  73969. 58703,
  73970. 54572,
  73971. 50445,
  73972. 13538,
  73973. 9411,
  73974. 5280,
  73975. 1153,
  73976. 29798,
  73977. 25671,
  73978. 21540,
  73979. 17413,
  73980. 42971,
  73981. 47098,
  73982. 34713,
  73983. 38840,
  73984. 59231,
  73985. 63358,
  73986. 50973,
  73987. 55100,
  73988. 9939,
  73989. 14066,
  73990. 1681,
  73991. 5808,
  73992. 26199,
  73993. 30326,
  73994. 17941,
  73995. 22068,
  73996. 55628,
  73997. 51565,
  73998. 63758,
  73999. 59695,
  74000. 39368,
  74001. 35305,
  74002. 47498,
  74003. 43435,
  74004. 22596,
  74005. 18533,
  74006. 30726,
  74007. 26663,
  74008. 6336,
  74009. 2273,
  74010. 14466,
  74011. 10403,
  74012. 52093,
  74013. 56156,
  74014. 60223,
  74015. 64286,
  74016. 35833,
  74017. 39896,
  74018. 43963,
  74019. 48026,
  74020. 19061,
  74021. 23124,
  74022. 27191,
  74023. 31254,
  74024. 2801,
  74025. 6864,
  74026. 10931,
  74027. 14994,
  74028. 64814,
  74029. 60687,
  74030. 56684,
  74031. 52557,
  74032. 48554,
  74033. 44427,
  74034. 40424,
  74035. 36297,
  74036. 31782,
  74037. 27655,
  74038. 23652,
  74039. 19525,
  74040. 15522,
  74041. 11395,
  74042. 7392,
  74043. 3265,
  74044. 61215,
  74045. 65342,
  74046. 53085,
  74047. 57212,
  74048. 44955,
  74049. 49082,
  74050. 36825,
  74051. 40952,
  74052. 28183,
  74053. 32310,
  74054. 20053,
  74055. 24180,
  74056. 11923,
  74057. 16050,
  74058. 3793,
  74059. 7920
  74060. ]);
  74061. function crcHqx(data, crc) {
  74062. crc &= 65535;
  74063. const len = data.length;
  74064. let i4 = 0;
  74065. while (i4 < len) {
  74066. crc = crc << 8 & 65280 ^ crctabHqx[crc >> 8 ^ data[i4++]];
  74067. }
  74068. return crc;
  74069. }
  74070. }
  74071. });
  74072. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.js
  74073. var require_conUtils = __commonJS({
  74074. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.js"(exports2) {
  74075. "use strict";
  74076. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  74077. if (k22 === void 0) k22 = k3;
  74078. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  74079. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  74080. desc = { enumerable: true, get: function() {
  74081. return m4[k3];
  74082. } };
  74083. }
  74084. Object.defineProperty(o3, k22, desc);
  74085. } : function(o3, m4, k3, k22) {
  74086. if (k22 === void 0) k22 = k3;
  74087. o3[k22] = m4[k3];
  74088. });
  74089. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  74090. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  74091. } : function(o3, v6) {
  74092. o3["default"] = v6;
  74093. });
  74094. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  74095. if (mod && mod.__esModule) return mod;
  74096. var result = {};
  74097. if (mod != null) {
  74098. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  74099. }
  74100. __setModuleDefault2(result, mod);
  74101. return result;
  74102. };
  74103. Object.defineProperty(exports2, "__esModule", { value: true });
  74104. exports2.ResolvedConnectConfig = exports2.validTlsSecurityValues = void 0;
  74105. exports2.isValidTlsSecurityValue = isValidTlsSecurityValue;
  74106. exports2.getConnectArgumentsParser = getConnectArgumentsParser;
  74107. exports2.parseDuration = parseDuration;
  74108. var errors = __importStar2(require_errors());
  74109. var credentials_1 = require_credentials();
  74110. var datetime_1 = require_datetime();
  74111. var datetime_2 = require_datetime2();
  74112. var errors_1 = require_errors();
  74113. var buffer_1 = require_buffer();
  74114. var crcHqx_1 = require_crcHqx();
  74115. var DOMAIN_NAME_MAX_LEN = 63;
  74116. exports2.validTlsSecurityValues = [
  74117. "insecure",
  74118. "no_host_verification",
  74119. "strict",
  74120. "default"
  74121. ];
  74122. function isValidTlsSecurityValue(candidate) {
  74123. return typeof candidate === "string" && exports2.validTlsSecurityValues.includes(candidate);
  74124. }
  74125. function getConnectArgumentsParser(utils) {
  74126. return async (opts) => {
  74127. return {
  74128. ...await parseConnectDsnAndArgs(opts, utils),
  74129. connectTimeout: opts.timeout,
  74130. logging: opts.logging ?? true
  74131. };
  74132. };
  74133. }
  74134. function getEnv(envName, _required = false) {
  74135. const gelEnv = envName;
  74136. const edgedbEnv = envName.replace(/^GEL_/, "EDGEDB_");
  74137. const gelValue = process.env[gelEnv];
  74138. const edgedbValue = process.env[edgedbEnv];
  74139. if (gelValue !== void 0 && edgedbValue !== void 0) {
  74140. console.warn(`Both GEL_w+ and EDGEDB_w+ are set; EDGEDB_w+ will be ignored`);
  74141. }
  74142. return gelValue ?? edgedbValue;
  74143. }
  74144. var ResolvedConnectConfig = class {
  74145. _host = null;
  74146. _hostSource = null;
  74147. _port = null;
  74148. _portSource = null;
  74149. _database = null;
  74150. _databaseSource = null;
  74151. _branch = null;
  74152. _branchSource = null;
  74153. _user = null;
  74154. _userSource = null;
  74155. _password = null;
  74156. _passwordSource = null;
  74157. _secretKey = null;
  74158. _secretKeySource = null;
  74159. _cloudProfile = null;
  74160. _cloudProfileSource = null;
  74161. _tlsCAData = null;
  74162. _tlsCADataSource = null;
  74163. _tlsSecurity = null;
  74164. _tlsSecuritySource = null;
  74165. _tlsServerName = null;
  74166. _tlsServerNameSource = null;
  74167. _waitUntilAvailable = null;
  74168. _waitUntilAvailableSource = null;
  74169. serverSettings = {};
  74170. constructor() {
  74171. this.setHost = this.setHost.bind(this);
  74172. this.setPort = this.setPort.bind(this);
  74173. this.setDatabase = this.setDatabase.bind(this);
  74174. this.setBranch = this.setBranch.bind(this);
  74175. this.setUser = this.setUser.bind(this);
  74176. this.setPassword = this.setPassword.bind(this);
  74177. this.setSecretKey = this.setSecretKey.bind(this);
  74178. this.setTlsCAData = this.setTlsCAData.bind(this);
  74179. this.setTlsCAFile = this.setTlsCAFile.bind(this);
  74180. this.setTlsServerName = this.setTlsServerName.bind(this);
  74181. this.setTlsSecurity = this.setTlsSecurity.bind(this);
  74182. this.setWaitUntilAvailable = this.setWaitUntilAvailable.bind(this);
  74183. }
  74184. _setParam(param, value, source, validator2) {
  74185. if (this[`_${param}`] === null) {
  74186. this[`_${param}Source`] = source;
  74187. if (value !== null) {
  74188. this[`_${param}`] = validator2 ? validator2(value) : value;
  74189. return true;
  74190. }
  74191. }
  74192. return false;
  74193. }
  74194. async _setParamAsync(param, value, source, validator2) {
  74195. if (this[`_${param}`] === null) {
  74196. this[`_${param}Source`] = source;
  74197. if (value !== null) {
  74198. this[`_${param}`] = validator2 ? await validator2(value) : value;
  74199. return true;
  74200. }
  74201. }
  74202. return false;
  74203. }
  74204. setHost(host, source) {
  74205. return this._setParam("host", host, source, validateHost);
  74206. }
  74207. setPort(port, source) {
  74208. return this._setParam("port", port, source, parseValidatePort);
  74209. }
  74210. setDatabase(database, source) {
  74211. return this._setParam("database", database, source, (db) => {
  74212. if (db === "") {
  74213. throw new errors_1.InterfaceError(`invalid database name: '${db}'`);
  74214. }
  74215. return db;
  74216. });
  74217. }
  74218. setBranch(branch, source) {
  74219. return this._setParam("branch", branch, source, (branchName) => {
  74220. if (branchName === "") {
  74221. throw new errors_1.InterfaceError(`invalid branch name: '${branchName}'`);
  74222. }
  74223. return branchName;
  74224. });
  74225. }
  74226. setUser(user, source) {
  74227. return this._setParam("user", user, source, (_user) => {
  74228. if (_user === "") {
  74229. throw new errors_1.InterfaceError(`invalid user name: '${_user}'`);
  74230. }
  74231. return _user;
  74232. });
  74233. }
  74234. setPassword(password, source) {
  74235. return this._setParam("password", password, source);
  74236. }
  74237. setSecretKey(secretKey, source) {
  74238. return this._setParam("secretKey", secretKey, source);
  74239. }
  74240. setCloudProfile(cloudProfile, source) {
  74241. return this._setParam("cloudProfile", cloudProfile, source);
  74242. }
  74243. setTlsCAData(caData, source) {
  74244. return this._setParam("tlsCAData", caData, source);
  74245. }
  74246. setTlsCAFile(caFile, source, readFile2) {
  74247. return this._setParamAsync("tlsCAData", caFile, source, (caFilePath) => readFile2(caFilePath));
  74248. }
  74249. setTlsServerName(serverName, source) {
  74250. return this._setParam("tlsServerName", serverName, source, validateHost);
  74251. }
  74252. setTlsSecurity(tlsSecurity, source) {
  74253. return this._setParam("tlsSecurity", tlsSecurity, source, (_tlsSecurity) => {
  74254. if (!exports2.validTlsSecurityValues.includes(_tlsSecurity)) {
  74255. throw new errors_1.InterfaceError(`invalid 'tlsSecurity' value: '${_tlsSecurity}', must be one of ${exports2.validTlsSecurityValues.map((val2) => `'${val2}'`).join(", ")}`);
  74256. }
  74257. const clientSecurity = getEnv("GEL_CLIENT_SECURITY");
  74258. if (clientSecurity !== void 0) {
  74259. if (!["default", "insecure_dev_mode", "strict"].includes(clientSecurity)) {
  74260. throw new errors_1.InterfaceError(`invalid GEL_CLIENT_SECURITY value: '${clientSecurity}', must be one of 'default', 'insecure_dev_mode' or 'strict'`);
  74261. }
  74262. if (clientSecurity === "insecure_dev_mode") {
  74263. if (_tlsSecurity === "default") {
  74264. _tlsSecurity = "insecure";
  74265. }
  74266. } else if (clientSecurity === "strict") {
  74267. if (_tlsSecurity === "insecure" || _tlsSecurity === "no_host_verification") {
  74268. throw new errors_1.InterfaceError(`'tlsSecurity' value (${_tlsSecurity}) conflicts with GEL_CLIENT_SECURITY value (${clientSecurity}), 'tlsSecurity' value cannot be lower than security level set by GEL_CLIENT_SECURITY`);
  74269. }
  74270. _tlsSecurity = "strict";
  74271. }
  74272. }
  74273. return _tlsSecurity;
  74274. });
  74275. }
  74276. setWaitUntilAvailable(duration, source) {
  74277. return this._setParam("waitUntilAvailable", duration, source, parseDuration);
  74278. }
  74279. addServerSettings(settings) {
  74280. this.serverSettings = {
  74281. ...settings,
  74282. ...this.serverSettings
  74283. };
  74284. }
  74285. get address() {
  74286. return [this._host ?? "localhost", this._port ?? 5656];
  74287. }
  74288. get database() {
  74289. return this._database ?? this._branch ?? "edgedb";
  74290. }
  74291. get branch() {
  74292. return this._branch ?? this._database ?? "__default__";
  74293. }
  74294. get user() {
  74295. return this._user ?? "edgedb";
  74296. }
  74297. get password() {
  74298. return this._password ?? void 0;
  74299. }
  74300. get secretKey() {
  74301. return this._secretKey ?? void 0;
  74302. }
  74303. get cloudProfile() {
  74304. return this._cloudProfile ?? "default";
  74305. }
  74306. get tlsServerName() {
  74307. return this._tlsServerName ?? void 0;
  74308. }
  74309. get tlsSecurity() {
  74310. return this._tlsSecurity && this._tlsSecurity !== "default" ? this._tlsSecurity : this._tlsCAData !== null ? "no_host_verification" : "strict";
  74311. }
  74312. get waitUntilAvailable() {
  74313. return this._waitUntilAvailable ?? 3e4;
  74314. }
  74315. explainConfig() {
  74316. const output = [
  74317. `Parameter Value Source`,
  74318. `--------- ----- ------`
  74319. ];
  74320. const outputLine = (param, val2, rawVal, source) => {
  74321. const isDefault = rawVal === null;
  74322. const maxValLength = 40 - (isDefault ? 10 : 0);
  74323. let value = String(val2);
  74324. if (value.length > maxValLength) {
  74325. value = value.slice(0, maxValLength - 3) + "...";
  74326. }
  74327. output.push(param.padEnd(19, " ") + (value + (isDefault ? " (default)" : "")).padEnd(42, " ") + (source ?? "default"));
  74328. };
  74329. outputLine("host", this.address[0], this._host, this._hostSource);
  74330. outputLine("port", this.address[1], this._port, this._portSource);
  74331. outputLine("database", this.database, this._database, this._databaseSource);
  74332. outputLine("branch", this.branch, this._branch, this._branchSource);
  74333. outputLine("user", this.user, this._user, this._userSource);
  74334. outputLine("password", this.password && this.password.slice(0, 3).padEnd(this.password.length, "*"), this._password, this._passwordSource);
  74335. outputLine("tlsCAData", this._tlsCAData && this._tlsCAData.replace(/\r\n?|\n/, ""), this._tlsCAData, this._tlsCADataSource);
  74336. outputLine("tlsSecurity", this.tlsSecurity, this._tlsSecurity, this._tlsSecuritySource);
  74337. outputLine("tlsServerName", this.tlsServerName, this._tlsServerName, this._tlsServerNameSource);
  74338. outputLine("waitUntilAvailable", this.waitUntilAvailable, this._waitUntilAvailable, this._waitUntilAvailableSource);
  74339. return output.join("\n");
  74340. }
  74341. };
  74342. exports2.ResolvedConnectConfig = ResolvedConnectConfig;
  74343. function parseValidatePort(port) {
  74344. let parsedPort;
  74345. if (typeof port === "string") {
  74346. if (!/^\d*$/.test(port)) {
  74347. throw new errors_1.InterfaceError(`invalid port: ${port}`);
  74348. }
  74349. parsedPort = parseInt(port, 10);
  74350. if (Number.isNaN(parsedPort)) {
  74351. throw new errors_1.InterfaceError(`invalid port: ${port}`);
  74352. }
  74353. } else {
  74354. parsedPort = port;
  74355. }
  74356. if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
  74357. throw new errors_1.InterfaceError(`invalid port: ${port}`);
  74358. }
  74359. return parsedPort;
  74360. }
  74361. function validateHost(host) {
  74362. if (host.includes("/")) {
  74363. throw new errors_1.InterfaceError(`unix socket paths not supported`);
  74364. }
  74365. if (!host.length || host.includes(",")) {
  74366. throw new errors_1.InterfaceError(`invalid host: '${host}'`);
  74367. }
  74368. return host;
  74369. }
  74370. function parseDuration(duration) {
  74371. if (typeof duration === "number") {
  74372. if (duration < 0) {
  74373. throw new errors_1.InterfaceError("invalid waitUntilAvailable duration, must be >= 0");
  74374. }
  74375. return duration;
  74376. }
  74377. if (typeof duration === "string") {
  74378. if (duration.startsWith("P")) {
  74379. duration = datetime_1.Duration.from(duration);
  74380. } else {
  74381. return (0, datetime_1.parseHumanDurationString)(duration);
  74382. }
  74383. }
  74384. if (duration instanceof datetime_1.Duration) {
  74385. const invalidField = (0, datetime_2.checkValidGelDuration)(duration);
  74386. if (invalidField) {
  74387. throw new errors_1.InterfaceError(`invalid waitUntilAvailable duration, cannot have a '${invalidField}' value`);
  74388. }
  74389. if (duration.sign < 0) {
  74390. throw new errors_1.InterfaceError("invalid waitUntilAvailable duration, must be >= 0");
  74391. }
  74392. return duration.milliseconds + duration.seconds * 1e3 + duration.minutes * 6e4 + duration.hours * 36e5;
  74393. }
  74394. throw new errors_1.InterfaceError(`invalid duration`);
  74395. }
  74396. async function parseConnectDsnAndArgs(config, serverUtils) {
  74397. const resolvedConfig = new ResolvedConnectConfig();
  74398. let fromEnv = false;
  74399. let fromProject = false;
  74400. const [dsn, instanceName] = config.instanceName == null && config.dsn != null && !/^[a-z]+:\/\//i.test(config.dsn) ? [void 0, config.dsn] : [config.dsn, config.instanceName];
  74401. let { hasCompoundOptions } = await resolveConfigOptions(resolvedConfig, {
  74402. dsn,
  74403. instanceName,
  74404. credentials: config.credentials,
  74405. credentialsFile: config.credentialsFile,
  74406. host: config.host,
  74407. port: config.port,
  74408. database: config.database,
  74409. branch: config.branch,
  74410. user: config.user,
  74411. password: config.password,
  74412. secretKey: config.secretKey,
  74413. cloudProfile: getEnv("GEL_CLOUD_PROFILE"),
  74414. tlsCA: config.tlsCA,
  74415. tlsCAFile: config.tlsCAFile,
  74416. tlsServerName: config.tlsServerName,
  74417. tlsSecurity: config.tlsSecurity,
  74418. serverSettings: config.serverSettings,
  74419. waitUntilAvailable: config.waitUntilAvailable
  74420. }, {
  74421. dsn: `'dsnOrInstanceName' option (parsed as dsn)`,
  74422. instanceName: config.instanceName != null ? `'instanceName' option` : `'dsnOrInstanceName' option (parsed as instance name)`,
  74423. credentials: `'credentials' option`,
  74424. credentialsFile: `'credentialsFile' option`,
  74425. host: `'host' option`,
  74426. port: `'port' option`,
  74427. database: `'database' option`,
  74428. branch: `'branch' option`,
  74429. user: `'user' option`,
  74430. password: `'password' option`,
  74431. secretKey: `'secretKey' option`,
  74432. cloudProfile: `'GEL_CLOUD_PROFILE' environment variable`,
  74433. tlsCA: `'tlsCA' option`,
  74434. tlsCAFile: `'tlsCAFile' option`,
  74435. tlsSecurity: `'tlsSecurity' option`,
  74436. tlsServerName: `'tlsServerName' option`,
  74437. serverSettings: `'serverSettings' option`,
  74438. waitUntilAvailable: `'waitUntilAvailable' option`
  74439. }, `Cannot have more than one of the following connection options: 'dsn', 'instanceName', 'credentials', 'credentialsFile' or 'host'/'port'`, serverUtils);
  74440. if (!hasCompoundOptions) {
  74441. let port = getEnv("GEL_PORT");
  74442. if (resolvedConfig._port === null && (port == null ? void 0 : port.startsWith("tcp://"))) {
  74443. console.warn(`GEL_PORT in 'tcp://host:port' format, so will be ignored`);
  74444. port = void 0;
  74445. }
  74446. ({ hasCompoundOptions, anyOptionsUsed: fromEnv } = await resolveConfigOptions(resolvedConfig, {
  74447. dsn: getEnv("GEL_DSN"),
  74448. instanceName: getEnv("GEL_INSTANCE"),
  74449. credentials: getEnv("GEL_CREDENTIALS"),
  74450. credentialsFile: getEnv("GEL_CREDENTIALS_FILE"),
  74451. host: getEnv("GEL_HOST"),
  74452. port,
  74453. database: getEnv("GEL_DATABASE"),
  74454. branch: getEnv("GEL_BRANCH"),
  74455. user: getEnv("GEL_USER"),
  74456. password: getEnv("GEL_PASSWORD"),
  74457. secretKey: getEnv("GEL_SECRET_KEY"),
  74458. tlsCA: getEnv("GEL_TLS_CA"),
  74459. tlsCAFile: getEnv("GEL_TLS_CA_FILE"),
  74460. tlsServerName: getEnv("GEL_TLS_SERVER_NAME"),
  74461. tlsSecurity: getEnv("GEL_CLIENT_TLS_SECURITY"),
  74462. waitUntilAvailable: getEnv("GEL_WAIT_UNTIL_AVAILABLE")
  74463. }, {
  74464. dsn: `'GEL_DSN' environment variable`,
  74465. instanceName: `'GEL_INSTANCE' environment variable`,
  74466. credentials: `'GEL_CREDENTIALS' environment variable`,
  74467. credentialsFile: `'GEL_CREDENTIALS_FILE' environment variable`,
  74468. host: `'GEL_HOST' environment variable`,
  74469. port: `'GEL_PORT' environment variable`,
  74470. database: `'GEL_DATABASE' environment variable`,
  74471. branch: `'GEL_BRANCH' environment variable`,
  74472. user: `'GEL_USER' environment variable`,
  74473. password: `'GEL_PASSWORD' environment variable`,
  74474. secretKey: `'GEL_SECRET_KEY' environment variable`,
  74475. tlsCA: `'GEL_TLS_CA' environment variable`,
  74476. tlsCAFile: `'GEL_TLS_CA_FILE' environment variable`,
  74477. tlsServerName: `'GEL_TLS_SERVER_NAME' environment variable`,
  74478. tlsSecurity: `'GEL_CLIENT_TLS_SECURITY' environment variable`,
  74479. waitUntilAvailable: `'GEL_WAIT_UNTIL_AVAILABLE' environment variable`
  74480. }, `Cannot have more than one of the following connection environment variables: 'GEL_DSN', 'GEL_INSTANCE', 'GEL_CREDENTIALS', 'GEL_CREDENTIALS_FILE' or 'GEL_HOST'`, serverUtils));
  74481. }
  74482. if (!hasCompoundOptions) {
  74483. if (!serverUtils) {
  74484. throw new errors.ClientConnectionError("no connection options specified either by arguments to `createClient` API or environment variables; also cannot resolve from project config file in browser (or edge runtime) environment");
  74485. }
  74486. const projectDir = await (serverUtils == null ? void 0 : serverUtils.findProjectDir());
  74487. if (!projectDir) {
  74488. throw new errors.ClientConnectionError("no project config file found and no connection options specified either via arguments to `createClient()` API or via environment variables GEL_HOST, GEL_INSTANCE, GEL_DSN, GEL_CREDENTIALS or GEL_CREDENTIALS_FILE");
  74489. }
  74490. const stashDir = await serverUtils.findStashPath(projectDir);
  74491. const instName = await serverUtils.readFileUtf8(stashDir, "instance-name").then((name) => name.trim()).catch(() => null);
  74492. if (instName !== null) {
  74493. const [cloudProfile, _database, branch] = await Promise.all([
  74494. serverUtils.readFileUtf8(stashDir, "cloud-profile").then((name) => name.trim()).catch(() => void 0),
  74495. serverUtils.readFileUtf8(stashDir, "database").then((name) => name.trim()).catch(() => void 0),
  74496. serverUtils.readFileUtf8(stashDir, "branch").then((name) => name.trim()).catch(() => void 0)
  74497. ]);
  74498. let database = _database;
  74499. if (database !== void 0 && branch !== void 0) {
  74500. if (database !== branch) {
  74501. throw new errors_1.InterfaceError("Both database and branch exist in the config dir and don't match.");
  74502. } else {
  74503. database = void 0;
  74504. }
  74505. }
  74506. await resolveConfigOptions(resolvedConfig, { instanceName: instName, cloudProfile, database, branch }, {
  74507. instanceName: `project linked instance ('${instName}')`,
  74508. cloudProfile: `project defined cloud instance ('${cloudProfile}')`,
  74509. database: `project default database`,
  74510. branch: `project default branch`
  74511. }, "", serverUtils);
  74512. fromProject = true;
  74513. } else {
  74514. throw new errors.ClientConnectionError("Found project config file but the project is not initialized. Run 'gel project init'.");
  74515. }
  74516. }
  74517. resolvedConfig.setTlsSecurity("default", "default");
  74518. return {
  74519. connectionParams: resolvedConfig,
  74520. inProject: async () => await (serverUtils == null ? void 0 : serverUtils.findProjectDir(false)) != null,
  74521. fromEnv,
  74522. fromProject
  74523. };
  74524. }
  74525. async function resolveConfigOptions(resolvedConfig, config, sources, compoundParamsError, serverUtils) {
  74526. var _a2;
  74527. let anyOptionsUsed = false;
  74528. const readFile2 = (serverUtils == null ? void 0 : serverUtils.readFileUtf8) ?? ((fn) => {
  74529. throw new errors_1.InterfaceError(`cannot read file "${fn}" in browser (or edge runtime) environment`);
  74530. });
  74531. if (config.tlsCA != null && config.tlsCAFile != null) {
  74532. throw new errors_1.InterfaceError(`Cannot specify both ${sources.tlsCA} and ${sources.tlsCAFile}`);
  74533. }
  74534. if (config.database != null) {
  74535. if (config.branch != null) {
  74536. throw new errors_1.InterfaceError(`${sources.database} and ${sources.branch} are mutually exclusive`);
  74537. }
  74538. if (resolvedConfig._branch == null) {
  74539. anyOptionsUsed = resolvedConfig.setDatabase(config.database ?? null, sources.database) || anyOptionsUsed;
  74540. }
  74541. }
  74542. if (config.branch != null) {
  74543. if (resolvedConfig._database == null) {
  74544. anyOptionsUsed = resolvedConfig.setBranch(config.branch ?? null, sources.branch) || anyOptionsUsed;
  74545. }
  74546. }
  74547. anyOptionsUsed = resolvedConfig.setUser(config.user ?? null, sources.user) || anyOptionsUsed;
  74548. anyOptionsUsed = resolvedConfig.setPassword(config.password ?? null, sources.password) || anyOptionsUsed;
  74549. anyOptionsUsed = resolvedConfig.setSecretKey(config.secretKey ?? null, sources.secretKey) || anyOptionsUsed;
  74550. anyOptionsUsed = resolvedConfig.setCloudProfile(config.cloudProfile ?? null, sources.cloudProfile) || anyOptionsUsed;
  74551. anyOptionsUsed = resolvedConfig.setTlsCAData(config.tlsCA ?? null, sources.tlsCA) || anyOptionsUsed;
  74552. anyOptionsUsed = await resolvedConfig.setTlsCAFile(config.tlsCAFile ?? null, sources.tlsCAFile, readFile2) || anyOptionsUsed;
  74553. anyOptionsUsed = resolvedConfig.setTlsServerName(config.tlsServerName ?? null, sources.tlsServerName) || anyOptionsUsed;
  74554. anyOptionsUsed = resolvedConfig.setTlsSecurity(config.tlsSecurity ?? null, sources.tlsSecurity) || anyOptionsUsed;
  74555. anyOptionsUsed = resolvedConfig.setWaitUntilAvailable(config.waitUntilAvailable ?? null, sources.waitUntilAvailable) || anyOptionsUsed;
  74556. resolvedConfig.addServerSettings(config.serverSettings ?? {});
  74557. const compoundParamsCount = [
  74558. config.dsn,
  74559. config.instanceName,
  74560. config.credentials,
  74561. config.credentialsFile,
  74562. config.host ?? config.port
  74563. ].filter((param) => param !== void 0).length;
  74564. if (compoundParamsCount > 1) {
  74565. throw new errors_1.InterfaceError(compoundParamsError);
  74566. }
  74567. if (compoundParamsCount === 1) {
  74568. if (config.dsn !== void 0 || config.host !== void 0 || config.port !== void 0) {
  74569. let dsn = config.dsn;
  74570. if (dsn === void 0) {
  74571. if (config.port !== void 0) {
  74572. resolvedConfig.setPort(config.port, sources.port);
  74573. }
  74574. const host = config.host != null ? validateHost(config.host) : "";
  74575. dsn = `edgedb://${host.includes(":") ? `[${encodeURI(host)}]` : host}`;
  74576. }
  74577. await parseDSNIntoConfig(dsn, resolvedConfig, config.dsn ? sources.dsn : config.host !== void 0 ? sources.host : sources.port, readFile2);
  74578. } else {
  74579. let creds;
  74580. let source;
  74581. if (config.credentials != null) {
  74582. creds = (0, credentials_1.validateCredentials)(JSON.parse(config.credentials));
  74583. source = sources.credentials;
  74584. } else {
  74585. if (!serverUtils && !((_a2 = config.instanceName) == null ? void 0 : _a2.includes("/"))) {
  74586. throw new errors_1.InterfaceError(`cannot ${config.credentialsFile ? `read credentials file "${config.credentialsFile}"` : `resolve instance name "${config.instanceName}"`} in browser (or edge runtime) environment`);
  74587. }
  74588. let credentialsFile = config.credentialsFile;
  74589. if (credentialsFile === void 0) {
  74590. if (/^\w(-?\w)*$/.test(config.instanceName)) {
  74591. credentialsFile = await (0, credentials_1.getCredentialsPath)(config.instanceName, serverUtils);
  74592. source = sources.instanceName;
  74593. } else {
  74594. if (!/^([A-Za-z0-9_-](-?[A-Za-z0-9_])*)\/([A-Za-z0-9](-?[A-Za-z0-9])*)$/.test(config.instanceName)) {
  74595. throw new errors_1.InterfaceError(`invalid DSN or instance name: '${config.instanceName}'`);
  74596. }
  74597. await parseCloudInstanceNameIntoConfig(resolvedConfig, config.instanceName, sources.instanceName, serverUtils);
  74598. return { hasCompoundOptions: true, anyOptionsUsed: true };
  74599. }
  74600. } else {
  74601. source = sources.credentialsFile;
  74602. }
  74603. creds = await (0, credentials_1.readCredentialsFile)(credentialsFile, serverUtils);
  74604. }
  74605. resolvedConfig.setHost(creds.host ?? null, source);
  74606. resolvedConfig.setPort(creds.port ?? null, source);
  74607. if (creds.database != null) {
  74608. if (resolvedConfig._branch == null) {
  74609. resolvedConfig.setDatabase(creds.database ?? null, source);
  74610. }
  74611. } else if (creds.branch != null) {
  74612. if (resolvedConfig._database == null) {
  74613. resolvedConfig.setBranch(creds.branch ?? null, source);
  74614. }
  74615. }
  74616. resolvedConfig.setUser(creds.user ?? null, source);
  74617. resolvedConfig.setPassword(creds.password ?? null, source);
  74618. resolvedConfig.setTlsCAData(creds.tlsCAData ?? null, source);
  74619. resolvedConfig.setTlsSecurity(creds.tlsSecurity ?? null, source);
  74620. }
  74621. return { hasCompoundOptions: true, anyOptionsUsed: true };
  74622. }
  74623. return { hasCompoundOptions: false, anyOptionsUsed };
  74624. }
  74625. async function parseDSNIntoConfig(_dsnString, config, source, readFile2) {
  74626. let dsnString = _dsnString;
  74627. let regexHostname = null;
  74628. let zoneId = "";
  74629. const regexResult = /\[(.*?)(%25.+?)\]/.exec(_dsnString);
  74630. if (regexResult) {
  74631. regexHostname = regexResult[1];
  74632. zoneId = decodeURI(regexResult[2]);
  74633. dsnString = dsnString.slice(0, regexResult.index + regexHostname.length + 1) + dsnString.slice(regexResult.index + regexHostname.length + regexResult[2].length + 1);
  74634. }
  74635. let parsed;
  74636. try {
  74637. parsed = new URL(dsnString);
  74638. if (regexHostname !== null && parsed.hostname !== `[${regexHostname}]`) {
  74639. throw new Error();
  74640. }
  74641. } catch (_3) {
  74642. throw new errors_1.InterfaceError(`invalid DSN or instance name: '${_dsnString}'`);
  74643. }
  74644. if (parsed.protocol !== "edgedb:" && parsed.protocol !== "gel:") {
  74645. throw new errors_1.InterfaceError(`invalid DSN: scheme is expected to be 'gel', got '${parsed.protocol.slice(0, -1)}'`);
  74646. }
  74647. const searchParams = /* @__PURE__ */ new Map();
  74648. for (const [key, value] of parsed.searchParams) {
  74649. if (searchParams.has(key)) {
  74650. throw new errors_1.InterfaceError(`invalid DSN: duplicate query parameter '${key}'`);
  74651. }
  74652. searchParams.set(key, value);
  74653. }
  74654. async function handleDSNPart(paramName, value, currentValue, setter, formatter = (val2) => val2) {
  74655. if ([
  74656. value || null,
  74657. searchParams.get(paramName),
  74658. searchParams.get(`${paramName}_env`),
  74659. searchParams.get(`${paramName}_file`)
  74660. ].filter((param) => param != null).length > 1) {
  74661. throw new errors_1.InterfaceError(`invalid DSN: more than one of ${value !== null ? `'${paramName}', ` : ""}'?${paramName}=', '?${paramName}_env=' or '?${paramName}_file=' was specified ${dsnString}`);
  74662. }
  74663. if (currentValue === null) {
  74664. let param = value || (searchParams.get(paramName) ?? null);
  74665. let paramSource = source;
  74666. if (param === null) {
  74667. const env3 = searchParams.get(`${paramName}_env`);
  74668. if (env3 != null) {
  74669. param = getEnv(env3, true) ?? null;
  74670. if (param === null) {
  74671. throw new errors_1.InterfaceError(`'${paramName}_env' environment variable '${env3}' doesn't exist`);
  74672. }
  74673. paramSource += ` (${paramName}_env: ${env3})`;
  74674. }
  74675. }
  74676. if (param === null) {
  74677. const file = searchParams.get(`${paramName}_file`);
  74678. if (file != null) {
  74679. param = await readFile2(file);
  74680. paramSource += ` (${paramName}_file: ${file})`;
  74681. }
  74682. }
  74683. param = param !== null ? formatter(param) : null;
  74684. await setter(param, paramSource);
  74685. }
  74686. searchParams.delete(paramName);
  74687. searchParams.delete(`${paramName}_env`);
  74688. searchParams.delete(`${paramName}_file`);
  74689. }
  74690. const hostname = /^\[.*\]$/.test(parsed.hostname) ? parsed.hostname.slice(1, -1) + zoneId : parsed.hostname;
  74691. await handleDSNPart("host", hostname, config._host, config.setHost);
  74692. await handleDSNPart("port", parsed.port, config._port, config.setPort);
  74693. const stripLeadingSlash = (str) => str.replace(/^\//, "");
  74694. const searchParamsContainsDatabase = searchParams.has("database") || searchParams.has("database_env") || searchParams.has("database_file");
  74695. const searchParamsContainsBranch = searchParams.has("branch") || searchParams.has("branch_env") || searchParams.has("branch_file");
  74696. if (searchParamsContainsBranch) {
  74697. if (searchParamsContainsDatabase) {
  74698. throw new errors_1.InterfaceError(`invalid DSN: cannot specify both 'database' and 'branch'`);
  74699. }
  74700. if (config._database === null) {
  74701. await handleDSNPart("branch", stripLeadingSlash(parsed.pathname), config._branch, config.setBranch, stripLeadingSlash);
  74702. } else {
  74703. searchParams.delete("branch");
  74704. searchParams.delete("branch_env");
  74705. searchParams.delete("branch_file");
  74706. }
  74707. } else {
  74708. if (config._branch === null) {
  74709. await handleDSNPart("database", stripLeadingSlash(parsed.pathname), config._database, config.setDatabase, stripLeadingSlash);
  74710. } else {
  74711. searchParams.delete("database");
  74712. searchParams.delete("database_env");
  74713. searchParams.delete("database_file");
  74714. }
  74715. }
  74716. await handleDSNPart("user", parsed.username, config._user, config.setUser);
  74717. await handleDSNPart("password", parsed.password, config._password, config.setPassword);
  74718. await handleDSNPart("secret_key", null, config._secretKey, config.setSecretKey);
  74719. await handleDSNPart("tls_ca", null, config._tlsCAData, config.setTlsCAData);
  74720. await handleDSNPart("tls_ca_file", null, config._tlsCAData, (val2, _source) => config.setTlsCAFile(val2, _source, readFile2));
  74721. await handleDSNPart("tls_server_name", null, config._tlsServerName, config.setTlsServerName);
  74722. await handleDSNPart("tls_security", null, config._tlsSecurity, config.setTlsSecurity);
  74723. await handleDSNPart("wait_until_available", null, config._waitUntilAvailable, config.setWaitUntilAvailable);
  74724. const serverSettings = {};
  74725. for (const [key, value] of searchParams) {
  74726. serverSettings[key] = value;
  74727. }
  74728. config.addServerSettings(serverSettings);
  74729. }
  74730. async function parseCloudInstanceNameIntoConfig(config, cloudInstanceName, source, serverUtils) {
  74731. const normInstanceName = cloudInstanceName.toLowerCase();
  74732. const [org, instanceName] = normInstanceName.split("/");
  74733. const domainName = `${instanceName}--${org}`;
  74734. if (domainName.length > DOMAIN_NAME_MAX_LEN) {
  74735. throw new errors_1.InterfaceError(`invalid instance name: cloud instance name length cannot exceed ${DOMAIN_NAME_MAX_LEN - 1} characters: ${cloudInstanceName}`);
  74736. }
  74737. let secretKey = config.secretKey;
  74738. if (secretKey == null) {
  74739. try {
  74740. if (!serverUtils) {
  74741. throw new errors_1.InterfaceError(`Cannot get secret key from cloud profile in browser (or edge runtime) environment`);
  74742. }
  74743. const profile = config.cloudProfile;
  74744. const profilePath = await serverUtils.searchConfigDir("cloud-credentials", `${profile}.json`);
  74745. const fileData = await serverUtils.readFileUtf8(profilePath);
  74746. secretKey = JSON.parse(fileData)["secret_key"];
  74747. if (!secretKey) {
  74748. throw new errors_1.InterfaceError(`Cloud profile '${profile}' doesn't contain a secret key`);
  74749. }
  74750. config.setSecretKey(secretKey, `cloud-credentials/${profile}.json`);
  74751. } catch (e4) {
  74752. throw new errors_1.InterfaceError(`Cannot connect to cloud instances without a secret key: ${e4}`);
  74753. }
  74754. }
  74755. try {
  74756. const keyParts = secretKey.split(".");
  74757. if (keyParts.length < 2) {
  74758. throw new errors_1.InterfaceError("Invalid secret key: does not contain payload");
  74759. }
  74760. const dnsZone = _jwtBase64Decode(keyParts[1])["iss"];
  74761. if (!dnsZone) {
  74762. throw new errors_1.InterfaceError("Invalid secret key: payload does not contain 'iss' value");
  74763. }
  74764. const dnsBucket = ((0, crcHqx_1.crcHqx)(buffer_1.utf8Encoder.encode(normInstanceName), 0) % 100).toString(10).padStart(2, "0");
  74765. const host = `${domainName}.c-${dnsBucket}.i.${dnsZone}`;
  74766. config.setHost(host, `resolved from 'secretKey' and ${source}`);
  74767. } catch (e4) {
  74768. if (e4 instanceof errors.GelError) {
  74769. throw e4;
  74770. } else {
  74771. throw new errors_1.InterfaceError(`Invalid secret key: ${e4}`);
  74772. }
  74773. }
  74774. }
  74775. function _jwtBase64Decode(payload) {
  74776. return JSON.parse(buffer_1.utf8Decoder.decode((0, buffer_1.decodeB64)(payload.padEnd(Math.ceil(payload.length / 4) * 4, "="))));
  74777. }
  74778. }
  74779. });
  74780. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.server.js
  74781. var require_conUtils_server = __commonJS({
  74782. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/conUtils.server.js"(exports2) {
  74783. "use strict";
  74784. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  74785. if (k22 === void 0) k22 = k3;
  74786. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  74787. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  74788. desc = { enumerable: true, get: function() {
  74789. return m4[k3];
  74790. } };
  74791. }
  74792. Object.defineProperty(o3, k22, desc);
  74793. } : function(o3, m4, k3, k22) {
  74794. if (k22 === void 0) k22 = k3;
  74795. o3[k22] = m4[k3];
  74796. });
  74797. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  74798. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  74799. } : function(o3, v6) {
  74800. o3["default"] = v6;
  74801. });
  74802. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  74803. if (mod && mod.__esModule) return mod;
  74804. var result = {};
  74805. if (mod != null) {
  74806. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  74807. }
  74808. __setModuleDefault2(result, mod);
  74809. return result;
  74810. };
  74811. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  74812. return mod && mod.__esModule ? mod : { "default": mod };
  74813. };
  74814. Object.defineProperty(exports2, "__esModule", { value: true });
  74815. exports2.parseConnectArguments = exports2.serverUtils = void 0;
  74816. exports2.findStashPath = findStashPath;
  74817. var platform = __importStar2(require_platform());
  74818. var node_fs_1 = require("node:fs");
  74819. var node_path_1 = __importDefault2(require("node:path"));
  74820. var systemUtils_1 = require_systemUtils();
  74821. var conUtils_1 = require_conUtils();
  74822. var projectDirCache = /* @__PURE__ */ new Map();
  74823. async function findProjectDir(required = true) {
  74824. if (!required && !(0, systemUtils_1.hasFSReadPermission)()) {
  74825. return null;
  74826. }
  74827. const workingDir = process.cwd();
  74828. if (projectDirCache.has(workingDir)) {
  74829. return projectDirCache.get(workingDir);
  74830. }
  74831. let dir = workingDir;
  74832. const cwdDev = (await node_fs_1.promises.stat(dir)).dev;
  74833. while (true) {
  74834. if (await (0, systemUtils_1.exists)(node_path_1.default.join(dir, "edgedb.toml")) || await (0, systemUtils_1.exists)(node_path_1.default.join(dir, "gel.toml"))) {
  74835. projectDirCache.set(workingDir, dir);
  74836. return dir;
  74837. }
  74838. const parentDir = node_path_1.default.join(dir, "..");
  74839. if (parentDir === dir || (await node_fs_1.promises.stat(parentDir)).dev !== cwdDev) {
  74840. projectDirCache.set(workingDir, null);
  74841. return null;
  74842. }
  74843. dir = parentDir;
  74844. }
  74845. }
  74846. async function findStashPath(projectDir) {
  74847. let projectPath = await node_fs_1.promises.realpath(projectDir);
  74848. if (platform.isWindows && !projectPath.startsWith("\\\\")) {
  74849. projectPath = "\\\\?\\" + projectPath;
  74850. }
  74851. const hash = (0, systemUtils_1.hashSHA1toHex)(projectPath);
  74852. const baseName = node_path_1.default.basename(projectPath);
  74853. const dirName = baseName + "-" + hash;
  74854. return platform.searchConfigDir("projects", dirName);
  74855. }
  74856. exports2.serverUtils = {
  74857. findProjectDir,
  74858. findStashPath,
  74859. readFileUtf8: systemUtils_1.readFileUtf8,
  74860. searchConfigDir: platform.searchConfigDir
  74861. };
  74862. exports2.parseConnectArguments = (0, conUtils_1.getConnectArgumentsParser)(exports2.serverUtils);
  74863. }
  74864. });
  74865. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/map.js
  74866. var require_map = __commonJS({
  74867. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/map.js"(exports2) {
  74868. "use strict";
  74869. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  74870. if (k22 === void 0) k22 = k3;
  74871. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  74872. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  74873. desc = { enumerable: true, get: function() {
  74874. return m4[k3];
  74875. } };
  74876. }
  74877. Object.defineProperty(o3, k22, desc);
  74878. } : function(o3, m4, k3, k22) {
  74879. if (k22 === void 0) k22 = k3;
  74880. o3[k22] = m4[k3];
  74881. });
  74882. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  74883. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  74884. } : function(o3, v6) {
  74885. o3["default"] = v6;
  74886. });
  74887. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  74888. if (mod && mod.__esModule) return mod;
  74889. var result = {};
  74890. if (mod != null) {
  74891. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  74892. }
  74893. __setModuleDefault2(result, mod);
  74894. return result;
  74895. };
  74896. Object.defineProperty(exports2, "__esModule", { value: true });
  74897. exports2.errorMapping = void 0;
  74898. var errors = __importStar2(require_errors());
  74899. exports2.errorMapping = /* @__PURE__ */ new Map();
  74900. exports2.errorMapping.set(16777216, errors.InternalServerError);
  74901. exports2.errorMapping.set(33554432, errors.UnsupportedFeatureError);
  74902. exports2.errorMapping.set(50331648, errors.ProtocolError);
  74903. exports2.errorMapping.set(50397184, errors.BinaryProtocolError);
  74904. exports2.errorMapping.set(50397185, errors.UnsupportedProtocolVersionError);
  74905. exports2.errorMapping.set(50397186, errors.TypeSpecNotFoundError);
  74906. exports2.errorMapping.set(50397187, errors.UnexpectedMessageError);
  74907. exports2.errorMapping.set(50462720, errors.InputDataError);
  74908. exports2.errorMapping.set(50462976, errors.ParameterTypeMismatchError);
  74909. exports2.errorMapping.set(50463232, errors.StateMismatchError);
  74910. exports2.errorMapping.set(50528256, errors.ResultCardinalityMismatchError);
  74911. exports2.errorMapping.set(50593792, errors.CapabilityError);
  74912. exports2.errorMapping.set(50594048, errors.UnsupportedCapabilityError);
  74913. exports2.errorMapping.set(50594304, errors.DisabledCapabilityError);
  74914. exports2.errorMapping.set(50594560, errors.UnsafeIsolationLevelError);
  74915. exports2.errorMapping.set(67108864, errors.QueryError);
  74916. exports2.errorMapping.set(67174400, errors.InvalidSyntaxError);
  74917. exports2.errorMapping.set(67174656, errors.EdgeQLSyntaxError);
  74918. exports2.errorMapping.set(67174912, errors.SchemaSyntaxError);
  74919. exports2.errorMapping.set(67175168, errors.GraphQLSyntaxError);
  74920. exports2.errorMapping.set(67239936, errors.InvalidTypeError);
  74921. exports2.errorMapping.set(67240192, errors.InvalidTargetError);
  74922. exports2.errorMapping.set(67240193, errors.InvalidLinkTargetError);
  74923. exports2.errorMapping.set(67240194, errors.InvalidPropertyTargetError);
  74924. exports2.errorMapping.set(67305472, errors.InvalidReferenceError);
  74925. exports2.errorMapping.set(67305473, errors.UnknownModuleError);
  74926. exports2.errorMapping.set(67305474, errors.UnknownLinkError);
  74927. exports2.errorMapping.set(67305475, errors.UnknownPropertyError);
  74928. exports2.errorMapping.set(67305476, errors.UnknownUserError);
  74929. exports2.errorMapping.set(67305477, errors.UnknownDatabaseError);
  74930. exports2.errorMapping.set(67305478, errors.UnknownParameterError);
  74931. exports2.errorMapping.set(67305479, errors.DeprecatedScopingError);
  74932. exports2.errorMapping.set(67371008, errors.SchemaError);
  74933. exports2.errorMapping.set(67436544, errors.SchemaDefinitionError);
  74934. exports2.errorMapping.set(67436800, errors.InvalidDefinitionError);
  74935. exports2.errorMapping.set(67436801, errors.InvalidModuleDefinitionError);
  74936. exports2.errorMapping.set(67436802, errors.InvalidLinkDefinitionError);
  74937. exports2.errorMapping.set(67436803, errors.InvalidPropertyDefinitionError);
  74938. exports2.errorMapping.set(67436804, errors.InvalidUserDefinitionError);
  74939. exports2.errorMapping.set(67436805, errors.InvalidDatabaseDefinitionError);
  74940. exports2.errorMapping.set(67436806, errors.InvalidOperatorDefinitionError);
  74941. exports2.errorMapping.set(67436807, errors.InvalidAliasDefinitionError);
  74942. exports2.errorMapping.set(67436808, errors.InvalidFunctionDefinitionError);
  74943. exports2.errorMapping.set(67436809, errors.InvalidConstraintDefinitionError);
  74944. exports2.errorMapping.set(67436810, errors.InvalidCastDefinitionError);
  74945. exports2.errorMapping.set(67437056, errors.DuplicateDefinitionError);
  74946. exports2.errorMapping.set(67437057, errors.DuplicateModuleDefinitionError);
  74947. exports2.errorMapping.set(67437058, errors.DuplicateLinkDefinitionError);
  74948. exports2.errorMapping.set(67437059, errors.DuplicatePropertyDefinitionError);
  74949. exports2.errorMapping.set(67437060, errors.DuplicateUserDefinitionError);
  74950. exports2.errorMapping.set(67437061, errors.DuplicateDatabaseDefinitionError);
  74951. exports2.errorMapping.set(67437062, errors.DuplicateOperatorDefinitionError);
  74952. exports2.errorMapping.set(67437063, errors.DuplicateViewDefinitionError);
  74953. exports2.errorMapping.set(67437064, errors.DuplicateFunctionDefinitionError);
  74954. exports2.errorMapping.set(67437065, errors.DuplicateConstraintDefinitionError);
  74955. exports2.errorMapping.set(67437066, errors.DuplicateCastDefinitionError);
  74956. exports2.errorMapping.set(67437067, errors.DuplicateMigrationError);
  74957. exports2.errorMapping.set(67502080, errors.SessionTimeoutError);
  74958. exports2.errorMapping.set(67502336, errors.IdleSessionTimeoutError);
  74959. exports2.errorMapping.set(67502592, errors.QueryTimeoutError);
  74960. exports2.errorMapping.set(67504640, errors.TransactionTimeoutError);
  74961. exports2.errorMapping.set(67504641, errors.IdleTransactionTimeoutError);
  74962. exports2.errorMapping.set(83886080, errors.ExecutionError);
  74963. exports2.errorMapping.set(83951616, errors.InvalidValueError);
  74964. exports2.errorMapping.set(83951617, errors.DivisionByZeroError);
  74965. exports2.errorMapping.set(83951618, errors.NumericOutOfRangeError);
  74966. exports2.errorMapping.set(83951619, errors.AccessPolicyError);
  74967. exports2.errorMapping.set(83951620, errors.QueryAssertionError);
  74968. exports2.errorMapping.set(84017152, errors.IntegrityError);
  74969. exports2.errorMapping.set(84017153, errors.ConstraintViolationError);
  74970. exports2.errorMapping.set(84017154, errors.CardinalityViolationError);
  74971. exports2.errorMapping.set(84017155, errors.MissingRequiredError);
  74972. exports2.errorMapping.set(84082688, errors.TransactionError);
  74973. exports2.errorMapping.set(84082944, errors.TransactionConflictError);
  74974. exports2.errorMapping.set(84082945, errors.TransactionSerializationError);
  74975. exports2.errorMapping.set(84082946, errors.TransactionDeadlockError);
  74976. exports2.errorMapping.set(84148224, errors.WatchError);
  74977. exports2.errorMapping.set(100663296, errors.ConfigurationError);
  74978. exports2.errorMapping.set(117440512, errors.AccessError);
  74979. exports2.errorMapping.set(117506048, errors.AuthenticationError);
  74980. exports2.errorMapping.set(134217728, errors.AvailabilityError);
  74981. exports2.errorMapping.set(134217729, errors.BackendUnavailableError);
  74982. exports2.errorMapping.set(134217730, errors.ServerOfflineError);
  74983. exports2.errorMapping.set(134217731, errors.UnknownTenantError);
  74984. exports2.errorMapping.set(134217732, errors.ServerBlockedError);
  74985. exports2.errorMapping.set(150994944, errors.BackendError);
  74986. exports2.errorMapping.set(150995200, errors.UnsupportedBackendFeatureError);
  74987. exports2.errorMapping.set(4026531840, errors.LogMessage);
  74988. exports2.errorMapping.set(4026597376, errors.WarningMessage);
  74989. exports2.errorMapping.set(4026662912, errors.StatusMessage);
  74990. exports2.errorMapping.set(4026662913, errors.MigrationStatusMessage);
  74991. exports2.errorMapping.set(4278190080, errors.ClientError);
  74992. exports2.errorMapping.set(4278255616, errors.ClientConnectionError);
  74993. exports2.errorMapping.set(4278255872, errors.ClientConnectionFailedError);
  74994. exports2.errorMapping.set(4278255873, errors.ClientConnectionFailedTemporarilyError);
  74995. exports2.errorMapping.set(4278256128, errors.ClientConnectionTimeoutError);
  74996. exports2.errorMapping.set(4278256384, errors.ClientConnectionClosedError);
  74997. exports2.errorMapping.set(4278321152, errors.InterfaceError);
  74998. exports2.errorMapping.set(4278321408, errors.QueryArgumentError);
  74999. exports2.errorMapping.set(4278321409, errors.MissingArgumentError);
  75000. exports2.errorMapping.set(4278321410, errors.UnknownArgumentError);
  75001. exports2.errorMapping.set(4278321411, errors.InvalidArgumentError);
  75002. exports2.errorMapping.set(4278386688, errors.NoDataError);
  75003. exports2.errorMapping.set(4278452224, errors.InternalClientError);
  75004. }
  75005. });
  75006. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/resolve.js
  75007. var require_resolve = __commonJS({
  75008. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/errors/resolve.js"(exports2) {
  75009. "use strict";
  75010. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  75011. if (k22 === void 0) k22 = k3;
  75012. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  75013. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  75014. desc = { enumerable: true, get: function() {
  75015. return m4[k3];
  75016. } };
  75017. }
  75018. Object.defineProperty(o3, k22, desc);
  75019. } : function(o3, m4, k3, k22) {
  75020. if (k22 === void 0) k22 = k3;
  75021. o3[k22] = m4[k3];
  75022. });
  75023. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  75024. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  75025. } : function(o3, v6) {
  75026. o3["default"] = v6;
  75027. });
  75028. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  75029. if (mod && mod.__esModule) return mod;
  75030. var result = {};
  75031. if (mod != null) {
  75032. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  75033. }
  75034. __setModuleDefault2(result, mod);
  75035. return result;
  75036. };
  75037. Object.defineProperty(exports2, "__esModule", { value: true });
  75038. exports2.resolveErrorCode = resolveErrorCode;
  75039. exports2.errorFromJSON = errorFromJSON;
  75040. var errors = __importStar2(require_errors());
  75041. var base_1 = require_base();
  75042. var map_1 = require_map();
  75043. function resolveErrorCode(code) {
  75044. let result;
  75045. result = map_1.errorMapping.get(code);
  75046. if (result) {
  75047. return result;
  75048. }
  75049. code = code & 4294967040;
  75050. result = map_1.errorMapping.get(code);
  75051. if (result) {
  75052. return result;
  75053. }
  75054. code = code & 4294901760;
  75055. result = map_1.errorMapping.get(code);
  75056. if (result) {
  75057. return result;
  75058. }
  75059. code = code & 4278190080;
  75060. result = map_1.errorMapping.get(code);
  75061. if (result) {
  75062. return result;
  75063. }
  75064. return errors.GelError;
  75065. }
  75066. var _JSON_FIELDS = {
  75067. hint: base_1.ErrorAttr.hint,
  75068. details: base_1.ErrorAttr.details,
  75069. start: base_1.ErrorAttr.characterStart,
  75070. end: base_1.ErrorAttr.characterEnd,
  75071. line: base_1.ErrorAttr.lineStart,
  75072. col: base_1.ErrorAttr.columnStart
  75073. };
  75074. function errorFromJSON(data) {
  75075. const errType = resolveErrorCode(data.code);
  75076. const err2 = new errType(data.message);
  75077. const attrs = /* @__PURE__ */ new Map();
  75078. for (const [name, field] of Object.entries(_JSON_FIELDS)) {
  75079. if (data[name] != null) {
  75080. attrs.set(field, data[name]);
  75081. }
  75082. }
  75083. err2._attrs = attrs;
  75084. return err2;
  75085. }
  75086. }
  75087. });
  75088. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseConn.js
  75089. var require_baseConn = __commonJS({
  75090. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/baseConn.js"(exports2) {
  75091. "use strict";
  75092. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  75093. if (k22 === void 0) k22 = k3;
  75094. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  75095. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  75096. desc = { enumerable: true, get: function() {
  75097. return m4[k3];
  75098. } };
  75099. }
  75100. Object.defineProperty(o3, k22, desc);
  75101. } : function(o3, m4, k3, k22) {
  75102. if (k22 === void 0) k22 = k3;
  75103. o3[k22] = m4[k3];
  75104. });
  75105. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  75106. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  75107. } : function(o3, v6) {
  75108. o3["default"] = v6;
  75109. });
  75110. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  75111. if (mod && mod.__esModule) return mod;
  75112. var result = {};
  75113. if (mod != null) {
  75114. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  75115. }
  75116. __setModuleDefault2(result, mod);
  75117. return result;
  75118. };
  75119. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  75120. return mod && mod.__esModule ? mod : { "default": mod };
  75121. };
  75122. Object.defineProperty(exports2, "__esModule", { value: true });
  75123. exports2.BaseRawConnection = exports2.RESTRICTED_CAPABILITIES = exports2.Capabilities = exports2.PROTO_VER_MIN = exports2.PROTO_VER = void 0;
  75124. var codecs_1 = require_codecs();
  75125. var object_1 = require_object();
  75126. var utils_1 = require_utils2();
  75127. var errors = __importStar2(require_errors());
  75128. var resolve_1 = require_resolve();
  75129. var context_1 = require_context();
  75130. var ifaces_1 = require_ifaces2();
  75131. var buffer_1 = require_buffer();
  75132. var chars = __importStar2(require_chars());
  75133. var event_1 = __importDefault2(require_event());
  75134. var lru_1 = __importDefault2(require_lru());
  75135. var options_1 = require_options();
  75136. exports2.PROTO_VER = [3, 0];
  75137. exports2.PROTO_VER_MIN = [0, 9];
  75138. var TransactionStatus;
  75139. (function(TransactionStatus2) {
  75140. TransactionStatus2[TransactionStatus2["TRANS_IDLE"] = 0] = "TRANS_IDLE";
  75141. TransactionStatus2[TransactionStatus2["TRANS_ACTIVE"] = 1] = "TRANS_ACTIVE";
  75142. TransactionStatus2[TransactionStatus2["TRANS_INTRANS"] = 2] = "TRANS_INTRANS";
  75143. TransactionStatus2[TransactionStatus2["TRANS_INERROR"] = 3] = "TRANS_INERROR";
  75144. TransactionStatus2[TransactionStatus2["TRANS_UNKNOWN"] = 4] = "TRANS_UNKNOWN";
  75145. })(TransactionStatus || (TransactionStatus = {}));
  75146. var Capabilities;
  75147. (function(Capabilities2) {
  75148. Capabilities2[Capabilities2["NONE"] = 0] = "NONE";
  75149. Capabilities2[Capabilities2["MODIFICATONS"] = 1] = "MODIFICATONS";
  75150. Capabilities2[Capabilities2["SESSION_CONFIG"] = 2] = "SESSION_CONFIG";
  75151. Capabilities2[Capabilities2["TRANSACTION"] = 4] = "TRANSACTION";
  75152. Capabilities2[Capabilities2["DDL"] = 8] = "DDL";
  75153. Capabilities2[Capabilities2["PERSISTENT_CONFIG"] = 16] = "PERSISTENT_CONFIG";
  75154. Capabilities2[Capabilities2["SET_GLOBAL"] = 32] = "SET_GLOBAL";
  75155. Capabilities2[Capabilities2["ALL"] = 4294967295] = "ALL";
  75156. })(Capabilities || (exports2.Capabilities = Capabilities = {}));
  75157. var NO_TRANSACTION_CAPABILITIES = (Capabilities.ALL & ~Capabilities.TRANSACTION) >>> 0;
  75158. var NO_TRANSACTION_CAPABILITIES_BYTES = new Uint8Array(Array(8).fill(255));
  75159. new DataView(NO_TRANSACTION_CAPABILITIES_BYTES.buffer).setUint32(4, NO_TRANSACTION_CAPABILITIES);
  75160. exports2.RESTRICTED_CAPABILITIES = (Capabilities.ALL & ~Capabilities.TRANSACTION & ~Capabilities.SESSION_CONFIG & ~Capabilities.SET_GLOBAL) >>> 0;
  75161. var CompilationFlag;
  75162. (function(CompilationFlag2) {
  75163. CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_TYPE_IDS"] = 1] = "INJECT_OUTPUT_TYPE_IDS";
  75164. CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_TYPE_NAMES"] = 2] = "INJECT_OUTPUT_TYPE_NAMES";
  75165. CompilationFlag2[CompilationFlag2["INJECT_OUTPUT_OBJECT_IDS"] = 4] = "INJECT_OUTPUT_OBJECT_IDS";
  75166. })(CompilationFlag || (CompilationFlag = {}));
  75167. var OLD_ERROR_CODES = /* @__PURE__ */ new Map([
  75168. [84082689, 84082945],
  75169. [84082690, 84082946]
  75170. ]);
  75171. var BaseRawConnection = class {
  75172. connected = false;
  75173. lastStatus;
  75174. codecsRegistry;
  75175. queryCodecCache;
  75176. serverSecret;
  75177. serverSettings;
  75178. serverXactStatus;
  75179. buffer;
  75180. messageWaiter;
  75181. connWaiter;
  75182. connAbortWaiter;
  75183. _abortedWith = null;
  75184. protocolVersion = exports2.PROTO_VER;
  75185. stateCodec = codecs_1.INVALID_CODEC;
  75186. stateCache = /* @__PURE__ */ new WeakMap();
  75187. lastStateUpdate = null;
  75188. adminUIMode = false;
  75189. constructor(registry) {
  75190. this.buffer = new buffer_1.ReadMessageBuffer();
  75191. this.codecsRegistry = registry;
  75192. this.queryCodecCache = new lru_1.default({ capacity: 1e3 });
  75193. this.lastStatus = null;
  75194. this.serverSecret = null;
  75195. this.serverSettings = {};
  75196. this.serverXactStatus = TransactionStatus.TRANS_UNKNOWN;
  75197. this.messageWaiter = null;
  75198. this.connWaiter = new event_1.default();
  75199. this.connAbortWaiter = new event_1.default();
  75200. }
  75201. throwNotImplemented(method) {
  75202. throw new errors.InternalClientError(`method ${method} is not implemented`);
  75203. }
  75204. async _waitForMessage() {
  75205. this.throwNotImplemented("_waitForMessage");
  75206. }
  75207. _sendData(_data3) {
  75208. this.throwNotImplemented("_sendData");
  75209. }
  75210. getConnAbortError() {
  75211. return this._abortedWith ?? new errors.InterfaceError(`client has been closed`);
  75212. }
  75213. _checkState() {
  75214. if (this.isClosed()) {
  75215. throw this.getConnAbortError();
  75216. }
  75217. }
  75218. _abortWithError(err2) {
  75219. this._abortedWith = err2;
  75220. this._abort();
  75221. }
  75222. _ignoreHeaders() {
  75223. let numFields = this.buffer.readInt16();
  75224. while (numFields) {
  75225. this.buffer.readInt16();
  75226. this.buffer.readLenPrefixedBuffer();
  75227. numFields--;
  75228. }
  75229. }
  75230. _readHeaders() {
  75231. const numFields = this.buffer.readInt16();
  75232. const headers = {};
  75233. for (let i4 = 0; i4 < numFields; i4++) {
  75234. const key = this.buffer.readString();
  75235. const value = this.buffer.readString();
  75236. headers[key] = value;
  75237. }
  75238. return headers;
  75239. }
  75240. _abortWaiters(err2) {
  75241. var _a2;
  75242. if (!this.connWaiter.done) {
  75243. this.connWaiter.setError(err2);
  75244. }
  75245. (_a2 = this.messageWaiter) == null ? void 0 : _a2.setError(err2);
  75246. this.messageWaiter = null;
  75247. }
  75248. _parseHeaders() {
  75249. const ret = /* @__PURE__ */ new Map();
  75250. let numFields = this.buffer.readInt16();
  75251. while (numFields) {
  75252. const key = this.buffer.readInt16();
  75253. const value = this.buffer.readLenPrefixedBuffer();
  75254. ret.set(key, value);
  75255. numFields--;
  75256. }
  75257. return ret;
  75258. }
  75259. _parseDescribeTypeMessage(query) {
  75260. let capabilities = -1;
  75261. let warnings = [];
  75262. let unsafeIsolationDangers = [];
  75263. const headers = this._readHeaders();
  75264. if (headers.warnings != null) {
  75265. warnings = JSON.parse(headers.warnings).map((warning3) => {
  75266. const err2 = (0, resolve_1.errorFromJSON)(warning3);
  75267. err2._query = query;
  75268. return err2;
  75269. });
  75270. }
  75271. if (headers.unsafe_isolation_dangers != null) {
  75272. unsafeIsolationDangers = JSON.parse(headers.unsafe_isolation_dangers).map((danger) => {
  75273. const err2 = (0, resolve_1.errorFromJSON)(danger);
  75274. err2._query = query;
  75275. return err2;
  75276. });
  75277. }
  75278. capabilities = Number(this.buffer.readBigInt64());
  75279. const cardinality = this.buffer.readChar();
  75280. const inTypeId = this.buffer.readUUID();
  75281. const inTypeData = this.buffer.readLenPrefixedBuffer();
  75282. const outTypeId = this.buffer.readUUID();
  75283. const outTypeData = this.buffer.readLenPrefixedBuffer();
  75284. this.buffer.finishMessage();
  75285. let inCodec = this.codecsRegistry.getCodec(inTypeId);
  75286. if (inCodec == null) {
  75287. inCodec = this.codecsRegistry.buildCodec(inTypeData, this.protocolVersion);
  75288. }
  75289. let outCodec = this.codecsRegistry.getCodec(outTypeId);
  75290. if (outCodec == null) {
  75291. outCodec = this.codecsRegistry.buildCodec(outTypeData, this.protocolVersion);
  75292. }
  75293. return [
  75294. cardinality,
  75295. inCodec,
  75296. outCodec,
  75297. capabilities,
  75298. inTypeData,
  75299. outTypeData,
  75300. warnings,
  75301. unsafeIsolationDangers
  75302. ];
  75303. }
  75304. _parseCommandCompleteMessage() {
  75305. this._ignoreHeaders();
  75306. this.buffer.readBigInt64();
  75307. const status = this.buffer.readString();
  75308. const stateTypeId = this.buffer.readUUID();
  75309. const stateData = this.buffer.readLenPrefixedBuffer();
  75310. if (this.adminUIMode && stateTypeId === this.stateCodec.tid) {
  75311. this.lastStateUpdate = this.stateCodec.decode(new buffer_1.ReadBuffer(stateData), context_1.NOOP_CODEC_CONTEXT);
  75312. }
  75313. this.buffer.finishMessage();
  75314. return status;
  75315. }
  75316. _parseErrorMessage() {
  75317. this.buffer.readChar();
  75318. const code = this.buffer.readUInt32();
  75319. const message = this.buffer.readString();
  75320. const errorType = (0, resolve_1.resolveErrorCode)(OLD_ERROR_CODES.get(code) ?? code);
  75321. const err2 = new errorType(message);
  75322. err2._attrs = this._parseHeaders();
  75323. this.buffer.finishMessage();
  75324. if (err2 instanceof errors.AuthenticationError) {
  75325. throw err2;
  75326. }
  75327. return err2;
  75328. }
  75329. _parseSyncMessage() {
  75330. this._parseHeaders();
  75331. const status = this.buffer.readChar();
  75332. switch (status) {
  75333. case chars.$I:
  75334. this.serverXactStatus = TransactionStatus.TRANS_IDLE;
  75335. break;
  75336. case chars.$T:
  75337. this.serverXactStatus = TransactionStatus.TRANS_INTRANS;
  75338. break;
  75339. case chars.$E:
  75340. this.serverXactStatus = TransactionStatus.TRANS_INERROR;
  75341. break;
  75342. default:
  75343. this.serverXactStatus = TransactionStatus.TRANS_UNKNOWN;
  75344. }
  75345. this.buffer.finishMessage();
  75346. }
  75347. _redirectDataMessages(result) {
  75348. const $D = chars.$D;
  75349. const buffer = this.buffer;
  75350. while (buffer.takeMessageType($D)) {
  75351. const msg = buffer.consumeMessage();
  75352. result.writeChar($D);
  75353. result.writeInt32(msg.length + 4);
  75354. result.writeBuffer(msg);
  75355. }
  75356. }
  75357. _parseDataMessages(codec, result, ctx) {
  75358. const frb = buffer_1.ReadBuffer.alloc();
  75359. const $D = chars.$D;
  75360. const buffer = this.buffer;
  75361. if (Array.isArray(result)) {
  75362. while (buffer.takeMessageType($D)) {
  75363. buffer.consumeMessageInto(frb);
  75364. frb.discard(6);
  75365. result.push(codec.decode(frb, ctx));
  75366. frb.finish();
  75367. }
  75368. } else {
  75369. this._redirectDataMessages(result);
  75370. }
  75371. }
  75372. _parseServerSettings(name, value) {
  75373. switch (name) {
  75374. case "suggested_pool_concurrency": {
  75375. this.serverSettings.suggested_pool_concurrency = parseInt(buffer_1.utf8Decoder.decode(value), 10);
  75376. break;
  75377. }
  75378. case "system_config": {
  75379. const buf = new buffer_1.ReadBuffer(value);
  75380. const typedescLen = buf.readInt32() - 16;
  75381. const typedescId = buf.readUUID();
  75382. const typedesc = buf.readBuffer(typedescLen);
  75383. let codec = this.codecsRegistry.getCodec(typedescId);
  75384. if (codec === null) {
  75385. codec = this.codecsRegistry.buildCodec(typedesc, this.protocolVersion);
  75386. }
  75387. buf.discard(4);
  75388. const data = codec.decode(buf, context_1.NOOP_CODEC_CONTEXT);
  75389. buf.finish();
  75390. this.serverSettings.system_config = data;
  75391. break;
  75392. }
  75393. default:
  75394. this.serverSettings[name] = value;
  75395. break;
  75396. }
  75397. }
  75398. _parseDescribeStateMessage() {
  75399. const typedescId = this.buffer.readUUID();
  75400. const typedesc = this.buffer.readBuffer(this.buffer.readInt32());
  75401. let codec = this.codecsRegistry.getCodec(typedescId);
  75402. if (codec === null) {
  75403. codec = this.codecsRegistry.buildCodec(typedesc, this.protocolVersion);
  75404. }
  75405. this.stateCodec = codec;
  75406. this.stateCache = /* @__PURE__ */ new WeakMap();
  75407. this.buffer.finishMessage();
  75408. }
  75409. _fallthrough() {
  75410. const mtype = this.buffer.getMessageType();
  75411. switch (mtype) {
  75412. case chars.$S: {
  75413. const name = this.buffer.readString();
  75414. const value = this.buffer.readLenPrefixedBuffer();
  75415. this._parseServerSettings(name, value);
  75416. this.buffer.finishMessage();
  75417. break;
  75418. }
  75419. case chars.$L: {
  75420. const severity = this.buffer.readChar();
  75421. const code = this.buffer.readUInt32();
  75422. const message = this.buffer.readString();
  75423. this._parseHeaders();
  75424. this.buffer.finishMessage();
  75425. console.info("SERVER MESSAGE", severity, code, message);
  75426. break;
  75427. }
  75428. default:
  75429. throw new errors.UnexpectedMessageError(`unexpected message type ${mtype} ("${chars.chr(mtype)}")`);
  75430. }
  75431. }
  75432. _encodeArgs(args, inCodec, ctx) {
  75433. if (inCodec === codecs_1.NULL_CODEC) {
  75434. if (args != null) {
  75435. throw new errors.QueryArgumentError(`This query does not contain any query parameters, but query arguments were provided to the 'query*()' method`);
  75436. }
  75437. return codecs_1.NullCodec.BUFFER;
  75438. }
  75439. if (inCodec instanceof object_1.ObjectCodec) {
  75440. return inCodec.encodeArgs(args, ctx);
  75441. }
  75442. throw new errors.ProtocolError("invalid input codec");
  75443. }
  75444. _isInTransaction() {
  75445. return this.serverXactStatus === TransactionStatus.TRANS_INTRANS || this.serverXactStatus === TransactionStatus.TRANS_ACTIVE;
  75446. }
  75447. _setStateCodec(state2) {
  75448. let encodedState = this.stateCache.get(state2);
  75449. if (encodedState) {
  75450. return encodedState;
  75451. }
  75452. const buf = new buffer_1.WriteBuffer();
  75453. this.stateCodec.encode(buf, state2._serialise(), context_1.NOOP_CODEC_CONTEXT);
  75454. encodedState = buf.unwrap();
  75455. this.stateCache.set(state2, encodedState);
  75456. return encodedState;
  75457. }
  75458. _encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, isExecute, unsafeIsolationDangers) {
  75459. if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0])) {
  75460. if (state2.annotations.size >= 1 << 16) {
  75461. throw new errors.InternalClientError("too many annotations");
  75462. }
  75463. wb.writeUInt16(state2.annotations.size);
  75464. for (const [name, value] of state2.annotations) {
  75465. wb.writeString(name);
  75466. wb.writeString(value);
  75467. }
  75468. } else {
  75469. wb.writeUInt16(0);
  75470. }
  75471. wb.writeFlags(4294967295, capabilitiesFlags);
  75472. wb.writeFlags(0, 0 | ((options == null ? void 0 : options.injectObjectids) ? CompilationFlag.INJECT_OUTPUT_OBJECT_IDS : 0) | ((options == null ? void 0 : options.injectTypeids) ? CompilationFlag.INJECT_OUTPUT_TYPE_IDS : 0) | ((options == null ? void 0 : options.injectTypenames) ? CompilationFlag.INJECT_OUTPUT_TYPE_NAMES : 0));
  75473. wb.writeBigInt64((options == null ? void 0 : options.implicitLimit) ?? BigInt(0));
  75474. if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0])) {
  75475. wb.writeChar(language);
  75476. }
  75477. wb.writeChar(outputFormat);
  75478. wb.writeChar(expectedCardinality === ifaces_1.Cardinality.ONE || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE ? ifaces_1.Cardinality.AT_MOST_ONE : ifaces_1.Cardinality.MANY);
  75479. wb.writeString(query);
  75480. if (!this.adminUIMode && state2.isDefaultSession()) {
  75481. wb.writeBuffer(codecs_1.NULL_CODEC.tidBuffer);
  75482. wb.writeInt32(0);
  75483. } else {
  75484. wb.writeBuffer(this.stateCodec.tidBuffer);
  75485. if (this.stateCodec === codecs_1.INVALID_CODEC || this.stateCodec === codecs_1.NULL_CODEC) {
  75486. wb.writeInt32(0);
  75487. } else {
  75488. if ((0, utils_1.versionGreaterThanOrEqual)(this.protocolVersion, [3, 0]) && isExecute && !this._isInTransaction()) {
  75489. const isolation = state2.transactionOptions.isolation === options_1.IsolationLevel.PreferRepeatableRead ? unsafeIsolationDangers.length === 0 ? options_1.IsolationLevel.RepeatableRead : options_1.IsolationLevel.Serializable : state2.transactionOptions.isolation;
  75490. if (isolation !== state2.config.get("default_transaction_isolation")) {
  75491. state2 = state2.withConfig({
  75492. default_transaction_isolation: isolation
  75493. }).withTransactionOptions({
  75494. isolation
  75495. });
  75496. }
  75497. if (state2.transactionOptions.readonly !== state2.config.get("default_transaction_access_mode")) {
  75498. state2 = state2.withConfig({
  75499. default_transaction_access_mode: state2.transactionOptions.readonly ? "ReadOnly" : "ReadWrite"
  75500. });
  75501. }
  75502. }
  75503. const encodedState = this._setStateCodec(state2);
  75504. wb.writeBuffer(encodedState);
  75505. }
  75506. }
  75507. }
  75508. async _parse(language, query, outputFormat, expectedCardinality, state2, capabilitiesFlags = exports2.RESTRICTED_CAPABILITIES, options, unsafeIsolationDangers = []) {
  75509. const wb = new buffer_1.WriteMessageBuffer();
  75510. wb.beginMessage(chars.$P);
  75511. this._encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, false, unsafeIsolationDangers);
  75512. wb.endMessage();
  75513. wb.writeSync();
  75514. this._sendData(wb.unwrap());
  75515. let parsing = true;
  75516. let error2 = null;
  75517. let newCard = null;
  75518. let capabilities = -1;
  75519. let inCodec = null;
  75520. let outCodec = null;
  75521. let inCodecBuf = null;
  75522. let outCodecBuf = null;
  75523. let warnings = [];
  75524. while (parsing) {
  75525. if (!this.buffer.takeMessage()) {
  75526. await this._waitForMessage();
  75527. }
  75528. const mtype = this.buffer.getMessageType();
  75529. switch (mtype) {
  75530. case chars.$T: {
  75531. try {
  75532. [
  75533. newCard,
  75534. inCodec,
  75535. outCodec,
  75536. capabilities,
  75537. inCodecBuf,
  75538. outCodecBuf,
  75539. warnings,
  75540. unsafeIsolationDangers
  75541. ] = this._parseDescribeTypeMessage(query);
  75542. const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
  75543. this.queryCodecCache.set(key, [
  75544. newCard,
  75545. inCodec,
  75546. outCodec,
  75547. capabilities,
  75548. unsafeIsolationDangers
  75549. ]);
  75550. } catch (e4) {
  75551. error2 = e4;
  75552. }
  75553. break;
  75554. }
  75555. case chars.$E: {
  75556. error2 = this._parseErrorMessage();
  75557. error2._query = query;
  75558. break;
  75559. }
  75560. case chars.$s: {
  75561. options_1.Options.signalSchemaChange();
  75562. this._parseDescribeStateMessage();
  75563. break;
  75564. }
  75565. case chars.$Z: {
  75566. this._parseSyncMessage();
  75567. parsing = false;
  75568. break;
  75569. }
  75570. default:
  75571. this._fallthrough();
  75572. }
  75573. }
  75574. if (error2 !== null) {
  75575. if (error2 instanceof errors.StateMismatchError) {
  75576. return this._parse(language, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, unsafeIsolationDangers);
  75577. }
  75578. throw error2;
  75579. }
  75580. return [
  75581. newCard,
  75582. inCodec,
  75583. outCodec,
  75584. capabilities,
  75585. inCodecBuf,
  75586. outCodecBuf,
  75587. warnings,
  75588. unsafeIsolationDangers
  75589. ];
  75590. }
  75591. async _executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec, outCodec, result, capabilitiesFlags = exports2.RESTRICTED_CAPABILITIES, options, unsafeIsolationDangers = []) {
  75592. let currentUnsafeIsolationDangers = unsafeIsolationDangers;
  75593. let ctx = state2.makeCodecContext();
  75594. const wb = new buffer_1.WriteMessageBuffer();
  75595. wb.beginMessage(chars.$O);
  75596. this._encodeParseParams(wb, query, outputFormat, expectedCardinality, state2, capabilitiesFlags, options, language, true, currentUnsafeIsolationDangers);
  75597. wb.writeBuffer(inCodec.tidBuffer);
  75598. wb.writeBuffer(outCodec.tidBuffer);
  75599. if (inCodec) {
  75600. wb.writeBuffer(this._encodeArgs(args, inCodec, ctx));
  75601. } else {
  75602. wb.writeInt32(0);
  75603. }
  75604. wb.endMessage();
  75605. wb.writeSync();
  75606. this._sendData(wb.unwrap());
  75607. let error2 = null;
  75608. let parsing = true;
  75609. let currentWarnings = [];
  75610. while (parsing) {
  75611. if (!this.buffer.takeMessage()) {
  75612. await this._waitForMessage();
  75613. }
  75614. const mtype = this.buffer.getMessageType();
  75615. switch (mtype) {
  75616. case chars.$D: {
  75617. if (error2 == null) {
  75618. try {
  75619. this._parseDataMessages(outCodec, result, ctx);
  75620. } catch (e4) {
  75621. error2 = e4;
  75622. this.buffer.finishMessage();
  75623. }
  75624. } else {
  75625. this.buffer.discardMessage();
  75626. }
  75627. break;
  75628. }
  75629. case chars.$C: {
  75630. this.lastStatus = this._parseCommandCompleteMessage();
  75631. break;
  75632. }
  75633. case chars.$Z: {
  75634. this._parseSyncMessage();
  75635. parsing = false;
  75636. break;
  75637. }
  75638. case chars.$T: {
  75639. try {
  75640. ctx = state2.makeCodecContext();
  75641. const [newCard, newInCodec, newOutCodec, capabilities, _3, __, _warnings, _dangers] = this._parseDescribeTypeMessage(query);
  75642. if (outCodec !== codecs_1.NULL_CODEC && outCodec.tid !== newOutCodec.tid || inCodec !== codecs_1.NULL_CODEC && inCodec.tid !== newInCodec.tid) {
  75643. options_1.Options.signalSchemaChange();
  75644. ctx = state2.makeCodecContext();
  75645. }
  75646. const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
  75647. this.queryCodecCache.set(key, [
  75648. newCard,
  75649. newInCodec,
  75650. newOutCodec,
  75651. capabilities,
  75652. _dangers
  75653. ]);
  75654. outCodec = newOutCodec;
  75655. currentWarnings = _warnings;
  75656. currentUnsafeIsolationDangers = _dangers;
  75657. } catch (e4) {
  75658. options_1.Options.signalSchemaChange();
  75659. error2 = e4;
  75660. }
  75661. break;
  75662. }
  75663. case chars.$s: {
  75664. options_1.Options.signalSchemaChange();
  75665. this._parseDescribeStateMessage();
  75666. break;
  75667. }
  75668. case chars.$E: {
  75669. error2 = this._parseErrorMessage();
  75670. error2._query = query;
  75671. break;
  75672. }
  75673. default:
  75674. this._fallthrough();
  75675. }
  75676. }
  75677. if (error2 != null) {
  75678. if (error2 instanceof errors.StateMismatchError) {
  75679. return this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec, outCodec, result, capabilitiesFlags, options, currentUnsafeIsolationDangers);
  75680. }
  75681. throw error2;
  75682. }
  75683. return [currentWarnings, currentUnsafeIsolationDangers];
  75684. }
  75685. _getQueryCacheKey(query, outputFormat, expectedCardinality, language = ifaces_1.Language.EDGEQL) {
  75686. const expectOne = expectedCardinality === ifaces_1.Cardinality.ONE || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE;
  75687. return [language, outputFormat, expectOne, query.length, query].join(";");
  75688. }
  75689. _validateFetchCardinality(card, outputFormat, expectedCardinality) {
  75690. if (expectedCardinality === ifaces_1.Cardinality.ONE && card === ifaces_1.Cardinality.NO_RESULT) {
  75691. throw new errors.NoDataError(`query executed via queryRequiredSingle${outputFormat === ifaces_1.OutputFormat.JSON ? "JSON" : ""}() returned no data`);
  75692. }
  75693. }
  75694. async fetch(query, args = null, outputFormat, expectedCardinality, state2, privilegedMode = false, language = ifaces_1.Language.EDGEQL) {
  75695. if (language !== ifaces_1.Language.EDGEQL && (0, utils_1.versionGreaterThan)([3, 0], this.protocolVersion)) {
  75696. throw new errors.UnsupportedFeatureError(`the server does not support SQL queries, upgrade to 6.0 or newer`);
  75697. }
  75698. this._checkState();
  75699. const requiredOne = expectedCardinality === ifaces_1.Cardinality.ONE;
  75700. const expectOne = requiredOne || expectedCardinality === ifaces_1.Cardinality.AT_MOST_ONE;
  75701. const asJson = outputFormat === ifaces_1.OutputFormat.JSON;
  75702. const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality, language);
  75703. const ret = [];
  75704. let warnings = [];
  75705. let [card, inCodec, outCodec, , unsafeIsolationDangers] = this.queryCodecCache.get(key) ?? [];
  75706. if (card) {
  75707. this._validateFetchCardinality(card, outputFormat, expectedCardinality);
  75708. }
  75709. if (!inCodec && args !== null || this.stateCodec === codecs_1.INVALID_CODEC && !state2.isDefaultSession()) {
  75710. [card, inCodec, outCodec, , , , warnings, unsafeIsolationDangers] = await this._parse(language, query, outputFormat, expectedCardinality, state2, privilegedMode ? Capabilities.ALL : void 0, void 0, unsafeIsolationDangers);
  75711. this._validateFetchCardinality(card, outputFormat, expectedCardinality);
  75712. }
  75713. try {
  75714. [warnings, unsafeIsolationDangers] = await this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, ret, privilegedMode ? Capabilities.ALL : void 0, void 0, unsafeIsolationDangers);
  75715. } catch (e4) {
  75716. if (e4 instanceof errors.ParameterTypeMismatchError) {
  75717. [card, inCodec, outCodec, , unsafeIsolationDangers] = this.queryCodecCache.get(key);
  75718. [warnings, unsafeIsolationDangers] = await this._executeFlow(language, query, args, outputFormat, expectedCardinality, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, ret, privilegedMode ? Capabilities.ALL : void 0);
  75719. } else {
  75720. throw e4;
  75721. }
  75722. }
  75723. if (outputFormat === ifaces_1.OutputFormat.NONE) {
  75724. return { result: null, warnings, unsafeIsolationDangers };
  75725. }
  75726. if (expectOne) {
  75727. if (requiredOne && !ret.length) {
  75728. throw new errors.NoDataError("query returned no data");
  75729. } else {
  75730. return {
  75731. result: ret[0] ?? (asJson ? "null" : null),
  75732. warnings,
  75733. unsafeIsolationDangers
  75734. };
  75735. }
  75736. } else {
  75737. if (ret && ret.length) {
  75738. if (asJson) {
  75739. return { result: ret[0], warnings, unsafeIsolationDangers };
  75740. } else {
  75741. return { result: ret, warnings, unsafeIsolationDangers };
  75742. }
  75743. } else {
  75744. if (asJson) {
  75745. return { result: "[]", warnings, unsafeIsolationDangers };
  75746. } else {
  75747. return { result: ret, warnings, unsafeIsolationDangers };
  75748. }
  75749. }
  75750. }
  75751. }
  75752. getQueryCapabilities(query, outputFormat, expectedCardinality) {
  75753. var _a2;
  75754. const key = this._getQueryCacheKey(query, outputFormat, expectedCardinality);
  75755. return ((_a2 = this.queryCodecCache.get(key)) == null ? void 0 : _a2[3]) ?? null;
  75756. }
  75757. async resetState() {
  75758. if (this.connected && this.serverXactStatus !== TransactionStatus.TRANS_IDLE) {
  75759. try {
  75760. await this.fetch(`rollback`, void 0, ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.NO_RESULT, options_1.Options.defaults(), true);
  75761. } catch {
  75762. this._abortWithError(new errors.ClientConnectionClosedError("failed to reset state"));
  75763. }
  75764. }
  75765. }
  75766. _abort() {
  75767. this.connected = false;
  75768. this._abortWaiters(this.getConnAbortError());
  75769. if (!this.connAbortWaiter.done) {
  75770. this.connAbortWaiter.set();
  75771. }
  75772. }
  75773. isClosed() {
  75774. return !this.connected;
  75775. }
  75776. async close() {
  75777. this._abort();
  75778. }
  75779. };
  75780. exports2.BaseRawConnection = BaseRawConnection;
  75781. }
  75782. });
  75783. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/scram.js
  75784. var require_scram = __commonJS({
  75785. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/scram.js"(exports2) {
  75786. "use strict";
  75787. Object.defineProperty(exports2, "__esModule", { value: true });
  75788. exports2.saslprep = saslprep;
  75789. exports2.getSCRAM = getSCRAM;
  75790. var buffer_1 = require_buffer();
  75791. var errors_1 = require_errors();
  75792. var RAW_NONCE_LENGTH = 18;
  75793. function saslprep(str) {
  75794. return str.normalize("NFKC");
  75795. }
  75796. function getSCRAM({ randomBytes, H: H2, HMAC, makeKey }) {
  75797. function bufferEquals(a3, b3) {
  75798. if (a3.length !== b3.length) {
  75799. return false;
  75800. }
  75801. for (let i4 = 0, len = a3.length; i4 < len; i4++) {
  75802. if (a3[i4] !== b3[i4]) {
  75803. return false;
  75804. }
  75805. }
  75806. return true;
  75807. }
  75808. function generateNonce(length = RAW_NONCE_LENGTH) {
  75809. return randomBytes(length);
  75810. }
  75811. function buildClientFirstMessage(clientNonce, username) {
  75812. const bare = `n=${saslprep(username)},r=${(0, buffer_1.encodeB64)(clientNonce)}`;
  75813. return [`n,,${bare}`, bare];
  75814. }
  75815. function parseServerFirstMessage(msg) {
  75816. const attrs = msg.split(",");
  75817. if (attrs.length < 3) {
  75818. throw new errors_1.ProtocolError("malformed SCRAM message");
  75819. }
  75820. const nonceAttr = attrs[0];
  75821. if (!nonceAttr || nonceAttr[0] !== "r") {
  75822. throw new errors_1.ProtocolError("malformed SCRAM message");
  75823. }
  75824. const nonceB64 = nonceAttr.split("=", 2)[1];
  75825. if (!nonceB64) {
  75826. throw new errors_1.ProtocolError("malformed SCRAM message");
  75827. }
  75828. const nonce = (0, buffer_1.decodeB64)(nonceB64);
  75829. const saltAttr = attrs[1];
  75830. if (!saltAttr || saltAttr[0] !== "s") {
  75831. throw new errors_1.ProtocolError("malformed SCRAM message");
  75832. }
  75833. const saltB64 = saltAttr.split("=", 2)[1];
  75834. if (!saltB64) {
  75835. throw new errors_1.ProtocolError("malformed SCRAM message");
  75836. }
  75837. const salt = (0, buffer_1.decodeB64)(saltB64);
  75838. const iterAttr = attrs[2];
  75839. if (!iterAttr || iterAttr[0] !== "i") {
  75840. throw new errors_1.ProtocolError("malformed SCRAM message");
  75841. }
  75842. const iter = iterAttr.split("=", 2)[1];
  75843. if (!iter || !iter.match(/^[0-9]*$/)) {
  75844. throw new errors_1.ProtocolError("malformed SCRAM message");
  75845. }
  75846. const iterCount = parseInt(iter, 10);
  75847. if (iterCount <= 0) {
  75848. throw new errors_1.ProtocolError("malformed SCRAM message");
  75849. }
  75850. return [nonce, salt, iterCount];
  75851. }
  75852. function parseServerFinalMessage(msg) {
  75853. const attrs = msg.split(",");
  75854. if (attrs.length < 1) {
  75855. throw new errors_1.ProtocolError("malformed SCRAM message");
  75856. }
  75857. const nonceAttr = attrs[0];
  75858. if (!nonceAttr || nonceAttr[0] !== "v") {
  75859. throw new errors_1.ProtocolError("malformed SCRAM message");
  75860. }
  75861. const signatureB64 = nonceAttr.split("=", 2)[1];
  75862. if (!signatureB64) {
  75863. throw new errors_1.ProtocolError("malformed SCRAM message");
  75864. }
  75865. return (0, buffer_1.decodeB64)(signatureB64);
  75866. }
  75867. async function buildClientFinalMessage(password, salt, iterations, clientFirstBare, serverFirst, serverNonce) {
  75868. const clientFinal = `c=biws,r=${(0, buffer_1.encodeB64)(serverNonce)}`;
  75869. const authMessage = buffer_1.utf8Encoder.encode(`${clientFirstBare},${serverFirst},${clientFinal}`);
  75870. const saltedPassword = await _getSaltedPassword(buffer_1.utf8Encoder.encode(saslprep(password)), salt, iterations);
  75871. const clientKey = await _getClientKey(saltedPassword);
  75872. const storedKey = await H2(clientKey);
  75873. const clientSignature = await HMAC(storedKey, authMessage);
  75874. const clientProof = _XOR(clientKey, clientSignature);
  75875. const serverKey = await _getServerKey(saltedPassword);
  75876. const serverProof = await HMAC(serverKey, authMessage);
  75877. return [`${clientFinal},p=${(0, buffer_1.encodeB64)(clientProof)}`, serverProof];
  75878. }
  75879. async function _getSaltedPassword(password, salt, iterations) {
  75880. const msg = new Uint8Array(salt.length + 4);
  75881. msg.set(salt);
  75882. msg.set([0, 0, 0, 1], salt.length);
  75883. const keyFromPassword = await makeKey(password);
  75884. let Hi = await HMAC(keyFromPassword, msg);
  75885. let Ui = Hi;
  75886. for (let _3 = 0; _3 < iterations - 1; _3++) {
  75887. Ui = await HMAC(keyFromPassword, Ui);
  75888. Hi = _XOR(Hi, Ui);
  75889. }
  75890. return Hi;
  75891. }
  75892. function _getClientKey(saltedPassword) {
  75893. return HMAC(saltedPassword, buffer_1.utf8Encoder.encode("Client Key"));
  75894. }
  75895. function _getServerKey(saltedPassword) {
  75896. return HMAC(saltedPassword, buffer_1.utf8Encoder.encode("Server Key"));
  75897. }
  75898. function _XOR(a3, b3) {
  75899. const len = a3.length;
  75900. if (len !== b3.length) {
  75901. throw new errors_1.ProtocolError("scram.XOR: buffers are of different lengths");
  75902. }
  75903. const res = new Uint8Array(len);
  75904. for (let i4 = 0; i4 < len; i4++) {
  75905. res[i4] = a3[i4] ^ b3[i4];
  75906. }
  75907. return res;
  75908. }
  75909. return {
  75910. bufferEquals,
  75911. generateNonce,
  75912. buildClientFirstMessage,
  75913. parseServerFirstMessage,
  75914. parseServerFinalMessage,
  75915. buildClientFinalMessage,
  75916. _getSaltedPassword,
  75917. _getClientKey,
  75918. _getServerKey,
  75919. _XOR
  75920. };
  75921. }
  75922. }
  75923. });
  75924. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/browserCrypto.js
  75925. var require_browserCrypto = __commonJS({
  75926. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/browserCrypto.js"(exports2) {
  75927. "use strict";
  75928. Object.defineProperty(exports2, "__esModule", { value: true });
  75929. exports2.cryptoUtils = void 0;
  75930. async function makeKey(key) {
  75931. return await crypto.subtle.importKey("raw", key, {
  75932. name: "HMAC",
  75933. hash: { name: "SHA-256" }
  75934. }, false, ["sign"]);
  75935. }
  75936. function randomBytes(size) {
  75937. return crypto.getRandomValues(new Uint8Array(size));
  75938. }
  75939. async function H2(msg) {
  75940. return new Uint8Array(await crypto.subtle.digest("SHA-256", msg));
  75941. }
  75942. async function HMAC(key, msg) {
  75943. const cryptoKey = key instanceof Uint8Array ? await makeKey(key) : key;
  75944. return new Uint8Array(await crypto.subtle.sign("HMAC", cryptoKey, msg));
  75945. }
  75946. exports2.cryptoUtils = {
  75947. makeKey,
  75948. randomBytes,
  75949. H: H2,
  75950. HMAC
  75951. };
  75952. }
  75953. });
  75954. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeCrypto.js
  75955. var require_nodeCrypto = __commonJS({
  75956. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeCrypto.js"(exports2) {
  75957. "use strict";
  75958. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  75959. return mod && mod.__esModule ? mod : { "default": mod };
  75960. };
  75961. Object.defineProperty(exports2, "__esModule", { value: true });
  75962. exports2.cryptoUtils = void 0;
  75963. var node_crypto_1 = __importDefault2(require("node:crypto"));
  75964. function makeKey(keyBytes) {
  75965. return Promise.resolve(keyBytes);
  75966. }
  75967. function randomBytes(size) {
  75968. return node_crypto_1.default.randomBytes(size);
  75969. }
  75970. async function H2(msg) {
  75971. const sign = node_crypto_1.default.createHash("sha256");
  75972. sign.update(msg);
  75973. return sign.digest();
  75974. }
  75975. async function HMAC(key, msg) {
  75976. const cryptoKey = key instanceof Uint8Array ? key : node_crypto_1.default.KeyObject.from(key);
  75977. const hm = node_crypto_1.default.createHmac("sha256", cryptoKey);
  75978. hm.update(msg);
  75979. return hm.digest();
  75980. }
  75981. exports2.cryptoUtils = {
  75982. makeKey,
  75983. randomBytes,
  75984. H: H2,
  75985. HMAC
  75986. };
  75987. }
  75988. });
  75989. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/cryptoUtils.js
  75990. var require_cryptoUtils = __commonJS({
  75991. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/cryptoUtils.js"(exports2) {
  75992. "use strict";
  75993. Object.defineProperty(exports2, "__esModule", { value: true });
  75994. var browserCrypto_1 = require_browserCrypto();
  75995. var isNode = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
  75996. var cryptoUtils;
  75997. function loadCrypto() {
  75998. if (isNode) {
  75999. try {
  76000. require("node:crypto");
  76001. cryptoUtils = require_nodeCrypto().cryptoUtils;
  76002. } catch (_3) {
  76003. if (typeof globalThis.crypto !== "undefined") {
  76004. cryptoUtils = browserCrypto_1.cryptoUtils;
  76005. } else {
  76006. throw new Error("No crypto implementation found");
  76007. }
  76008. }
  76009. } else {
  76010. cryptoUtils = browserCrypto_1.cryptoUtils;
  76011. }
  76012. }
  76013. loadCrypto();
  76014. exports2.default = cryptoUtils;
  76015. }
  76016. });
  76017. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/rawConn.js
  76018. var require_rawConn = __commonJS({
  76019. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/rawConn.js"(exports2) {
  76020. "use strict";
  76021. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  76022. if (k22 === void 0) k22 = k3;
  76023. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  76024. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  76025. desc = { enumerable: true, get: function() {
  76026. return m4[k3];
  76027. } };
  76028. }
  76029. Object.defineProperty(o3, k22, desc);
  76030. } : function(o3, m4, k3, k22) {
  76031. if (k22 === void 0) k22 = k3;
  76032. o3[k22] = m4[k3];
  76033. });
  76034. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  76035. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  76036. } : function(o3, v6) {
  76037. o3["default"] = v6;
  76038. });
  76039. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  76040. if (mod && mod.__esModule) return mod;
  76041. var result = {};
  76042. if (mod != null) {
  76043. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  76044. }
  76045. __setModuleDefault2(result, mod);
  76046. return result;
  76047. };
  76048. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  76049. return mod && mod.__esModule ? mod : { "default": mod };
  76050. };
  76051. Object.defineProperty(exports2, "__esModule", { value: true });
  76052. exports2.RawConnection = void 0;
  76053. var node_net_1 = __importDefault2(require("node:net"));
  76054. var tls = __importStar2(require("node:tls"));
  76055. var baseConn_1 = require_baseConn();
  76056. var utils_1 = require_utils2();
  76057. var buffer_1 = require_buffer();
  76058. var event_1 = __importDefault2(require_event());
  76059. var chars = __importStar2(require_chars());
  76060. var scram_1 = require_scram();
  76061. var errors = __importStar2(require_errors());
  76062. var cryptoUtils_1 = __importDefault2(require_cryptoUtils());
  76063. var AuthenticationStatuses;
  76064. (function(AuthenticationStatuses2) {
  76065. AuthenticationStatuses2[AuthenticationStatuses2["AUTH_OK"] = 0] = "AUTH_OK";
  76066. AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL"] = 10] = "AUTH_SASL";
  76067. AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL_CONTINUE"] = 11] = "AUTH_SASL_CONTINUE";
  76068. AuthenticationStatuses2[AuthenticationStatuses2["AUTH_SASL_FINAL"] = 12] = "AUTH_SASL_FINAL";
  76069. })(AuthenticationStatuses || (AuthenticationStatuses = {}));
  76070. var scram = (0, scram_1.getSCRAM)(cryptoUtils_1.default);
  76071. var _tlsOptions = /* @__PURE__ */ new WeakMap();
  76072. function getTlsOptions(config) {
  76073. if (_tlsOptions.has(config)) {
  76074. return _tlsOptions.get(config);
  76075. }
  76076. const tlsSecurity = config.tlsSecurity;
  76077. const tlsOptions = {
  76078. ALPNProtocols: ["edgedb-binary"],
  76079. rejectUnauthorized: tlsSecurity !== "insecure"
  76080. };
  76081. const isIPAddress = node_net_1.default.isIP(config.address[0]) !== 0;
  76082. if (!isIPAddress) {
  76083. tlsOptions.servername = config.tlsServerName || config.address[0];
  76084. }
  76085. _tlsOptions.set(config, tlsOptions);
  76086. if (config._tlsCAData !== null) {
  76087. tlsOptions.ca = config._tlsCAData;
  76088. }
  76089. if (tlsSecurity === "no_host_verification") {
  76090. tlsOptions.checkServerIdentity = (hostname, cert) => {
  76091. const err2 = tls.checkServerIdentity(hostname, cert);
  76092. if (err2 === void 0) {
  76093. return void 0;
  76094. }
  76095. if (err2.message.startsWith("Hostname/IP does not match certificate")) {
  76096. return void 0;
  76097. }
  76098. return err2;
  76099. };
  76100. }
  76101. return tlsOptions;
  76102. }
  76103. var RawConnection = class extends baseConn_1.BaseRawConnection {
  76104. config;
  76105. sock;
  76106. paused;
  76107. constructor(sock, config, registry) {
  76108. super(registry);
  76109. this.config = config;
  76110. this.paused = false;
  76111. this.sock = sock;
  76112. this.sock.setNoDelay();
  76113. this.sock.on("error", this._onError.bind(this));
  76114. this.sock.on("data", this._onData.bind(this));
  76115. if (tls.TLSSocket && this.sock instanceof tls.TLSSocket) {
  76116. this.sock.on("secureConnect", this._onConnect.bind(this));
  76117. } else {
  76118. this.sock.on("connect", this._onConnect.bind(this));
  76119. }
  76120. this.sock.on("close", this._onClose.bind(this));
  76121. }
  76122. _onConnect() {
  76123. this.connWaiter.set();
  76124. }
  76125. _onClose() {
  76126. if (!this.connected) {
  76127. return;
  76128. }
  76129. const newErr = new errors.ClientConnectionClosedError(`the connection has been aborted`);
  76130. if (!this.connWaiter.done || this.messageWaiter) {
  76131. this._abortWaiters(newErr);
  76132. }
  76133. if (this.buffer.takeMessage() && this.buffer.getMessageType() === chars.$E) {
  76134. Object.defineProperty(newErr, "cause", {
  76135. enumerable: false,
  76136. value: this._parseErrorMessage()
  76137. });
  76138. }
  76139. this._abortWithError(newErr);
  76140. }
  76141. _onError(err2) {
  76142. const newErr = new errors.ClientConnectionClosedError(`network error: ${err2}`, { cause: err2 });
  76143. try {
  76144. this._abortWaiters(newErr);
  76145. } finally {
  76146. this._abortWithError(newErr);
  76147. }
  76148. }
  76149. _onData(data) {
  76150. try {
  76151. this.buffer.feed(data);
  76152. } catch (e4) {
  76153. if (this.messageWaiter) {
  76154. this.messageWaiter.setError(e4);
  76155. this.messageWaiter = null;
  76156. }
  76157. this._abortWithError(e4);
  76158. }
  76159. if (this.messageWaiter) {
  76160. if (this.buffer.takeMessage()) {
  76161. this.messageWaiter.set();
  76162. this.messageWaiter = null;
  76163. }
  76164. }
  76165. }
  76166. async _waitForMessage() {
  76167. if (this.buffer.takeMessage()) {
  76168. return;
  76169. }
  76170. if (this.paused) {
  76171. this.paused = false;
  76172. this.sock.resume();
  76173. }
  76174. this.sock.ref();
  76175. this.messageWaiter = new event_1.default();
  76176. try {
  76177. await this.messageWaiter.wait();
  76178. } finally {
  76179. this.sock.unref();
  76180. }
  76181. }
  76182. _sendData(data) {
  76183. this.sock.write(data);
  76184. }
  76185. static newSock(addr, options) {
  76186. if (typeof addr === "string") {
  76187. return node_net_1.default.createConnection(addr);
  76188. }
  76189. const [host, port] = addr;
  76190. if (options == null) {
  76191. return node_net_1.default.createConnection(port, host);
  76192. }
  76193. const opts = { ...options, host, port };
  76194. return tls.connect(opts);
  76195. }
  76196. _abort() {
  76197. if (this.sock && this.connected) {
  76198. this.sock.destroy();
  76199. }
  76200. super._abort();
  76201. }
  76202. async close() {
  76203. if (this.sock && this.connected) {
  76204. this.sock.write(new buffer_1.WriteMessageBuffer().beginMessage(chars.$X).endMessage().unwrap());
  76205. }
  76206. return await super.close();
  76207. }
  76208. static async connectWithTimeout(config, registry, useTls = true) {
  76209. const sock = this.newSock(config.connectionParams.address, useTls ? getTlsOptions(config.connectionParams) : void 0);
  76210. const conn = new this(sock, config, registry);
  76211. const connPromise = conn.connect();
  76212. let timeoutCb = null;
  76213. let timeoutHappened = false;
  76214. if (config.connectTimeout) {
  76215. timeoutCb = setTimeout(() => {
  76216. if (!conn.connected) {
  76217. timeoutHappened = true;
  76218. conn.sock.destroy(new errors.ClientConnectionTimeoutError(`connection timed out (${config.connectTimeout}ms)`));
  76219. }
  76220. }, config.connectTimeout);
  76221. }
  76222. try {
  76223. await connPromise;
  76224. } catch (e4) {
  76225. conn._abort();
  76226. if (timeoutHappened && e4 instanceof errors.ClientConnectionClosedError) {
  76227. throw new errors.ClientConnectionTimeoutError(`connection timed out (${config.connectTimeout}ms)`);
  76228. }
  76229. if (e4 instanceof errors.GelError) {
  76230. throw e4;
  76231. } else {
  76232. let err2;
  76233. switch (e4.code) {
  76234. case "EPROTO":
  76235. if (useTls === true) {
  76236. try {
  76237. return this.connectWithTimeout(config, registry, false);
  76238. } catch {
  76239. }
  76240. }
  76241. err2 = new errors.ClientConnectionFailedError(`${e4.message}
  76242. Attempted to connect using the following credentials:
  76243. ${config.connectionParams.explainConfig()}
  76244. `, { cause: e4 });
  76245. break;
  76246. case "ECONNREFUSED":
  76247. case "ECONNABORTED":
  76248. case "ECONNRESET":
  76249. case "ENOTFOUND":
  76250. case "ENOENT":
  76251. err2 = new errors.ClientConnectionFailedTemporarilyError(`${e4.message}
  76252. Attempted to connect using the following credentials:
  76253. ${config.connectionParams.explainConfig()}
  76254. `, { cause: e4 });
  76255. break;
  76256. default:
  76257. err2 = new errors.ClientConnectionFailedError(`${e4.message}
  76258. Attempted to connect using the following credentials:
  76259. ${config.connectionParams.explainConfig()}
  76260. `, { cause: e4 });
  76261. break;
  76262. }
  76263. throw err2;
  76264. }
  76265. } finally {
  76266. if (timeoutCb != null) {
  76267. clearTimeout(timeoutCb);
  76268. }
  76269. }
  76270. return conn;
  76271. }
  76272. async connect() {
  76273. await this.connWaiter.wait();
  76274. if (this.sock instanceof tls.TLSSocket) {
  76275. if (this.sock.alpnProtocol !== "edgedb-binary") {
  76276. throw new errors.ClientConnectionFailedError("The server doesn't support the edgedb-binary protocol.");
  76277. }
  76278. }
  76279. const handshake = new buffer_1.WriteMessageBuffer();
  76280. handshake.beginMessage(chars.$V).writeInt16(this.protocolVersion[0]).writeInt16(this.protocolVersion[1]);
  76281. const clientHandshakeOptions = {
  76282. user: this.config.connectionParams.user,
  76283. database: this.config.connectionParams.database
  76284. };
  76285. if (this.config.connectionParams.secretKey != null) {
  76286. clientHandshakeOptions.secret_key = this.config.connectionParams.secretKey;
  76287. }
  76288. handshake.writeInt16(Object.keys(clientHandshakeOptions).length);
  76289. for (const [key, value] of Object.entries(clientHandshakeOptions)) {
  76290. handshake.writeString(key).writeString(value);
  76291. }
  76292. handshake.writeInt16(0);
  76293. handshake.endMessage();
  76294. this.sock.write(handshake.unwrap());
  76295. while (true) {
  76296. if (!this.buffer.takeMessage()) {
  76297. await this._waitForMessage();
  76298. }
  76299. const mtype = this.buffer.getMessageType();
  76300. switch (mtype) {
  76301. case chars.$v: {
  76302. const hi = this.buffer.readInt16();
  76303. const lo = this.buffer.readInt16();
  76304. this._parseHeaders();
  76305. this.buffer.finishMessage();
  76306. const proposed = [hi, lo];
  76307. if ((0, utils_1.versionGreaterThan)(proposed, baseConn_1.PROTO_VER) || (0, utils_1.versionGreaterThan)(baseConn_1.PROTO_VER_MIN, proposed)) {
  76308. throw new errors.UnsupportedProtocolVersionError(`the server requested an unsupported version of the protocol ${hi}.${lo}`);
  76309. }
  76310. this.protocolVersion = [hi, lo];
  76311. break;
  76312. }
  76313. case chars.$R: {
  76314. const status = this.buffer.readInt32();
  76315. if (status === AuthenticationStatuses.AUTH_OK) {
  76316. this.buffer.finishMessage();
  76317. } else if (status === AuthenticationStatuses.AUTH_SASL) {
  76318. await this._authSasl();
  76319. } else {
  76320. throw new errors.ProtocolError(`unsupported authentication method requested by the server: ${status}`);
  76321. }
  76322. break;
  76323. }
  76324. case chars.$K: {
  76325. this.serverSecret = this.buffer.readBuffer(32);
  76326. this.buffer.finishMessage();
  76327. break;
  76328. }
  76329. case chars.$E: {
  76330. throw this._parseErrorMessage();
  76331. }
  76332. case chars.$s: {
  76333. this._parseDescribeStateMessage();
  76334. break;
  76335. }
  76336. case chars.$Z: {
  76337. this._parseSyncMessage();
  76338. if (!(this.sock instanceof tls.TLSSocket) && typeof Deno === "undefined") {
  76339. const [major, minor] = this.protocolVersion;
  76340. throw new errors.ProtocolError(`the protocol version requires TLS: ${major}.${minor}`);
  76341. }
  76342. this.connected = true;
  76343. return;
  76344. }
  76345. default:
  76346. this._fallthrough();
  76347. }
  76348. }
  76349. }
  76350. async _authSasl() {
  76351. const numMethods = this.buffer.readInt32();
  76352. if (numMethods <= 0) {
  76353. throw new errors.ProtocolError("the server requested SASL authentication but did not offer any methods");
  76354. }
  76355. const methods = [];
  76356. let foundScram256 = false;
  76357. for (let _3 = 0; _3 < numMethods; _3++) {
  76358. const method = this.buffer.readString();
  76359. if (method === "SCRAM-SHA-256") {
  76360. foundScram256 = true;
  76361. }
  76362. methods.push(method);
  76363. }
  76364. this.buffer.finishMessage();
  76365. if (!foundScram256) {
  76366. throw new errors.ProtocolError(`the server offered the following SASL authentication methods: ${methods.join(", ")}, neither are supported.`);
  76367. }
  76368. const clientNonce = scram.generateNonce();
  76369. const [clientFirst, clientFirstBare] = scram.buildClientFirstMessage(clientNonce, this.config.connectionParams.user);
  76370. const wb = new buffer_1.WriteMessageBuffer();
  76371. wb.beginMessage(chars.$p).writeString("SCRAM-SHA-256").writeString(clientFirst).endMessage();
  76372. this.sock.write(wb.unwrap());
  76373. await this._ensureMessage(chars.$R, "SASLContinue");
  76374. let status = this.buffer.readInt32();
  76375. if (status !== AuthenticationStatuses.AUTH_SASL_CONTINUE) {
  76376. throw new errors.ProtocolError(`expected SASLContinue from the server, received ${status}`);
  76377. }
  76378. const serverFirst = this.buffer.readString();
  76379. this.buffer.finishMessage();
  76380. const [serverNonce, salt, itercount] = scram.parseServerFirstMessage(serverFirst);
  76381. const [clientFinal, expectedServerSig] = await scram.buildClientFinalMessage(this.config.connectionParams.password || "", salt, itercount, clientFirstBare, serverFirst, serverNonce);
  76382. wb.reset().beginMessage(chars.$r).writeString(clientFinal).endMessage();
  76383. this.sock.write(wb.unwrap());
  76384. await this._ensureMessage(chars.$R, "SASLFinal");
  76385. status = this.buffer.readInt32();
  76386. if (status !== AuthenticationStatuses.AUTH_SASL_FINAL) {
  76387. throw new errors.ProtocolError(`expected SASLFinal from the server, received ${status}`);
  76388. }
  76389. const serverFinal = this.buffer.readString();
  76390. this.buffer.finishMessage();
  76391. const serverSig = scram.parseServerFinalMessage(serverFinal);
  76392. if (!scram.bufferEquals(serverSig, expectedServerSig)) {
  76393. throw new errors.ProtocolError("server SCRAM proof does not match");
  76394. }
  76395. }
  76396. async _ensureMessage(expectedMtype, err2) {
  76397. if (!this.buffer.takeMessage()) {
  76398. await this._waitForMessage();
  76399. }
  76400. const mtype = this.buffer.getMessageType();
  76401. switch (mtype) {
  76402. case chars.$E: {
  76403. throw this._parseErrorMessage();
  76404. }
  76405. case expectedMtype: {
  76406. return;
  76407. }
  76408. default: {
  76409. throw new errors.UnexpectedMessageError(`expected ${err2} from the server, received ${chars.chr(mtype)}`);
  76410. }
  76411. }
  76412. }
  76413. };
  76414. exports2.RawConnection = RawConnection;
  76415. }
  76416. });
  76417. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/fetchConn.js
  76418. var require_fetchConn = __commonJS({
  76419. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/fetchConn.js"(exports2) {
  76420. "use strict";
  76421. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  76422. if (k22 === void 0) k22 = k3;
  76423. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  76424. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  76425. desc = { enumerable: true, get: function() {
  76426. return m4[k3];
  76427. } };
  76428. }
  76429. Object.defineProperty(o3, k22, desc);
  76430. } : function(o3, m4, k3, k22) {
  76431. if (k22 === void 0) k22 = k3;
  76432. o3[k22] = m4[k3];
  76433. });
  76434. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  76435. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  76436. } : function(o3, v6) {
  76437. o3["default"] = v6;
  76438. });
  76439. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  76440. if (mod && mod.__esModule) return mod;
  76441. var result = {};
  76442. if (mod != null) {
  76443. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  76444. }
  76445. __setModuleDefault2(result, mod);
  76446. return result;
  76447. };
  76448. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  76449. return mod && mod.__esModule ? mod : { "default": mod };
  76450. };
  76451. Object.defineProperty(exports2, "__esModule", { value: true });
  76452. exports2.FetchConnection = exports2.AdminUIFetchConnection = void 0;
  76453. var baseConn_1 = require_baseConn();
  76454. var codecs_1 = require_codecs();
  76455. var errors_1 = require_errors();
  76456. var ifaces_1 = require_ifaces2();
  76457. var buffer_1 = require_buffer();
  76458. var chars = __importStar2(require_chars());
  76459. var event_1 = __importDefault2(require_event());
  76460. var utils_1 = require_utils2();
  76461. var PROTO_MIME = `application/x.edgedb.v_${baseConn_1.PROTO_VER[0]}_${baseConn_1.PROTO_VER[1]}.binary'`;
  76462. var PROTO_MIME_RE = /application\/x\.edgedb\.v_(\d+)_(\d+)\.binary/;
  76463. var STUDIO_CAPABILITIES = (baseConn_1.RESTRICTED_CAPABILITIES | baseConn_1.Capabilities.SESSION_CONFIG | baseConn_1.Capabilities.SET_GLOBAL) >>> 0;
  76464. var BaseFetchConnection = class extends baseConn_1.BaseRawConnection {
  76465. authenticatedFetch;
  76466. abortSignal = null;
  76467. constructor(fetch3, registry) {
  76468. super(registry);
  76469. this.authenticatedFetch = fetch3;
  76470. }
  76471. async _waitForMessage() {
  76472. if (this.buffer.takeMessage()) {
  76473. return;
  76474. }
  76475. if (this.messageWaiter == null || this.messageWaiter.done) {
  76476. throw new errors_1.InternalClientError(`message waiter was not initialized before waiting for response`);
  76477. }
  76478. await this.messageWaiter.wait();
  76479. }
  76480. async __sendData(data) {
  76481. if (this.buffer.takeMessage()) {
  76482. const mtype = this.buffer.getMessageType();
  76483. throw new errors_1.InternalClientError(`sending request before reading all data of the previous one: ${chars.chr(mtype)}`);
  76484. }
  76485. if (this.messageWaiter != null && !this.messageWaiter.done) {
  76486. throw new errors_1.InternalClientError(`sending request before waiting for completion of the previous one`);
  76487. }
  76488. this.messageWaiter = new event_1.default();
  76489. try {
  76490. const resp = await this.authenticatedFetch("", {
  76491. method: "post",
  76492. body: data,
  76493. headers: {
  76494. "Content-Type": PROTO_MIME
  76495. },
  76496. signal: this.abortSignal
  76497. });
  76498. if (!resp.ok) {
  76499. throw new errors_1.ProtocolError(`fetch failed with status code ${resp.status}: ${resp.statusText}`);
  76500. }
  76501. const contentType = resp.headers.get("content-type");
  76502. const matchProtoVer = contentType == null ? void 0 : contentType.match(PROTO_MIME_RE);
  76503. if (matchProtoVer) {
  76504. this.protocolVersion = [+matchProtoVer[1], +matchProtoVer[2]];
  76505. }
  76506. const respData = await resp.arrayBuffer();
  76507. const buf = new Uint8Array(respData);
  76508. try {
  76509. this.buffer.feed(buf);
  76510. } catch (e4) {
  76511. this.messageWaiter.setError(e4);
  76512. }
  76513. if (!this.buffer.takeMessage()) {
  76514. throw new errors_1.ProtocolError("no binary protocol messages in the response");
  76515. }
  76516. this.messageWaiter.set();
  76517. } catch (e4) {
  76518. this.messageWaiter.setError(e4);
  76519. } finally {
  76520. this.messageWaiter = null;
  76521. }
  76522. }
  76523. _sendData(data) {
  76524. this.__sendData(data);
  76525. }
  76526. async fetch(...args) {
  76527. const protoVer = this.protocolVersion;
  76528. try {
  76529. return await super.fetch(...args);
  76530. } catch (err2) {
  76531. if (err2 instanceof errors_1.BinaryProtocolError && !(0, utils_1.versionEqual)(protoVer, this.protocolVersion)) {
  76532. return await super.fetch(...args);
  76533. }
  76534. throw err2;
  76535. }
  76536. }
  76537. static create(fetch3, registry) {
  76538. const conn = new this(fetch3, registry);
  76539. conn.connected = true;
  76540. conn.connWaiter.set();
  76541. return conn;
  76542. }
  76543. };
  76544. var AdminUIFetchConnection = class extends BaseFetchConnection {
  76545. adminUIMode = true;
  76546. static create(fetch3, registry, knownServerVersion) {
  76547. const conn = super.create(fetch3, registry);
  76548. if (knownServerVersion && knownServerVersion[0] < 6) {
  76549. conn.protocolVersion = [2, 0];
  76550. }
  76551. return conn;
  76552. }
  76553. async rawParse(language, query, state2, options, abortSignal) {
  76554. this.abortSignal = abortSignal ?? null;
  76555. const result = await this._parse(language, query, ifaces_1.OutputFormat.BINARY, ifaces_1.Cardinality.MANY, state2, STUDIO_CAPABILITIES, options);
  76556. return [this.protocolVersion, ...result];
  76557. }
  76558. async rawExecute(language, query, state2, outCodec, options, inCodec, args = null, abortSignal) {
  76559. this.abortSignal = abortSignal ?? null;
  76560. const result = new buffer_1.WriteBuffer();
  76561. const [warnings] = await this._executeFlow(language, query, args, outCodec ? ifaces_1.OutputFormat.BINARY : ifaces_1.OutputFormat.NONE, ifaces_1.Cardinality.MANY, state2, inCodec ?? codecs_1.NULL_CODEC, outCodec ?? codecs_1.NULL_CODEC, result, STUDIO_CAPABILITIES, options);
  76562. return [result.unwrap(), warnings];
  76563. }
  76564. };
  76565. exports2.AdminUIFetchConnection = AdminUIFetchConnection;
  76566. var FetchConnection = class _FetchConnection extends BaseFetchConnection {
  76567. static createConnectWithTimeout(httpSCRAMAuth) {
  76568. return async function connectWithTimeout(config, registry) {
  76569. const fetch3 = await (0, utils_1.getAuthenticatedFetch)(config.connectionParams, httpSCRAMAuth);
  76570. const conn = new _FetchConnection(fetch3, registry);
  76571. conn.connected = true;
  76572. conn.connWaiter.set();
  76573. return conn;
  76574. };
  76575. }
  76576. };
  76577. exports2.FetchConnection = FetchConnection;
  76578. }
  76579. });
  76580. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/httpScram.js
  76581. var require_httpScram = __commonJS({
  76582. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/httpScram.js"(exports2) {
  76583. "use strict";
  76584. Object.defineProperty(exports2, "__esModule", { value: true });
  76585. exports2.getHTTPSCRAMAuth = getHTTPSCRAMAuth;
  76586. var errors_1 = require_errors();
  76587. var buffer_1 = require_buffer();
  76588. var scram_1 = require_scram();
  76589. var AUTH_ENDPOINT = "/auth/token";
  76590. function getHTTPSCRAMAuth(cryptoUtils) {
  76591. const { bufferEquals, generateNonce, buildClientFirstMessage, buildClientFinalMessage, parseServerFirstMessage, parseServerFinalMessage } = (0, scram_1.getSCRAM)(cryptoUtils);
  76592. return async function HTTPSCRAMAuth(baseUrl, username, password) {
  76593. const authUrl = baseUrl + AUTH_ENDPOINT;
  76594. const clientNonce = generateNonce();
  76595. const [clientFirst, clientFirstBare] = buildClientFirstMessage(clientNonce, username);
  76596. const serverFirstRes = await fetch(authUrl, {
  76597. headers: {
  76598. Authorization: `SCRAM-SHA-256 data=${utf8ToB64(clientFirst)}`
  76599. }
  76600. });
  76601. const authenticateHeader = serverFirstRes.headers.get("WWW-Authenticate");
  76602. if (serverFirstRes.status !== 401 || !authenticateHeader) {
  76603. const body = await serverFirstRes.text();
  76604. throw new errors_1.ProtocolError(`authentication failed: ${body}`);
  76605. }
  76606. if (!authenticateHeader.startsWith("SCRAM-SHA-256")) {
  76607. throw new errors_1.ProtocolError(`unsupported authentication scheme: ${authenticateHeader}`);
  76608. }
  76609. const authParams = authenticateHeader.split(/ (.+)?/, 2)[1] ?? "";
  76610. if (authParams.length === 0) {
  76611. const body = await serverFirstRes.text();
  76612. throw new errors_1.ProtocolError(`authentication failed: ${body}`);
  76613. }
  76614. const { sid, data: serverFirst } = parseScramAttrs(authParams);
  76615. if (!sid || !serverFirst) {
  76616. throw new errors_1.ProtocolError(`authentication challenge missing attributes: expected "sid" and "data", got '${authParams}'`);
  76617. }
  76618. const [serverNonce, salt, iterCount] = parseServerFirstMessage(serverFirst);
  76619. const [clientFinal, expectedServerSig] = await buildClientFinalMessage(password, salt, iterCount, clientFirstBare, serverFirst, serverNonce);
  76620. const serverFinalRes = await fetch(authUrl, {
  76621. headers: {
  76622. Authorization: `SCRAM-SHA-256 sid=${sid}, data=${utf8ToB64(clientFinal)}`
  76623. }
  76624. });
  76625. const authInfoHeader = serverFinalRes.headers.get("Authentication-Info");
  76626. if (!serverFinalRes.ok || !authInfoHeader) {
  76627. const body = await serverFinalRes.text();
  76628. throw new errors_1.ProtocolError(`authentication failed: ${body}`);
  76629. }
  76630. const { data: serverFinal, sid: sidFinal } = parseScramAttrs(authInfoHeader);
  76631. if (!sidFinal || !serverFinal) {
  76632. throw new errors_1.ProtocolError(`authentication info missing attributes: expected "sid" and "data", got '${authInfoHeader}'`);
  76633. }
  76634. if (sidFinal !== sid) {
  76635. throw new errors_1.ProtocolError("SCRAM session id does not match");
  76636. }
  76637. const serverSig = parseServerFinalMessage(serverFinal);
  76638. if (!bufferEquals(serverSig, expectedServerSig)) {
  76639. throw new errors_1.ProtocolError("server SCRAM proof does not match");
  76640. }
  76641. const authToken = await serverFinalRes.text();
  76642. return authToken;
  76643. };
  76644. }
  76645. function utf8ToB64(str) {
  76646. return (0, buffer_1.encodeB64)(buffer_1.utf8Encoder.encode(str));
  76647. }
  76648. function b64ToUtf8(str) {
  76649. return buffer_1.utf8Decoder.decode((0, buffer_1.decodeB64)(str));
  76650. }
  76651. function parseScramAttrs(paramsStr) {
  76652. const params = new Map(paramsStr.length > 0 ? paramsStr.split(",").map((attr) => attr.split(/=(.+)?/, 2)).map(([key, val2]) => [key.trim(), val2.trim()]) : []);
  76653. const sid = params.get("sid") ?? null;
  76654. const rawData = params.get("data");
  76655. const data = rawData ? b64ToUtf8(rawData) : null;
  76656. return { sid, data };
  76657. }
  76658. }
  76659. });
  76660. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeClient.js
  76661. var require_nodeClient = __commonJS({
  76662. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/nodeClient.js"(exports2) {
  76663. "use strict";
  76664. var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
  76665. return mod && mod.__esModule ? mod : { "default": mod };
  76666. };
  76667. Object.defineProperty(exports2, "__esModule", { value: true });
  76668. exports2.createClient = createClient;
  76669. exports2.createHttpClient = createHttpClient;
  76670. var baseClient_1 = require_baseClient();
  76671. var conUtils_server_1 = require_conUtils_server();
  76672. var options_1 = require_options();
  76673. var rawConn_1 = require_rawConn();
  76674. var fetchConn_1 = require_fetchConn();
  76675. var httpScram_1 = require_httpScram();
  76676. var cryptoUtils_1 = __importDefault2(require_cryptoUtils());
  76677. var ClientPool = class extends baseClient_1.BaseClientPool {
  76678. isStateless = false;
  76679. _connectWithTimeout = rawConn_1.RawConnection.connectWithTimeout.bind(rawConn_1.RawConnection);
  76680. };
  76681. function createClient(options) {
  76682. return new baseClient_1.Client(new ClientPool(conUtils_server_1.parseConnectArguments, typeof options === "string" ? { dsn: options } : options ?? {}), options_1.Options.defaults());
  76683. }
  76684. var httpSCRAMAuth = (0, httpScram_1.getHTTPSCRAMAuth)(cryptoUtils_1.default);
  76685. var FetchClientPool = class extends baseClient_1.BaseClientPool {
  76686. isStateless = true;
  76687. _connectWithTimeout = fetchConn_1.FetchConnection.createConnectWithTimeout(httpSCRAMAuth);
  76688. };
  76689. function createHttpClient(options) {
  76690. return new baseClient_1.Client(new FetchClientPool(conUtils_server_1.parseConnectArguments, typeof options === "string" ? { dsn: options } : options ?? {}), options_1.Options.defaults());
  76691. }
  76692. }
  76693. });
  76694. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/wkt.js
  76695. var require_wkt = __commonJS({
  76696. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/datatypes/wkt.js"(exports2) {
  76697. "use strict";
  76698. Object.defineProperty(exports2, "__esModule", { value: true });
  76699. exports2.parseWKT = parseWKT;
  76700. var postgis_1 = require_postgis();
  76701. var sridRegex = /\s*SRID=([0-9]+)\s*;/iy;
  76702. var endRegex = /\s*$/y;
  76703. var geomTypes = [
  76704. "POINT",
  76705. "LINESTRING",
  76706. "POLYGON",
  76707. "MULTIPOINT",
  76708. "MULTILINESTRING",
  76709. "MULTIPOLYGON",
  76710. "GEOMETRYCOLLECTION",
  76711. "POLYHEDRALSURFACE",
  76712. "TRIANGLE",
  76713. "TIN",
  76714. "CIRCULARSTRING",
  76715. "COMPOUNDCURVE",
  76716. "CURVEPOLYGON",
  76717. "MULTICURVE",
  76718. "MULTISURFACE"
  76719. ];
  76720. var geomTypeRegex = new RegExp(`\\s*(${geomTypes.join("|")})`, "iy");
  76721. var zmFlagsRegex = /\s+(ZM|Z|M)/iy;
  76722. var emptyOrOpenRegex = /\s+(EMPTY)|\s*\(/iy;
  76723. var openRegex = /\s*\(/y;
  76724. var closeRegex = /\s*\)/y;
  76725. var commaRegex = /\s*,/y;
  76726. var _num = "-?[0-9]+(?:\\.[0-9]+)?";
  76727. var pointRegex = new RegExp(`\\s*(${_num})\\s+(${_num})(?:\\s+(${_num}))?(?:\\s+(${_num}))?`, "y");
  76728. function parseWKT(wkt) {
  76729. let i4 = 0;
  76730. let hasZ = null;
  76731. let hasM = null;
  76732. let srid = null;
  76733. sridRegex.lastIndex = i4;
  76734. const _srid = sridRegex.exec(wkt);
  76735. if (_srid) {
  76736. srid = parseInt(_srid[1], 10);
  76737. i4 += _srid[0].length;
  76738. }
  76739. const geom = _parseGeom();
  76740. endRegex.lastIndex = i4;
  76741. if (endRegex.exec(wkt) === null) {
  76742. throw createParseError(wkt, i4, "expected end of wkt");
  76743. }
  76744. return geom;
  76745. function _parseGeom(unnamedGeom = null, allowedGeoms = null) {
  76746. geomTypeRegex.lastIndex = i4;
  76747. const _geomType = geomTypeRegex.exec(wkt);
  76748. const type = (_geomType == null ? void 0 : _geomType[1].toUpperCase()) ?? unnamedGeom;
  76749. if (!type || allowedGeoms && !allowedGeoms.includes(type)) {
  76750. throw createParseError(wkt, i4, `expected one of ${(allowedGeoms ? ["(", ...allowedGeoms] : geomTypes).join(", ")}`);
  76751. }
  76752. i4 += (_geomType == null ? void 0 : _geomType[0].length) ?? 0;
  76753. if (_geomType !== null) {
  76754. zmFlagsRegex.lastIndex = i4;
  76755. const _zmFlags = zmFlagsRegex.exec(wkt);
  76756. if (_zmFlags !== null) {
  76757. const zm = _zmFlags[1].toLowerCase();
  76758. hasZ = zm === "zm" || zm === "z";
  76759. hasM = zm === "zm" || zm === "m";
  76760. i4 += _zmFlags[0].length;
  76761. } else {
  76762. hasZ = null;
  76763. hasM = null;
  76764. }
  76765. }
  76766. const open = _geomType === null ? openRegex : emptyOrOpenRegex;
  76767. open.lastIndex = i4;
  76768. const _emptyOrOpen = open.exec(wkt);
  76769. if (_emptyOrOpen === null) {
  76770. throw createParseError(wkt, i4, _geomType === null ? `expected (` : `expected EMPTY or (`);
  76771. }
  76772. i4 += _emptyOrOpen[0].length;
  76773. const empty = _emptyOrOpen[1] != null;
  76774. let geom2;
  76775. switch (type) {
  76776. case "POINT":
  76777. geom2 = _parsePoint(empty);
  76778. break;
  76779. case "LINESTRING":
  76780. case "CIRCULARSTRING":
  76781. geom2 = _parseLineString(empty, type === "CIRCULARSTRING" ? postgis_1.CircularString : postgis_1.LineString);
  76782. break;
  76783. case "POLYGON":
  76784. case "TRIANGLE":
  76785. geom2 = _parsePolygon(empty, type === "TRIANGLE" ? postgis_1.Triangle : postgis_1.Polygon);
  76786. break;
  76787. case "MULTIPOINT":
  76788. geom2 = new postgis_1.MultiPoint(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parsePoint)), hasZ ?? false, hasM ?? false, srid);
  76789. break;
  76790. case "MULTILINESTRING":
  76791. geom2 = new postgis_1.MultiLineString(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parseLineString)), hasZ ?? false, hasM ?? false, srid);
  76792. break;
  76793. case "MULTIPOLYGON":
  76794. case "POLYHEDRALSURFACE":
  76795. case "TIN":
  76796. {
  76797. const Geom = type === "TIN" ? postgis_1.TriangulatedIrregularNetwork : type === "POLYHEDRALSURFACE" ? postgis_1.PolyhedralSurface : postgis_1.MultiPolygon;
  76798. geom2 = new Geom(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(() => _parsePolygon(false, type === "TIN" ? postgis_1.Triangle : postgis_1.Polygon))), hasZ ?? false, hasM ?? false, srid);
  76799. }
  76800. break;
  76801. case "GEOMETRYCOLLECTION": {
  76802. geom2 = new postgis_1.GeometryCollection(empty ? [] : _checkDimensions(() => _parseCommaSep(_parseGeom)), hasZ ?? false, hasM ?? false, srid);
  76803. break;
  76804. }
  76805. case "COMPOUNDCURVE":
  76806. {
  76807. const segments = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("LINESTRING", ["LINESTRING", "CIRCULARSTRING"])));
  76808. geom2 = new postgis_1.CompoundCurve(segments, hasZ ?? false, hasM ?? false, srid);
  76809. }
  76810. break;
  76811. case "CURVEPOLYGON":
  76812. case "MULTICURVE":
  76813. {
  76814. const rings = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("LINESTRING", [
  76815. "LINESTRING",
  76816. "CIRCULARSTRING",
  76817. "COMPOUNDCURVE"
  76818. ])));
  76819. const Geom = type === "MULTICURVE" ? postgis_1.MultiCurve : postgis_1.CurvePolygon;
  76820. geom2 = new Geom(rings, hasZ ?? false, hasM ?? false, srid);
  76821. }
  76822. break;
  76823. case "MULTISURFACE":
  76824. {
  76825. const surfaces = empty ? [] : _checkDimensions(() => _parseCommaSep(() => _parseGeom("POLYGON", ["POLYGON", "CURVEPOLYGON"])));
  76826. geom2 = new postgis_1.MultiSurface(surfaces, hasZ ?? false, hasM ?? false, srid);
  76827. }
  76828. break;
  76829. default:
  76830. assertNever(type, `unknown geometry type ${type}`);
  76831. }
  76832. if (!empty) {
  76833. closeRegex.lastIndex = i4;
  76834. const _close = closeRegex.exec(wkt);
  76835. if (_close === null) {
  76836. throw createParseError(wkt, i4, `expected )`);
  76837. }
  76838. i4 += _close[0].length;
  76839. }
  76840. return geom2;
  76841. }
  76842. function _parsePoint(empty = false) {
  76843. if (empty) {
  76844. return new postgis_1.Point(NaN, NaN, hasZ ? NaN : null, hasM ? NaN : null, srid);
  76845. }
  76846. pointRegex.lastIndex = i4;
  76847. const coords = pointRegex.exec(wkt);
  76848. if (coords === null) {
  76849. throw createParseError(wkt, i4, `expected between 2 to 4 coordinates`);
  76850. }
  76851. const x4 = parseFloat(coords[1]);
  76852. const y2 = parseFloat(coords[2]);
  76853. const z2 = coords[3] ? parseFloat(coords[3]) : null;
  76854. const m4 = coords[4] ? parseFloat(coords[4]) : null;
  76855. if (hasZ === null) {
  76856. hasZ = z2 !== null;
  76857. hasM = m4 !== null;
  76858. } else {
  76859. if (m4 === null) {
  76860. if (hasZ && hasM) {
  76861. throw createParseError(wkt, i4, `expected M coordinate`);
  76862. }
  76863. } else {
  76864. if (!hasM) {
  76865. throw createParseError(wkt, i4, `unexpected M coordinate`);
  76866. }
  76867. }
  76868. if (z2 === null) {
  76869. if (hasZ || hasM) {
  76870. throw createParseError(wkt, i4, `expected ${hasZ ? "Z" : "M"} coordinate`);
  76871. }
  76872. } else {
  76873. if (!hasZ && (!hasM || m4 !== null)) {
  76874. throw createParseError(wkt, i4, `unexpected Z coordinate`);
  76875. }
  76876. }
  76877. }
  76878. i4 += coords[0].length;
  76879. return new postgis_1.Point(x4, y2, hasZ ? z2 : null, hasZ ? m4 : z2, srid);
  76880. }
  76881. function _parseLineString(empty = false, Geom = postgis_1.LineString) {
  76882. return new Geom(empty ? [] : _parseCommaSep(_parsePoint), hasZ ?? false, hasM ?? false, srid);
  76883. }
  76884. function _parsePolygon(empty = false, Geom = postgis_1.Polygon) {
  76885. return new Geom(empty ? [] : _parseCommaSep(() => _parseBracketedGeom(_parseLineString)), hasZ ?? false, hasM ?? false, srid);
  76886. }
  76887. function _parseCommaSep(parseGeom) {
  76888. const geoms = [parseGeom()];
  76889. while (true) {
  76890. commaRegex.lastIndex = i4;
  76891. const comma = commaRegex.exec(wkt);
  76892. if (comma === null) {
  76893. break;
  76894. }
  76895. i4 += comma[0].length;
  76896. geoms.push(parseGeom());
  76897. }
  76898. return geoms;
  76899. }
  76900. function _parseBracketedGeom(parseGeom) {
  76901. openRegex.lastIndex = i4;
  76902. const open = openRegex.exec(wkt);
  76903. if (open === null) {
  76904. throw createParseError(wkt, i4, `expected (`);
  76905. }
  76906. i4 += open[0].length;
  76907. const geom2 = parseGeom();
  76908. closeRegex.lastIndex = i4;
  76909. const close = closeRegex.exec(wkt);
  76910. if (close === null) {
  76911. throw createParseError(wkt, i4, `expected )`);
  76912. }
  76913. i4 += close[0].length;
  76914. return geom2;
  76915. }
  76916. function _checkDimensions(parseChildren) {
  76917. const parentZ = hasZ;
  76918. const parentM = hasM;
  76919. const geoms = parseChildren();
  76920. hasZ = parentZ ?? geoms[0].hasZ ?? false;
  76921. hasM = parentM ?? geoms[0].hasM ?? false;
  76922. if (geoms.some((geom2) => geom2.hasZ !== hasZ || geom2.hasM !== hasM)) {
  76923. throw createParseError(wkt, i4, `child geometries have mixed dimensions`);
  76924. }
  76925. return geoms;
  76926. }
  76927. }
  76928. function createParseError(_wkt, index6, error2) {
  76929. return new Error(`${error2} at position ${index6}`);
  76930. }
  76931. function assertNever(_type, message) {
  76932. throw new Error(message);
  76933. }
  76934. }
  76935. });
  76936. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.shared.js
  76937. var require_index_shared = __commonJS({
  76938. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.shared.js"(exports2) {
  76939. "use strict";
  76940. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  76941. if (k22 === void 0) k22 = k3;
  76942. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  76943. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  76944. desc = { enumerable: true, get: function() {
  76945. return m4[k3];
  76946. } };
  76947. }
  76948. Object.defineProperty(o3, k22, desc);
  76949. } : function(o3, m4, k3, k22) {
  76950. if (k22 === void 0) k22 = k3;
  76951. o3[k22] = m4[k3];
  76952. });
  76953. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  76954. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  76955. } : function(o3, v6) {
  76956. o3["default"] = v6;
  76957. });
  76958. var __exportStar2 = exports2 && exports2.__exportStar || function(m4, exports3) {
  76959. for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) __createBinding2(exports3, m4, p3);
  76960. };
  76961. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  76962. if (mod && mod.__esModule) return mod;
  76963. var result = {};
  76964. if (mod != null) {
  76965. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  76966. }
  76967. __setModuleDefault2(result, mod);
  76968. return result;
  76969. };
  76970. Object.defineProperty(exports2, "__esModule", { value: true });
  76971. exports2._ReadBuffer = exports2._CodecsRegistry = exports2.throwWarnings = exports2.logWarnings = exports2.defaultBackoff = exports2.Options = exports2.RetryOptions = exports2.RetryCondition = exports2.IsolationLevel = exports2.parseWKT = exports2.Float16Array = exports2.SparseVector = exports2.MultiRange = exports2.Range = exports2.ConfigMemory = exports2.DateDuration = exports2.RelativeDuration = exports2.Duration = exports2.LocalTime = exports2.LocalDate = exports2.LocalDateTime = void 0;
  76972. var datetime_1 = require_datetime();
  76973. Object.defineProperty(exports2, "LocalDateTime", { enumerable: true, get: function() {
  76974. return datetime_1.LocalDateTime;
  76975. } });
  76976. Object.defineProperty(exports2, "LocalDate", { enumerable: true, get: function() {
  76977. return datetime_1.LocalDate;
  76978. } });
  76979. Object.defineProperty(exports2, "LocalTime", { enumerable: true, get: function() {
  76980. return datetime_1.LocalTime;
  76981. } });
  76982. Object.defineProperty(exports2, "Duration", { enumerable: true, get: function() {
  76983. return datetime_1.Duration;
  76984. } });
  76985. Object.defineProperty(exports2, "RelativeDuration", { enumerable: true, get: function() {
  76986. return datetime_1.RelativeDuration;
  76987. } });
  76988. Object.defineProperty(exports2, "DateDuration", { enumerable: true, get: function() {
  76989. return datetime_1.DateDuration;
  76990. } });
  76991. var memory_1 = require_memory();
  76992. Object.defineProperty(exports2, "ConfigMemory", { enumerable: true, get: function() {
  76993. return memory_1.ConfigMemory;
  76994. } });
  76995. var range_1 = require_range2();
  76996. Object.defineProperty(exports2, "Range", { enumerable: true, get: function() {
  76997. return range_1.Range;
  76998. } });
  76999. Object.defineProperty(exports2, "MultiRange", { enumerable: true, get: function() {
  77000. return range_1.MultiRange;
  77001. } });
  77002. var pgvector_1 = require_pgvector();
  77003. Object.defineProperty(exports2, "SparseVector", { enumerable: true, get: function() {
  77004. return pgvector_1.SparseVector;
  77005. } });
  77006. var utils_1 = require_utils2();
  77007. Object.defineProperty(exports2, "Float16Array", { enumerable: true, get: function() {
  77008. return utils_1.Float16Array;
  77009. } });
  77010. __exportStar2(require_postgis(), exports2);
  77011. var wkt_1 = require_wkt();
  77012. Object.defineProperty(exports2, "parseWKT", { enumerable: true, get: function() {
  77013. return wkt_1.parseWKT;
  77014. } });
  77015. var options_1 = require_options();
  77016. Object.defineProperty(exports2, "IsolationLevel", { enumerable: true, get: function() {
  77017. return options_1.IsolationLevel;
  77018. } });
  77019. Object.defineProperty(exports2, "RetryCondition", { enumerable: true, get: function() {
  77020. return options_1.RetryCondition;
  77021. } });
  77022. Object.defineProperty(exports2, "RetryOptions", { enumerable: true, get: function() {
  77023. return options_1.RetryOptions;
  77024. } });
  77025. Object.defineProperty(exports2, "Options", { enumerable: true, get: function() {
  77026. return options_1.Options;
  77027. } });
  77028. Object.defineProperty(exports2, "defaultBackoff", { enumerable: true, get: function() {
  77029. return options_1.defaultBackoff;
  77030. } });
  77031. Object.defineProperty(exports2, "logWarnings", { enumerable: true, get: function() {
  77032. return options_1.logWarnings;
  77033. } });
  77034. Object.defineProperty(exports2, "throwWarnings", { enumerable: true, get: function() {
  77035. return options_1.throwWarnings;
  77036. } });
  77037. __exportStar2(require_errors(), exports2);
  77038. var reg = __importStar2(require_registry());
  77039. var buf = __importStar2(require_buffer());
  77040. exports2._CodecsRegistry = reg.CodecsRegistry;
  77041. exports2._ReadBuffer = buf.ReadBuffer;
  77042. }
  77043. });
  77044. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/typeutil.js
  77045. var require_typeutil = __commonJS({
  77046. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/typeutil.js"(exports2) {
  77047. "use strict";
  77048. Object.defineProperty(exports2, "__esModule", { value: true });
  77049. }
  77050. });
  77051. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/strictMap.js
  77052. var require_strictMap = __commonJS({
  77053. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/strictMap.js"(exports2) {
  77054. "use strict";
  77055. Object.defineProperty(exports2, "__esModule", { value: true });
  77056. exports2.StrictMapSet = exports2.StrictMap = void 0;
  77057. var StrictMap = class extends Map {
  77058. get(key) {
  77059. if (!this.has(key)) {
  77060. throw new Error(`key "${key}" is not found`);
  77061. }
  77062. return super.get(key);
  77063. }
  77064. };
  77065. exports2.StrictMap = StrictMap;
  77066. var StrictMapSet = class extends StrictMap {
  77067. appendAt(key, value) {
  77068. const set = this.has(key) ? this.get(key) : /* @__PURE__ */ new Set();
  77069. set.add(value);
  77070. this.set(key, set);
  77071. }
  77072. };
  77073. exports2.StrictMapSet = StrictMapSet;
  77074. }
  77075. });
  77076. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/reservedKeywords.js
  77077. var require_reservedKeywords = __commonJS({
  77078. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/reservedKeywords.js"(exports2) {
  77079. "use strict";
  77080. Object.defineProperty(exports2, "__esModule", { value: true });
  77081. exports2.reservedKeywords = void 0;
  77082. exports2.reservedKeywords = /* @__PURE__ */ new Set([
  77083. "__edgedbsys__",
  77084. "__edgedbtpl__",
  77085. "__source__",
  77086. "__std__",
  77087. "__subject__",
  77088. "__type__",
  77089. "abort",
  77090. "alter",
  77091. "analyze",
  77092. "and",
  77093. "anyarray",
  77094. "anytuple",
  77095. "anytype",
  77096. "anyobject",
  77097. "begin",
  77098. "case",
  77099. "check",
  77100. "commit",
  77101. "configure",
  77102. "create",
  77103. "deallocate",
  77104. "declare",
  77105. "delete",
  77106. "describe",
  77107. "detached",
  77108. "discard",
  77109. "distinct",
  77110. "do",
  77111. "drop",
  77112. "else",
  77113. "empty",
  77114. "end",
  77115. "execute",
  77116. "exists",
  77117. "explain",
  77118. "extending",
  77119. "fetch",
  77120. "filter",
  77121. "for",
  77122. "get",
  77123. "global",
  77124. "grant",
  77125. "group",
  77126. "if",
  77127. "ilike",
  77128. "import",
  77129. "in",
  77130. "insert",
  77131. "introspect",
  77132. "is",
  77133. "like",
  77134. "limit",
  77135. "listen",
  77136. "load",
  77137. "lock",
  77138. "match",
  77139. "module",
  77140. "move",
  77141. "not",
  77142. "notify",
  77143. "offset",
  77144. "optional",
  77145. "or",
  77146. "order",
  77147. "over",
  77148. "partition",
  77149. "policy",
  77150. "populate",
  77151. "prepare",
  77152. "raise",
  77153. "refresh",
  77154. "reindex",
  77155. "release",
  77156. "reset",
  77157. "revoke",
  77158. "rollback",
  77159. "select",
  77160. "set",
  77161. "single",
  77162. "start",
  77163. "typeof",
  77164. "union",
  77165. "update",
  77166. "variadic",
  77167. "when",
  77168. "window",
  77169. "with"
  77170. ]);
  77171. }
  77172. });
  77173. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/types.js
  77174. var require_types = __commonJS({
  77175. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/types.js"(exports2) {
  77176. "use strict";
  77177. Object.defineProperty(exports2, "__esModule", { value: true });
  77178. exports2.typeMapping = void 0;
  77179. exports2.getTypes = getTypes;
  77180. exports2.types = getTypes;
  77181. exports2.topoSort = topoSort;
  77182. exports2.getTypes = getTypes;
  77183. exports2.types = getTypes;
  77184. var strictMap_1 = require_strictMap();
  77185. var numberType2 = {
  77186. id: "00000000-0000-0000-0000-0000000001ff",
  77187. name: "std::number",
  77188. is_abstract: false,
  77189. is_seq: false,
  77190. kind: "scalar",
  77191. enum_values: null,
  77192. material_id: null,
  77193. bases: []
  77194. };
  77195. exports2.typeMapping = /* @__PURE__ */ new Map([
  77196. [
  77197. "00000000-0000-0000-0000-000000000103",
  77198. numberType2
  77199. ],
  77200. [
  77201. "00000000-0000-0000-0000-000000000104",
  77202. numberType2
  77203. ],
  77204. [
  77205. "00000000-0000-0000-0000-000000000105",
  77206. numberType2
  77207. ],
  77208. [
  77209. "00000000-0000-0000-0000-000000000106",
  77210. numberType2
  77211. ],
  77212. [
  77213. "00000000-0000-0000-0000-000000000107",
  77214. numberType2
  77215. ]
  77216. ]);
  77217. async function getTypes(cxn, params) {
  77218. var _a2, _b, _c, _d;
  77219. const debug = (params == null ? void 0 : params.debug) === true;
  77220. const version3 = await cxn.queryRequiredSingle(`select sys::get_version().major;`);
  77221. const v2Plus = version3 >= 2;
  77222. const v4Plus = version3 >= 4;
  77223. const QUERY = `
  77224. WITH
  77225. MODULE schema,
  77226. material_scalars := (
  77227. SELECT ScalarType
  77228. FILTER NOT .abstract
  77229. AND NOT EXISTS .enum_values
  77230. AND NOT EXISTS (SELECT .ancestors FILTER NOT .abstract)
  77231. )
  77232. SELECT Type {
  77233. id,
  77234. name :=
  77235. array_join(array_agg([IS ObjectType].union_of.name), ' | ')
  77236. IF EXISTS [IS ObjectType].union_of
  77237. ELSE .name,
  77238. is_abstract := .abstract,
  77239. kind := 'object' IF Type IS ObjectType ELSE
  77240. 'scalar' IF Type IS ScalarType ELSE
  77241. 'array' IF Type IS Array ELSE
  77242. 'tuple' IF Type IS Tuple ELSE
  77243. ${v2Plus ? `'range' IF Type IS Range ELSE` : ``}
  77244. ${v4Plus ? `'multirange' IF Type IS MultiRange ELSE` : ``}
  77245. 'unknown',
  77246. [IS ScalarType].enum_values,
  77247. is_seq := 'std::sequence' in [IS ScalarType].ancestors.name,
  77248. # for sequence (abstract type that has non-abstract ancestor)
  77249. single material_id := (
  77250. SELECT x := Type[IS ScalarType].ancestors
  77251. FILTER x IN material_scalars
  77252. LIMIT 1
  77253. ).id,
  77254. [IS InheritingObject].bases: {
  77255. id
  77256. } ORDER BY @index ASC,
  77257. [IS ObjectType].union_of,
  77258. [IS ObjectType].intersection_of,
  77259. [IS ObjectType].pointers: {
  77260. card := ("One" IF .required ELSE "AtMostOne") IF <str>.cardinality = "One" ELSE ("AtLeastOne" IF .required ELSE "Many"),
  77261. name,
  77262. target_id := .target.id,
  77263. kind := 'link' IF .__type__.name = 'schema::Link' ELSE 'property',
  77264. is_exclusive := exists (select .constraints filter .name = 'std::exclusive'),
  77265. is_computed := len(.computed_fields) != 0,
  77266. is_readonly := .readonly,
  77267. has_default := EXISTS .default or ("std::sequence" in .target[IS ScalarType].ancestors.name),
  77268. [IS Link].pointers: {
  77269. card := ("One" IF .required ELSE "AtMostOne") IF <str>.cardinality = "One" ELSE ("AtLeastOne" IF .required ELSE "Many"),
  77270. name := '@' ++ .name,
  77271. target_id := .target.id,
  77272. kind := 'link' IF .__type__.name = 'schema::Link' ELSE 'property',
  77273. is_computed := len(.computed_fields) != 0,
  77274. is_readonly := .readonly
  77275. } filter .name != '@source' and .name != '@target',
  77276. } FILTER any(@is_owned),
  77277. exclusives := assert_distinct((
  77278. [is schema::ObjectType].constraints
  77279. union
  77280. [is schema::ObjectType].pointers.constraints
  77281. ) {
  77282. target := (.subject[is schema::Property].name ?? .subject[is schema::Link].name ?? .subjectexpr)
  77283. } filter .name = 'std::exclusive'),
  77284. backlinks := (
  77285. SELECT DETACHED Link
  77286. FILTER .target = Type
  77287. AND NOT EXISTS .source[IS ObjectType].union_of
  77288. ) {
  77289. card := "AtMostOne"
  77290. IF
  77291. EXISTS (select .constraints filter .name = 'std::exclusive')
  77292. ELSE
  77293. "Many",
  77294. name := '<' ++ .name ++ '[is ' ++ assert_exists(.source.name) ++ ']',
  77295. stub := .name,
  77296. target_id := .source.id,
  77297. kind := 'link',
  77298. is_exclusive := (EXISTS (select .constraints filter .name = 'std::exclusive')) AND <str>.cardinality = "One",
  77299. },
  77300. backlink_stubs := array_agg((
  77301. WITH
  77302. stubs := DISTINCT (SELECT DETACHED Link FILTER .target = Type).name,
  77303. baseObjectId := (SELECT DETACHED ObjectType FILTER .name = 'std::BaseObject' LIMIT 1).id
  77304. FOR stub in { stubs }
  77305. UNION (
  77306. SELECT {
  77307. card := "Many",
  77308. name := '<' ++ stub,
  77309. target_id := baseObjectId,
  77310. kind := 'link',
  77311. is_exclusive := false,
  77312. }
  77313. )
  77314. )),
  77315. array_element_id := [IS Array].element_type.id,
  77316. tuple_elements := (SELECT [IS Tuple].element_types {
  77317. target_id := .type.id,
  77318. name
  77319. } ORDER BY @index ASC),
  77320. ${v2Plus ? `range_element_id := [IS Range].element_type.id,` : ``}
  77321. ${v4Plus ? `multirange_element_id := [IS MultiRange].element_type.id,` : ``}
  77322. }
  77323. ORDER BY .name;
  77324. `;
  77325. const _types = JSON.parse(await cxn.queryJSON(QUERY));
  77326. if (debug)
  77327. console.log(JSON.stringify(_types, null, 2));
  77328. for (const type of _types) {
  77329. if (Array.isArray(type.backlinks)) {
  77330. for (const backlink of type.backlinks) {
  77331. const isName = backlink.name.match(/\[is (.+)\]/)[1];
  77332. if (isName.split("::").length === 2 && isName.startsWith("default::")) {
  77333. backlink.name = backlink.name.replace(/\[is (.+)\]/, `[is ${isName.slice(9)}]`);
  77334. }
  77335. }
  77336. }
  77337. switch (type.kind) {
  77338. case "scalar":
  77339. if (exports2.typeMapping.has(type.id)) {
  77340. type.cast_type = exports2.typeMapping.get(type.id).id;
  77341. }
  77342. if (type.is_seq) {
  77343. type.cast_type = numberType2.id;
  77344. }
  77345. if (type.name !== "std::sequence" && ((_a2 = type.bases[0]) == null ? void 0 : _a2.id) === type.material_id) {
  77346. type.cast_type = ((_b = exports2.typeMapping.get(type.material_id)) == null ? void 0 : _b.id) ?? type.material_id;
  77347. }
  77348. break;
  77349. case "multirange":
  77350. type.multirange_element_id = ((_c = exports2.typeMapping.get(type.multirange_element_id)) == null ? void 0 : _c.id) ?? type.multirange_element_id;
  77351. break;
  77352. case "range":
  77353. type.range_element_id = ((_d = exports2.typeMapping.get(type.range_element_id)) == null ? void 0 : _d.id) ?? type.range_element_id;
  77354. break;
  77355. case "object": {
  77356. const ptrs = {};
  77357. for (const ptr of type.pointers) {
  77358. ptrs[ptr.name] = ptr;
  77359. }
  77360. const rawExclusives = type.exclusives;
  77361. const exclusives = [];
  77362. for (const ex of rawExclusives) {
  77363. const target = ex.target;
  77364. if (target in ptrs) {
  77365. exclusives.push({ [ex.target]: ptrs[ex.target] });
  77366. }
  77367. if (target[0] === "(" && target[target.length - 1] === ")") {
  77368. const targets = target.slice(1, -1).split(" ").map((t4) => {
  77369. t4 = t4.trim();
  77370. if (t4[0] === ".")
  77371. t4 = t4.slice(1);
  77372. if (t4[t4.length - 1] === ",")
  77373. t4 = t4.slice(0, -1);
  77374. return t4;
  77375. });
  77376. const newEx = {};
  77377. if (!targets.every((t4) => t4 in ptrs)) {
  77378. continue;
  77379. }
  77380. for (const t4 of targets) {
  77381. newEx[t4] = ptrs[t4];
  77382. }
  77383. exclusives.push(newEx);
  77384. }
  77385. }
  77386. type.exclusives = exclusives;
  77387. break;
  77388. }
  77389. }
  77390. }
  77391. _types.push(numberType2);
  77392. const types3 = topoSort(_types);
  77393. for (const [_3, type] of types3) {
  77394. if (type.kind === "object" && type.union_of.length) {
  77395. const unionTypes = type.union_of.map(({ id }) => {
  77396. const t4 = types3.get(id);
  77397. if (t4.kind !== "object") {
  77398. throw new Error(`type '${t4.name}' of union '${type.name}' is not an object type`);
  77399. }
  77400. return t4;
  77401. });
  77402. const [first, ...rest] = unionTypes;
  77403. const restPointerNames = rest.map((t4) => new Set(t4.pointers.map((p3) => p3.name)));
  77404. for (const pointer of first.pointers) {
  77405. if (restPointerNames.every((names) => names.has(pointer.name))) {
  77406. type.pointers.push(pointer);
  77407. }
  77408. }
  77409. type.backlinks = [];
  77410. type.backlink_stubs = [];
  77411. }
  77412. }
  77413. return types3;
  77414. }
  77415. function topoSort(types3) {
  77416. const graph = new strictMap_1.StrictMap();
  77417. const adj = new strictMap_1.StrictMap();
  77418. for (const type of types3) {
  77419. graph.set(type.id, type);
  77420. }
  77421. for (const type of types3) {
  77422. if (type.kind !== "object" && type.kind !== "scalar") {
  77423. continue;
  77424. }
  77425. for (const { id: base } of type.bases) {
  77426. if (!graph.has(base)) {
  77427. throw new Error(`reference to an unknown object type: ${base}`);
  77428. }
  77429. if (!adj.has(type.id)) {
  77430. adj.set(type.id, /* @__PURE__ */ new Set());
  77431. }
  77432. adj.get(type.id).add(base);
  77433. }
  77434. }
  77435. const visiting = /* @__PURE__ */ new Set();
  77436. const visited = /* @__PURE__ */ new Set();
  77437. const sorted = new strictMap_1.StrictMap();
  77438. const visit = (type) => {
  77439. if (visiting.has(type.name)) {
  77440. const last = Array.from(visiting).slice(1, 2);
  77441. throw new Error(`dependency cycle between ${type.name} and ${last}`);
  77442. }
  77443. if (!visited.has(type.id)) {
  77444. visiting.add(type.name);
  77445. if (adj.has(type.id)) {
  77446. for (const adjId of adj.get(type.id).values()) {
  77447. visit(graph.get(adjId));
  77448. }
  77449. }
  77450. sorted.set(type.id, type);
  77451. visited.add(type.id);
  77452. visiting.delete(type.name);
  77453. }
  77454. };
  77455. for (const type of types3) {
  77456. visit(type);
  77457. }
  77458. return sorted;
  77459. }
  77460. }
  77461. });
  77462. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/casts.js
  77463. var require_casts = __commonJS({
  77464. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/casts.js"(exports2) {
  77465. "use strict";
  77466. Object.defineProperty(exports2, "__esModule", { value: true });
  77467. exports2.casts = void 0;
  77468. var types_1 = require_types();
  77469. var reachableFrom = (source, adj, seen = /* @__PURE__ */ new Set()) => {
  77470. const reachable = /* @__PURE__ */ new Set();
  77471. if (seen.has(source))
  77472. return [];
  77473. seen.add(source);
  77474. (adj[source] || []).map((cast) => {
  77475. reachable.add(cast);
  77476. for (const item of reachableFrom(cast, adj, seen)) {
  77477. reachable.add(item);
  77478. }
  77479. });
  77480. return [...reachable];
  77481. };
  77482. var casts = async (cxn, params) => {
  77483. const allCastsRaw = await cxn.queryJSON(`WITH MODULE schema
  77484. SELECT Cast {
  77485. id,
  77486. source := .from_type { id, name },
  77487. target := .to_type { id, name },
  77488. allow_assignment,
  77489. allow_implicit,
  77490. }
  77491. FILTER .from_type IS ScalarType
  77492. AND .to_type IS ScalarType
  77493. # AND .from_type.is_abstract = false
  77494. # AND .to_type.is_abstract = false
  77495. `);
  77496. const allCasts = JSON.parse(allCastsRaw);
  77497. const types3 = /* @__PURE__ */ new Set();
  77498. const typesById = {};
  77499. const castsById = {};
  77500. const castsBySource = {};
  77501. const implicitCastsBySource = {};
  77502. const implicitCastsByTarget = {};
  77503. const assignmentCastsBySource = {};
  77504. const assignmentCastsByTarget = {};
  77505. for (const cast of allCasts) {
  77506. if (types_1.typeMapping.has(cast.source.id) || types_1.typeMapping.has(cast.target.id)) {
  77507. cast.allow_implicit = false;
  77508. cast.allow_assignment = false;
  77509. }
  77510. typesById[cast.source.id] = cast.source;
  77511. typesById[cast.target.id] = cast.target;
  77512. types3.add(cast.source.id);
  77513. types3.add(cast.target.id);
  77514. castsById[cast.id] = cast;
  77515. castsBySource[cast.source.id] = castsBySource[cast.source.id] || [];
  77516. castsBySource[cast.source.id].push(cast.target.id);
  77517. if (cast.allow_assignment || cast.allow_implicit) {
  77518. assignmentCastsBySource[cast.source.id] ??= [];
  77519. assignmentCastsBySource[cast.source.id].push(cast.target.id);
  77520. assignmentCastsByTarget[cast.target.id] ??= [];
  77521. assignmentCastsByTarget[cast.target.id].push(cast.source.id);
  77522. }
  77523. if (cast.allow_implicit) {
  77524. implicitCastsBySource[cast.source.id] ??= [];
  77525. implicitCastsBySource[cast.source.id].push(cast.target.id);
  77526. implicitCastsByTarget[cast.target.id] ??= [];
  77527. implicitCastsByTarget[cast.target.id].push(cast.source.id);
  77528. }
  77529. }
  77530. const castMap = {};
  77531. const implicitCastMap = {};
  77532. const implicitCastFromMap = {};
  77533. const assignmentCastMap = {};
  77534. const assignableByMap = {};
  77535. for (const type of [...types3]) {
  77536. castMap[type] = castsBySource[type] || [];
  77537. implicitCastMap[type] = reachableFrom(type, implicitCastsBySource);
  77538. implicitCastFromMap[type] = reachableFrom(type, implicitCastsByTarget);
  77539. assignmentCastMap[type] = reachableFrom(type, assignmentCastsBySource);
  77540. assignableByMap[type] = reachableFrom(type, assignmentCastsByTarget);
  77541. }
  77542. if ((params == null ? void 0 : params.debug) === true) {
  77543. console.log(`
  77544. IMPLICIT`);
  77545. for (const [fromId, castArr] of Object.entries(implicitCastMap)) {
  77546. console.log(`${typesById[fromId].name} implicitly castable to: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
  77547. }
  77548. console.log("");
  77549. for (const [fromId, castArr] of Object.entries(implicitCastFromMap)) {
  77550. console.log(`${typesById[fromId].name} implicitly castable from: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
  77551. }
  77552. console.log(`
  77553. ASSIGNABLE TO`);
  77554. for (const [fromId, castArr] of Object.entries(assignmentCastMap)) {
  77555. console.log(`${typesById[fromId].name} assignable to: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
  77556. }
  77557. console.log(`
  77558. ASSIGNABLE BY`);
  77559. for (const [fromId, castArr] of Object.entries(assignableByMap)) {
  77560. console.log(`${typesById[fromId].name} assignable by: [${castArr.map((id) => typesById[id].name).join(", ")}]`);
  77561. }
  77562. console.log(`
  77563. EXPLICIT`);
  77564. for (const [fromId, castArr] of Object.entries(castMap)) {
  77565. console.log(`${typesById[fromId].name} castable to: [${castArr.map((id) => {
  77566. return typesById[id].name;
  77567. }).join(", ")}]`);
  77568. }
  77569. }
  77570. return {
  77571. castsById,
  77572. typesById,
  77573. castMap,
  77574. implicitCastMap,
  77575. implicitCastFromMap,
  77576. assignmentCastMap,
  77577. assignableByMap
  77578. };
  77579. };
  77580. exports2.casts = casts;
  77581. }
  77582. });
  77583. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/functions.js
  77584. var require_functions = __commonJS({
  77585. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/functions.js"(exports2) {
  77586. "use strict";
  77587. Object.defineProperty(exports2, "__esModule", { value: true });
  77588. exports2.functions = void 0;
  77589. exports2.replaceNumberTypes = replaceNumberTypes;
  77590. var strictMap_1 = require_strictMap();
  77591. var types_1 = require_types();
  77592. var functions = async (cxn) => {
  77593. var _a2;
  77594. const functionsJson = await cxn.queryJSON(`
  77595. with module schema
  77596. select Function {
  77597. id,
  77598. name,
  77599. annotations: {
  77600. name,
  77601. @value
  77602. } filter .name = 'std::description',
  77603. return_type: {id, name},
  77604. return_typemod,
  77605. params: {
  77606. name,
  77607. type: {id, name},
  77608. kind,
  77609. typemod,
  77610. hasDefault := exists .default,
  77611. } order by @index,
  77612. preserves_optionality,
  77613. } filter .internal = false
  77614. `);
  77615. const functionMap = new strictMap_1.StrictMap();
  77616. const seenFuncDefHashes = /* @__PURE__ */ new Set();
  77617. for (const func of JSON.parse(functionsJson)) {
  77618. const { name } = func;
  77619. const funcDef = {
  77620. ...func,
  77621. description: (_a2 = func.annotations[0]) == null ? void 0 : _a2["@value"]
  77622. };
  77623. replaceNumberTypes(funcDef);
  77624. const hash = hashFuncDef(funcDef);
  77625. if (!seenFuncDefHashes.has(hash)) {
  77626. if (!functionMap.has(name)) {
  77627. functionMap.set(name, [funcDef]);
  77628. } else {
  77629. functionMap.get(name).push(funcDef);
  77630. }
  77631. seenFuncDefHashes.add(hash);
  77632. }
  77633. }
  77634. return functionMap;
  77635. };
  77636. exports2.functions = functions;
  77637. function replaceNumberTypes(def) {
  77638. if (types_1.typeMapping.has(def.return_type.id)) {
  77639. const type = types_1.typeMapping.get(def.return_type.id);
  77640. def.return_type = {
  77641. id: type.id,
  77642. name: type.name
  77643. };
  77644. }
  77645. for (const param of def.params) {
  77646. if (types_1.typeMapping.has(param.type.id)) {
  77647. const type = types_1.typeMapping.get(param.type.id);
  77648. param.type = {
  77649. id: type.id,
  77650. name: type.name
  77651. };
  77652. }
  77653. }
  77654. }
  77655. function hashFuncDef(def) {
  77656. return JSON.stringify({
  77657. name: def.name,
  77658. return_type: def.return_type.id,
  77659. return_typemod: def.return_typemod,
  77660. params: def.params.map((param) => JSON.stringify({
  77661. kind: param.kind,
  77662. type: param.type.id,
  77663. typemod: param.typemod,
  77664. hasDefault: !!param.hasDefault
  77665. })).sort(),
  77666. preserves_optionality: def.preserves_optionality
  77667. });
  77668. }
  77669. }
  77670. });
  77671. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/globals.js
  77672. var require_globals = __commonJS({
  77673. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/globals.js"(exports2) {
  77674. "use strict";
  77675. Object.defineProperty(exports2, "__esModule", { value: true });
  77676. exports2.globals = globals;
  77677. async function globals(cxn) {
  77678. const globalsMap = /* @__PURE__ */ new Map();
  77679. const version3 = await cxn.queryRequiredSingle(`select sys::get_version().major;`);
  77680. if (version3 === 1) {
  77681. return globalsMap;
  77682. }
  77683. const QUERY = `
  77684. WITH
  77685. MODULE schema
  77686. SELECT schema::Global {
  77687. id,
  77688. name,
  77689. target_id := .target.id,
  77690. card := ("One" IF .required ELSE "One" IF EXISTS .default ELSE "AtMostOne")
  77691. IF <str>.cardinality = "One" ELSE
  77692. ("AtLeastOne" IF .required ELSE "Many"),
  77693. has_default := exists .default,
  77694. }
  77695. ORDER BY .name;
  77696. `;
  77697. const allGlobals = JSON.parse(await cxn.queryJSON(QUERY));
  77698. for (const g3 of allGlobals) {
  77699. globalsMap.set(g3.id, g3);
  77700. }
  77701. return globalsMap;
  77702. }
  77703. }
  77704. });
  77705. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/operators.js
  77706. var require_operators = __commonJS({
  77707. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/operators.js"(exports2) {
  77708. "use strict";
  77709. Object.defineProperty(exports2, "__esModule", { value: true });
  77710. exports2.operators = void 0;
  77711. var strictMap_1 = require_strictMap();
  77712. var functions_1 = require_functions();
  77713. var util_1 = require_util3();
  77714. var _operators = async (cxn) => {
  77715. var _a2, _b;
  77716. const operatorsJson = await cxn.queryJSON(`
  77717. with module schema
  77718. select Operator {
  77719. id,
  77720. name,
  77721. annotations: {
  77722. name,
  77723. @value
  77724. } filter .name in {'std::identifier', 'std::description'},
  77725. operator_kind,
  77726. return_type: {id, name},
  77727. return_typemod,
  77728. params: {
  77729. name,
  77730. type: {id, name},
  77731. kind,
  77732. typemod,
  77733. } order by @index,
  77734. } filter not .internal and not .abstract
  77735. `);
  77736. const operators = new strictMap_1.StrictMap();
  77737. const seenOpDefHashes = /* @__PURE__ */ new Set();
  77738. for (const op of JSON.parse(operatorsJson)) {
  77739. const identifier = (_a2 = op.annotations.find((anno) => anno.name === "std::identifier")) == null ? void 0 : _a2["@value"];
  77740. if (!identifier) {
  77741. continue;
  77742. }
  77743. const { mod } = util_1.util.splitName(op.name);
  77744. const name = `${mod}::${identifier}`;
  77745. const opDef = {
  77746. ...op,
  77747. name,
  77748. kind: op.operator_kind,
  77749. originalName: op.name,
  77750. description: (_b = op.annotations.find((anno) => anno.name === "std::description")) == null ? void 0 : _b["@value"],
  77751. annotations: void 0
  77752. };
  77753. (0, functions_1.replaceNumberTypes)(opDef);
  77754. const hash = hashOpDef(opDef);
  77755. if (!seenOpDefHashes.has(hash)) {
  77756. if (!operators.has(name)) {
  77757. operators.set(name, [opDef]);
  77758. } else {
  77759. operators.get(name).push(opDef);
  77760. }
  77761. seenOpDefHashes.add(hash);
  77762. }
  77763. }
  77764. return operators;
  77765. };
  77766. exports2.operators = _operators;
  77767. function hashOpDef(def) {
  77768. return JSON.stringify({
  77769. name: def.name,
  77770. return_type: def.return_type.id,
  77771. return_typemod: def.return_typemod,
  77772. params: def.params.map((param) => JSON.stringify({
  77773. kind: param.kind,
  77774. type: param.type.id,
  77775. typemod: param.typemod,
  77776. hasDefault: !!param.hasDefault
  77777. })).sort(),
  77778. operator_kind: def.operator_kind
  77779. });
  77780. }
  77781. }
  77782. });
  77783. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/scalars.js
  77784. var require_scalars = __commonJS({
  77785. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries/scalars.js"(exports2) {
  77786. "use strict";
  77787. Object.defineProperty(exports2, "__esModule", { value: true });
  77788. exports2.scalars = void 0;
  77789. var strictMap_1 = require_strictMap();
  77790. var _scalars = async (cxn) => {
  77791. const scalarArray = await cxn.queryJSON(`with module schema
  77792. select InheritingObject {
  77793. id,
  77794. name,
  77795. is_abstract,
  77796. bases: { id, name },
  77797. ancestors: { id, name },
  77798. children := .<bases[IS Type] { id, name },
  77799. descendants := .<ancestors[IS Type] { id, name }
  77800. }
  77801. FILTER
  77802. InheritingObject IS ScalarType OR
  77803. InheritingObject IS ObjectType;
  77804. `);
  77805. const scalars = new strictMap_1.StrictMap();
  77806. for (const type of JSON.parse(scalarArray)) {
  77807. scalars.set(type.id, type);
  77808. }
  77809. return scalars;
  77810. };
  77811. exports2.scalars = _scalars;
  77812. }
  77813. });
  77814. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries.js
  77815. var require_queries = __commonJS({
  77816. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/queries.js"(exports2) {
  77817. "use strict";
  77818. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  77819. if (k22 === void 0) k22 = k3;
  77820. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  77821. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  77822. desc = { enumerable: true, get: function() {
  77823. return m4[k3];
  77824. } };
  77825. }
  77826. Object.defineProperty(o3, k22, desc);
  77827. } : function(o3, m4, k3, k22) {
  77828. if (k22 === void 0) k22 = k3;
  77829. o3[k22] = m4[k3];
  77830. });
  77831. var __exportStar2 = exports2 && exports2.__exportStar || function(m4, exports3) {
  77832. for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) __createBinding2(exports3, m4, p3);
  77833. };
  77834. Object.defineProperty(exports2, "__esModule", { value: true });
  77835. __exportStar2(require_casts(), exports2);
  77836. __exportStar2(require_functions(), exports2);
  77837. __exportStar2(require_globals(), exports2);
  77838. __exportStar2(require_operators(), exports2);
  77839. __exportStar2(require_scalars(), exports2);
  77840. __exportStar2(require_types(), exports2);
  77841. }
  77842. });
  77843. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/analyzeQuery.js
  77844. var require_analyzeQuery = __commonJS({
  77845. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/analyzeQuery.js"(exports2) {
  77846. "use strict";
  77847. Object.defineProperty(exports2, "__esModule", { value: true });
  77848. exports2.ImportMap = exports2.defaultApplyCardinalityToTsType = exports2.generateTsObjectField = exports2.generateTsObject = exports2.defaultCodecGenerators = exports2.defineCodecGeneratorTuple = exports2.generateTSTypeFromCodec = void 0;
  77849. exports2.analyzeQuery = analyzeQuery;
  77850. var array_1 = require_array();
  77851. var enum_1 = require_enum();
  77852. var ifaces_1 = require_ifaces();
  77853. var namedtuple_1 = require_namedtuple();
  77854. var object_1 = require_object();
  77855. var range_1 = require_range3();
  77856. var codecs_1 = require_codecs();
  77857. var set_1 = require_set();
  77858. var tuple_1 = require_tuple();
  77859. var enums_1 = require_enums();
  77860. var util_1 = require_util3();
  77861. async function analyzeQuery(client, query) {
  77862. const { cardinality, capabilities, in: inCodec, out: outCodec } = await client.describe(query);
  77863. const args = (0, exports2.generateTSTypeFromCodec)(inCodec, enums_1.Cardinality.One, {
  77864. optionalNulls: true,
  77865. readonly: true
  77866. });
  77867. const result = (0, exports2.generateTSTypeFromCodec)(outCodec, cardinality);
  77868. const imports = args.imports.merge(result.imports);
  77869. return {
  77870. result: result.type,
  77871. args: args.type,
  77872. cardinality,
  77873. capabilities,
  77874. query,
  77875. importMap: imports,
  77876. imports: imports.get("gel") ?? /* @__PURE__ */ new Set()
  77877. };
  77878. }
  77879. var generateTSTypeFromCodec = (codec, cardinality = enums_1.Cardinality.One, options = {}) => {
  77880. const optionsWithDefaults = {
  77881. indent: "",
  77882. optionalNulls: false,
  77883. readonly: false,
  77884. ...options
  77885. };
  77886. const context = {
  77887. ...optionsWithDefaults,
  77888. generators: exports2.defaultCodecGenerators,
  77889. applyCardinality: (0, exports2.defaultApplyCardinalityToTsType)(optionsWithDefaults),
  77890. ...options,
  77891. imports: new ImportMap(),
  77892. walk: (codec2, innerContext) => {
  77893. innerContext ??= context;
  77894. for (const [type2, generator] of innerContext.generators) {
  77895. if (codec2 instanceof type2) {
  77896. return generator(codec2, innerContext);
  77897. }
  77898. }
  77899. throw new Error(`Unexpected codec kind: ${codec2.getKind()}`);
  77900. }
  77901. };
  77902. const type = context.applyCardinality(context.walk(codec, context), cardinality);
  77903. return {
  77904. type,
  77905. imports: context.imports
  77906. };
  77907. };
  77908. exports2.generateTSTypeFromCodec = generateTSTypeFromCodec;
  77909. var genDef = (codecType, generator) => [codecType, generator];
  77910. exports2.defineCodecGeneratorTuple = genDef;
  77911. exports2.defaultCodecGenerators = new Map([
  77912. genDef(codecs_1.NullCodec, () => "null"),
  77913. genDef(enum_1.EnumCodec, (codec) => {
  77914. return `(${codec.values.map((val2) => JSON.stringify(val2)).join(" | ")})`;
  77915. }),
  77916. genDef(ifaces_1.ScalarCodec, (codec, ctx) => {
  77917. if (codec.tsModule) {
  77918. ctx.imports.add(codec.tsModule, codec.tsType);
  77919. }
  77920. return codec.tsType;
  77921. }),
  77922. genDef(object_1.ObjectCodec, (codec, ctx) => {
  77923. const subCodecs = codec.getSubcodecs();
  77924. const fields = codec.getFields().map((field, i4) => ({
  77925. name: field.name,
  77926. codec: subCodecs[i4],
  77927. cardinality: util_1.util.parseCardinality(field.cardinality)
  77928. }));
  77929. return (0, exports2.generateTsObject)(fields, ctx);
  77930. }),
  77931. genDef(namedtuple_1.NamedTupleCodec, (codec, ctx) => {
  77932. const subCodecs = codec.getSubcodecs();
  77933. const fields = codec.getNames().map((name, i4) => ({
  77934. name,
  77935. codec: subCodecs[i4],
  77936. cardinality: enums_1.Cardinality.One
  77937. }));
  77938. return (0, exports2.generateTsObject)(fields, ctx);
  77939. }),
  77940. genDef(tuple_1.TupleCodec, (codec, ctx) => {
  77941. const subCodecs = codec.getSubcodecs().map((subCodec) => ctx.walk(subCodec));
  77942. const tuple = `[${subCodecs.join(", ")}]`;
  77943. return ctx.readonly ? `(readonly ${tuple})` : tuple;
  77944. }),
  77945. genDef(array_1.ArrayCodec, (codec, ctx) => ctx.applyCardinality(ctx.walk(codec.getSubcodecs()[0]), enums_1.Cardinality.Many)),
  77946. genDef(range_1.RangeCodec, (codec, ctx) => {
  77947. const subCodec = codec.getSubcodecs()[0];
  77948. if (!(subCodec instanceof ifaces_1.ScalarCodec)) {
  77949. throw Error("expected range subtype to be scalar type");
  77950. }
  77951. ctx.imports.add(codec.tsModule, codec.tsType);
  77952. return `${codec.tsType}<${ctx.walk(subCodec)}>`;
  77953. }),
  77954. genDef(range_1.MultiRangeCodec, (codec, ctx) => {
  77955. const subCodec = codec.getSubcodecs()[0];
  77956. if (!(subCodec instanceof ifaces_1.ScalarCodec)) {
  77957. throw Error("expected multirange subtype to be scalar type");
  77958. }
  77959. ctx.imports.add(codec.tsModule, codec.tsType);
  77960. return `${codec.tsType}<${ctx.walk(subCodec)}>`;
  77961. })
  77962. ]);
  77963. var generateTsObject = (fields, ctx) => {
  77964. const properties = fields.map((field) => (0, exports2.generateTsObjectField)(field, ctx));
  77965. return `{
  77966. ${properties.join("\n")}
  77967. ${ctx.indent}}`;
  77968. };
  77969. exports2.generateTsObject = generateTsObject;
  77970. var generateTsObjectField = (field, ctx) => {
  77971. const codec = unwrapSetCodec(field.codec, field.cardinality);
  77972. const name = JSON.stringify(field.name);
  77973. const value = ctx.applyCardinality(ctx.walk(codec, { ...ctx, indent: ctx.indent + " " }), field.cardinality);
  77974. const optional = ctx.optionalNulls && field.cardinality === enums_1.Cardinality.AtMostOne;
  77975. const questionMark = optional ? "?" : "";
  77976. const isReadonly = ctx.readonly ? "readonly " : "";
  77977. return `${ctx.indent} ${isReadonly}${name}${questionMark}: ${value};`;
  77978. };
  77979. exports2.generateTsObjectField = generateTsObjectField;
  77980. function unwrapSetCodec(codec, cardinality) {
  77981. if (!(codec instanceof set_1.SetCodec)) {
  77982. return codec;
  77983. }
  77984. if (cardinality === enums_1.Cardinality.Many || cardinality === enums_1.Cardinality.AtLeastOne) {
  77985. return codec.getSubcodecs()[0];
  77986. }
  77987. throw new Error("Sub-codec is SetCodec, but upper cardinality is one");
  77988. }
  77989. var defaultApplyCardinalityToTsType = (ctx) => (type, cardinality) => {
  77990. switch (cardinality) {
  77991. case enums_1.Cardinality.Many:
  77992. return `${ctx.readonly ? "Readonly" : ""}Array<${type}>`;
  77993. case enums_1.Cardinality.One:
  77994. return type;
  77995. case enums_1.Cardinality.AtMostOne:
  77996. return `${type} | null`;
  77997. case enums_1.Cardinality.AtLeastOne: {
  77998. const tuple = `[(${type}), ...(${type})[]]`;
  77999. return ctx.readonly ? `(readonly ${tuple})` : tuple;
  78000. }
  78001. }
  78002. throw new Error(`Unexpected cardinality: ${cardinality}`);
  78003. };
  78004. exports2.defaultApplyCardinalityToTsType = defaultApplyCardinalityToTsType;
  78005. var ImportMap = class _ImportMap extends Map {
  78006. add(module3, specifier) {
  78007. if (!this.has(module3)) {
  78008. this.set(module3, /* @__PURE__ */ new Set());
  78009. }
  78010. this.get(module3).add(specifier);
  78011. return this;
  78012. }
  78013. merge(map2) {
  78014. const out = new _ImportMap();
  78015. for (const [mod, specifiers] of [...this, ...map2]) {
  78016. for (const specifier of specifiers) {
  78017. out.add(mod, specifier);
  78018. }
  78019. }
  78020. return out;
  78021. }
  78022. };
  78023. exports2.ImportMap = ImportMap;
  78024. }
  78025. });
  78026. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/index.js
  78027. var require_reflection = __commonJS({
  78028. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/reflection/index.js"(exports2) {
  78029. "use strict";
  78030. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  78031. if (k22 === void 0) k22 = k3;
  78032. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  78033. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  78034. desc = { enumerable: true, get: function() {
  78035. return m4[k3];
  78036. } };
  78037. }
  78038. Object.defineProperty(o3, k22, desc);
  78039. } : function(o3, m4, k3, k22) {
  78040. if (k22 === void 0) k22 = k3;
  78041. o3[k22] = m4[k3];
  78042. });
  78043. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  78044. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  78045. } : function(o3, v6) {
  78046. o3["default"] = v6;
  78047. });
  78048. var __exportStar2 = exports2 && exports2.__exportStar || function(m4, exports3) {
  78049. for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) __createBinding2(exports3, m4, p3);
  78050. };
  78051. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  78052. if (mod && mod.__esModule) return mod;
  78053. var result = {};
  78054. if (mod != null) {
  78055. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  78056. }
  78057. __setModuleDefault2(result, mod);
  78058. return result;
  78059. };
  78060. Object.defineProperty(exports2, "__esModule", { value: true });
  78061. exports2.Capabilities = exports2.introspect = void 0;
  78062. __exportStar2(require_enums(), exports2);
  78063. __exportStar2(require_util3(), exports2);
  78064. __exportStar2(require_typeutil(), exports2);
  78065. __exportStar2(require_util3(), exports2);
  78066. __exportStar2(require_strictMap(), exports2);
  78067. __exportStar2(require_reservedKeywords(), exports2);
  78068. exports2.introspect = __importStar2(require_queries());
  78069. __exportStar2(require_analyzeQuery(), exports2);
  78070. var baseConn_1 = require_baseConn();
  78071. Object.defineProperty(exports2, "Capabilities", { enumerable: true, get: function() {
  78072. return baseConn_1.Capabilities;
  78073. } });
  78074. }
  78075. });
  78076. // ../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.node.js
  78077. var require_index_node = __commonJS({
  78078. "../node_modules/.pnpm/gel@2.1.0/node_modules/gel/dist/index.node.js"(exports2) {
  78079. "use strict";
  78080. var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o3, m4, k3, k22) {
  78081. if (k22 === void 0) k22 = k3;
  78082. var desc = Object.getOwnPropertyDescriptor(m4, k3);
  78083. if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) {
  78084. desc = { enumerable: true, get: function() {
  78085. return m4[k3];
  78086. } };
  78087. }
  78088. Object.defineProperty(o3, k22, desc);
  78089. } : function(o3, m4, k3, k22) {
  78090. if (k22 === void 0) k22 = k3;
  78091. o3[k22] = m4[k3];
  78092. });
  78093. var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? function(o3, v6) {
  78094. Object.defineProperty(o3, "default", { enumerable: true, value: v6 });
  78095. } : function(o3, v6) {
  78096. o3["default"] = v6;
  78097. });
  78098. var __importStar2 = exports2 && exports2.__importStar || function(mod) {
  78099. if (mod && mod.__esModule) return mod;
  78100. var result = {};
  78101. if (mod != null) {
  78102. for (var k3 in mod) if (k3 !== "default" && Object.prototype.hasOwnProperty.call(mod, k3)) __createBinding2(result, mod, k3);
  78103. }
  78104. __setModuleDefault2(result, mod);
  78105. return result;
  78106. };
  78107. var __exportStar2 = exports2 && exports2.__exportStar || function(m4, exports3) {
  78108. for (var p3 in m4) if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p3)) __createBinding2(exports3, m4, p3);
  78109. };
  78110. Object.defineProperty(exports2, "__esModule", { value: true });
  78111. exports2.$ = exports2.Client = exports2.ResolvedConnectConfig = exports2._RawConnection = exports2.systemUtils = exports2.createHttpClient = exports2.createClient = void 0;
  78112. var nodeClient_1 = require_nodeClient();
  78113. exports2.default = nodeClient_1.createClient;
  78114. var nodeClient_2 = require_nodeClient();
  78115. Object.defineProperty(exports2, "createClient", { enumerable: true, get: function() {
  78116. return nodeClient_2.createClient;
  78117. } });
  78118. Object.defineProperty(exports2, "createHttpClient", { enumerable: true, get: function() {
  78119. return nodeClient_2.createHttpClient;
  78120. } });
  78121. var systemUtils = __importStar2(require_systemUtils());
  78122. exports2.systemUtils = systemUtils;
  78123. var rawConn_1 = require_rawConn();
  78124. Object.defineProperty(exports2, "_RawConnection", { enumerable: true, get: function() {
  78125. return rawConn_1.RawConnection;
  78126. } });
  78127. var conUtils_1 = require_conUtils();
  78128. Object.defineProperty(exports2, "ResolvedConnectConfig", { enumerable: true, get: function() {
  78129. return conUtils_1.ResolvedConnectConfig;
  78130. } });
  78131. var baseClient_1 = require_baseClient();
  78132. Object.defineProperty(exports2, "Client", { enumerable: true, get: function() {
  78133. return baseClient_1.Client;
  78134. } });
  78135. __exportStar2(require_index_shared(), exports2);
  78136. exports2.$ = __importStar2(require_reflection());
  78137. }
  78138. });
  78139. // src/cli/connections.ts
  78140. var connections_exports = {};
  78141. __export(connections_exports, {
  78142. connectToD1: () => connectToD1,
  78143. connectToLibSQL: () => connectToLibSQL,
  78144. connectToMySQL: () => connectToMySQL,
  78145. connectToSQLite: () => connectToSQLite,
  78146. connectToSingleStore: () => connectToSingleStore,
  78147. prepareGelDB: () => prepareGelDB,
  78148. preparePostgresDB: () => preparePostgresDB
  78149. });
  78150. var preparePostgresDB, prepareGelDB, parseSingleStoreCredentials, connectToSingleStore, parseMysqlCredentials, connectToMySQL, prepareSqliteParams, preparePGliteParams, connectToD1, connectToSQLite, connectToLibSQL;
  78151. var init_connections = __esm({
  78152. "src/cli/connections.ts"() {
  78153. "use strict";
  78154. init_src();
  78155. init_wrapper();
  78156. init_global();
  78157. init_utils2();
  78158. init_utils5();
  78159. init_outputs();
  78160. preparePostgresDB = async (credentials2) => {
  78161. if ("driver" in credentials2) {
  78162. const { driver: driver2 } = credentials2;
  78163. if (driver2 === "aws-data-api") {
  78164. assertPackages("@aws-sdk/client-rds-data");
  78165. const { RDSDataClient, ExecuteStatementCommand, TypeHint } = await Promise.resolve().then(() => __toESM(require_dist_cjs51()));
  78166. const { AwsDataApiSession, drizzle } = await import("drizzle-orm/aws-data-api/pg");
  78167. const { migrate: migrate2 } = await import("drizzle-orm/aws-data-api/pg/migrator");
  78168. const { PgDialect: PgDialect2 } = await import("drizzle-orm/pg-core");
  78169. const config = {
  78170. database: credentials2.database,
  78171. resourceArn: credentials2.resourceArn,
  78172. secretArn: credentials2.secretArn
  78173. };
  78174. const rdsClient = new RDSDataClient();
  78175. const session = new AwsDataApiSession(
  78176. rdsClient,
  78177. new PgDialect2(),
  78178. void 0,
  78179. config,
  78180. void 0
  78181. );
  78182. const db = drizzle(rdsClient, config);
  78183. const migrateFn = async (config2) => {
  78184. return migrate2(db, config2);
  78185. };
  78186. const query = async (sql, params) => {
  78187. const prepared = session.prepareQuery(
  78188. { sql, params: params ?? [] },
  78189. void 0,
  78190. void 0,
  78191. false
  78192. );
  78193. const result = await prepared.all();
  78194. return result;
  78195. };
  78196. const proxy = async (params) => {
  78197. const prepared = session.prepareQuery(
  78198. {
  78199. sql: params.sql,
  78200. params: params.params ?? [],
  78201. typings: params.typings
  78202. },
  78203. void 0,
  78204. void 0,
  78205. params.mode === "array"
  78206. );
  78207. if (params.mode === "array") {
  78208. const result2 = await prepared.values();
  78209. return result2.rows;
  78210. }
  78211. const result = await prepared.execute();
  78212. return result.rows;
  78213. };
  78214. const transactionProxy = async (queries) => {
  78215. throw new Error("Transaction not supported");
  78216. };
  78217. return {
  78218. packageName: "@aws-sdk/client-rds-data",
  78219. query,
  78220. proxy,
  78221. transactionProxy,
  78222. migrate: migrateFn
  78223. };
  78224. }
  78225. if (driver2 === "pglite") {
  78226. assertPackages("@electric-sql/pglite");
  78227. const { PGlite, types: types3 } = await import("@electric-sql/pglite");
  78228. const { drizzle } = await import("drizzle-orm/pglite");
  78229. const { migrate: migrate2 } = await import("drizzle-orm/pglite/migrator");
  78230. const pglite = "client" in credentials2 ? credentials2.client : new PGlite(normalisePGliteUrl(credentials2.url));
  78231. await pglite.waitReady;
  78232. const drzl = drizzle(pglite);
  78233. const migrateFn = async (config) => {
  78234. return migrate2(drzl, config);
  78235. };
  78236. const parsers = {
  78237. [types3.TIMESTAMP]: (value) => value,
  78238. [types3.TIMESTAMPTZ]: (value) => value,
  78239. [types3.INTERVAL]: (value) => value,
  78240. [types3.DATE]: (value) => value
  78241. };
  78242. const query = async (sql, params = []) => {
  78243. const result = await pglite.query(sql, params, {
  78244. parsers
  78245. });
  78246. return result.rows;
  78247. };
  78248. const proxy = async (params) => {
  78249. const preparedParams = preparePGliteParams(params.params || []);
  78250. const result = await pglite.query(params.sql, preparedParams, {
  78251. rowMode: params.mode,
  78252. parsers
  78253. });
  78254. return result.rows;
  78255. };
  78256. const transactionProxy = async (queries) => {
  78257. const results = [];
  78258. try {
  78259. await pglite.transaction(async (tx) => {
  78260. for (const query2 of queries) {
  78261. const result = await tx.query(query2.sql, void 0, {
  78262. parsers
  78263. });
  78264. results.push(result.rows);
  78265. }
  78266. });
  78267. } catch (error2) {
  78268. results.push(error2);
  78269. }
  78270. return results;
  78271. };
  78272. return { packageName: "pglite", query, proxy, transactionProxy, migrate: migrateFn };
  78273. }
  78274. assertUnreachable(driver2);
  78275. }
  78276. if (await checkPackage("pg")) {
  78277. console.log(withStyle.info(`Using 'pg' driver for database querying`));
  78278. const { default: pg } = await import("pg");
  78279. const { drizzle } = await import("drizzle-orm/node-postgres");
  78280. const { migrate: migrate2 } = await import("drizzle-orm/node-postgres/migrator");
  78281. const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
  78282. const types3 = {
  78283. // @ts-ignore
  78284. getTypeParser: (typeId, format) => {
  78285. if (typeId === pg.types.builtins.TIMESTAMPTZ) {
  78286. return (val2) => val2;
  78287. }
  78288. if (typeId === pg.types.builtins.TIMESTAMP) {
  78289. return (val2) => val2;
  78290. }
  78291. if (typeId === pg.types.builtins.DATE) {
  78292. return (val2) => val2;
  78293. }
  78294. if (typeId === pg.types.builtins.INTERVAL) {
  78295. return (val2) => val2;
  78296. }
  78297. return pg.types.getTypeParser(typeId, format);
  78298. }
  78299. };
  78300. const client = "url" in credentials2 ? new pg.Pool({ connectionString: credentials2.url, max: 1 }) : new pg.Pool({ ...credentials2, ssl, max: 1 });
  78301. const db = drizzle(client);
  78302. const migrateFn = async (config) => {
  78303. return migrate2(db, config);
  78304. };
  78305. const query = async (sql, params) => {
  78306. const result = await client.query({
  78307. text: sql,
  78308. values: params ?? [],
  78309. types: types3
  78310. });
  78311. return result.rows;
  78312. };
  78313. const proxy = async (params) => {
  78314. const result = await client.query({
  78315. text: params.sql,
  78316. values: params.params,
  78317. ...params.mode === "array" && { rowMode: "array" },
  78318. types: types3
  78319. });
  78320. return result.rows;
  78321. };
  78322. const transactionProxy = async (queries) => {
  78323. const results = [];
  78324. const tx = await client.connect();
  78325. try {
  78326. await tx.query("BEGIN");
  78327. for (const query2 of queries) {
  78328. const result = await tx.query({
  78329. text: query2.sql,
  78330. types: types3
  78331. });
  78332. results.push(result.rows);
  78333. }
  78334. await tx.query("COMMIT");
  78335. } catch (error2) {
  78336. await tx.query("ROLLBACK");
  78337. results.push(error2);
  78338. } finally {
  78339. tx.release();
  78340. }
  78341. return results;
  78342. };
  78343. return { packageName: "pg", query, proxy, transactionProxy, migrate: migrateFn };
  78344. }
  78345. if (await checkPackage("postgres")) {
  78346. console.log(
  78347. withStyle.info(`Using 'postgres' driver for database querying`)
  78348. );
  78349. const postgres = await import("postgres");
  78350. const { drizzle } = await import("drizzle-orm/postgres-js");
  78351. const { migrate: migrate2 } = await import("drizzle-orm/postgres-js/migrator");
  78352. const client = "url" in credentials2 ? postgres.default(credentials2.url, { max: 1 }) : postgres.default({ ...credentials2, max: 1 });
  78353. const transparentParser = (val2) => val2;
  78354. for (const type of ["1184", "1082", "1083", "1114"]) {
  78355. client.options.parsers[type] = transparentParser;
  78356. client.options.serializers[type] = transparentParser;
  78357. }
  78358. client.options.serializers["114"] = transparentParser;
  78359. client.options.serializers["3802"] = transparentParser;
  78360. const db = drizzle(client);
  78361. const migrateFn = async (config) => {
  78362. return migrate2(db, config);
  78363. };
  78364. const query = async (sql, params) => {
  78365. const result = await client.unsafe(sql, params ?? []);
  78366. return result;
  78367. };
  78368. const proxy = async (params) => {
  78369. if (params.mode === "array") {
  78370. return await client.unsafe(params.sql, params.params).values();
  78371. }
  78372. return await client.unsafe(params.sql, params.params);
  78373. };
  78374. const transactionProxy = async (queries) => {
  78375. const results = [];
  78376. try {
  78377. await client.begin(async (sql) => {
  78378. for (const query2 of queries) {
  78379. const result = await sql.unsafe(query2.sql);
  78380. results.push(result);
  78381. }
  78382. });
  78383. } catch (error2) {
  78384. results.push(error2);
  78385. }
  78386. return results;
  78387. };
  78388. return { packageName: "postgres", query, proxy, transactionProxy, migrate: migrateFn };
  78389. }
  78390. if (await checkPackage("@vercel/postgres")) {
  78391. console.log(
  78392. withStyle.info(`Using '@vercel/postgres' driver for database querying`)
  78393. );
  78394. console.log(
  78395. withStyle.fullWarning(
  78396. "'@vercel/postgres' can only connect to remote Neon/Vercel Postgres/Supabase instances through a websocket"
  78397. )
  78398. );
  78399. const { VercelPool, types: pgTypes } = await import("@vercel/postgres");
  78400. const { drizzle } = await import("drizzle-orm/vercel-postgres");
  78401. const { migrate: migrate2 } = await import("drizzle-orm/vercel-postgres/migrator");
  78402. const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
  78403. const types3 = {
  78404. // @ts-ignore
  78405. getTypeParser: (typeId, format) => {
  78406. if (typeId === pgTypes.builtins.TIMESTAMPTZ) {
  78407. return (val2) => val2;
  78408. }
  78409. if (typeId === pgTypes.builtins.TIMESTAMP) {
  78410. return (val2) => val2;
  78411. }
  78412. if (typeId === pgTypes.builtins.DATE) {
  78413. return (val2) => val2;
  78414. }
  78415. if (typeId === pgTypes.builtins.INTERVAL) {
  78416. return (val2) => val2;
  78417. }
  78418. return pgTypes.getTypeParser(typeId, format);
  78419. }
  78420. };
  78421. const client = "url" in credentials2 ? new VercelPool({ connectionString: credentials2.url }) : new VercelPool({ ...credentials2, ssl });
  78422. await client.connect();
  78423. const db = drizzle(client);
  78424. const migrateFn = async (config) => {
  78425. return migrate2(db, config);
  78426. };
  78427. const query = async (sql, params) => {
  78428. const result = await client.query({
  78429. text: sql,
  78430. values: params ?? [],
  78431. types: types3
  78432. });
  78433. return result.rows;
  78434. };
  78435. const proxy = async (params) => {
  78436. const result = await client.query({
  78437. text: params.sql,
  78438. values: params.params,
  78439. ...params.mode === "array" && { rowMode: "array" },
  78440. types: types3
  78441. });
  78442. return result.rows;
  78443. };
  78444. const transactionProxy = async (queries) => {
  78445. const results = [];
  78446. const tx = await client.connect();
  78447. try {
  78448. await tx.query("BEGIN");
  78449. for (const query2 of queries) {
  78450. const result = await tx.query({
  78451. text: query2.sql,
  78452. types: types3
  78453. });
  78454. results.push(result.rows);
  78455. }
  78456. await tx.query("COMMIT");
  78457. } catch (error2) {
  78458. await tx.query("ROLLBACK");
  78459. results.push(error2);
  78460. } finally {
  78461. tx.release();
  78462. }
  78463. return results;
  78464. };
  78465. return { packageName: "@vercel/postgres", query, proxy, transactionProxy, migrate: migrateFn };
  78466. }
  78467. if (await checkPackage("@neondatabase/serverless")) {
  78468. console.log(
  78469. withStyle.info(
  78470. `Using '@neondatabase/serverless' driver for database querying`
  78471. )
  78472. );
  78473. console.log(
  78474. withStyle.fullWarning(
  78475. "'@neondatabase/serverless' can only connect to remote Neon/Vercel Postgres/Supabase instances through a websocket"
  78476. )
  78477. );
  78478. const { Pool, neonConfig, types: pgTypes } = await import("@neondatabase/serverless");
  78479. const { drizzle } = await import("drizzle-orm/neon-serverless");
  78480. const { migrate: migrate2 } = await import("drizzle-orm/neon-serverless/migrator");
  78481. const ssl = "ssl" in credentials2 ? credentials2.ssl === "prefer" || credentials2.ssl === "require" || credentials2.ssl === "allow" ? { rejectUnauthorized: false } : credentials2.ssl === "verify-full" ? {} : credentials2.ssl : {};
  78482. const types3 = {
  78483. // @ts-ignore
  78484. getTypeParser: (typeId, format) => {
  78485. if (typeId === pgTypes.builtins.TIMESTAMPTZ) {
  78486. return (val2) => val2;
  78487. }
  78488. if (typeId === pgTypes.builtins.TIMESTAMP) {
  78489. return (val2) => val2;
  78490. }
  78491. if (typeId === pgTypes.builtins.DATE) {
  78492. return (val2) => val2;
  78493. }
  78494. if (typeId === pgTypes.builtins.INTERVAL) {
  78495. return (val2) => val2;
  78496. }
  78497. return pgTypes.getTypeParser(typeId, format);
  78498. }
  78499. };
  78500. const client = "url" in credentials2 ? new Pool({ connectionString: credentials2.url, max: 1 }) : new Pool({ ...credentials2, max: 1, ssl });
  78501. neonConfig.webSocketConstructor = wrapper_default;
  78502. const db = drizzle(client);
  78503. const migrateFn = async (config) => {
  78504. return migrate2(db, config);
  78505. };
  78506. const query = async (sql, params) => {
  78507. const result = await client.query({
  78508. text: sql,
  78509. values: params ?? [],
  78510. types: types3
  78511. });
  78512. return result.rows;
  78513. };
  78514. const proxy = async (params) => {
  78515. const result = await client.query({
  78516. text: params.sql,
  78517. values: params.params,
  78518. ...params.mode === "array" && { rowMode: "array" },
  78519. types: types3
  78520. });
  78521. return result.rows;
  78522. };
  78523. const transactionProxy = async (queries) => {
  78524. const results = [];
  78525. const tx = await client.connect();
  78526. try {
  78527. await tx.query("BEGIN");
  78528. for (const query2 of queries) {
  78529. const result = await tx.query({
  78530. text: query2.sql,
  78531. types: types3
  78532. });
  78533. results.push(result.rows);
  78534. }
  78535. await tx.query("COMMIT");
  78536. } catch (error2) {
  78537. await tx.query("ROLLBACK");
  78538. results.push(error2);
  78539. } finally {
  78540. tx.release();
  78541. }
  78542. return results;
  78543. };
  78544. return { packageName: "@neondatabase/serverless", query, proxy, transactionProxy, migrate: migrateFn };
  78545. }
  78546. console.error(
  78547. "To connect to Postgres database - please install either of 'pg', 'postgres', '@neondatabase/serverless' or '@vercel/postgres' drivers"
  78548. );
  78549. process.exit(1);
  78550. };
  78551. prepareGelDB = async (credentials2) => {
  78552. if (await checkPackage("gel")) {
  78553. const gel = await Promise.resolve().then(() => __toESM(require_index_node()));
  78554. let client;
  78555. if (!credentials2) {
  78556. client = gel.createClient();
  78557. try {
  78558. await client.querySQL(`select 1;`);
  78559. } catch (error2) {
  78560. if (error2 instanceof gel.ClientConnectionError) {
  78561. console.error(
  78562. `It looks like you forgot to link the Gel project or provide the database credentials.
  78563. To link your project, please refer https://docs.geldata.com/reference/cli/gel_instance/gel_instance_link, or add the dbCredentials to your configuration file.`
  78564. );
  78565. process.exit(1);
  78566. }
  78567. throw error2;
  78568. }
  78569. } else if ("url" in credentials2) {
  78570. "tlsSecurity" in credentials2 ? client = gel.createClient({ dsn: credentials2.url, tlsSecurity: credentials2.tlsSecurity, concurrency: 1 }) : client = gel.createClient({ dsn: credentials2.url, concurrency: 1 });
  78571. } else {
  78572. gel.createClient({ ...credentials2, concurrency: 1 });
  78573. }
  78574. const query = async (sql, params) => {
  78575. const result = (params == null ? void 0 : params.length) ? await client.querySQL(sql, params) : await client.querySQL(sql);
  78576. return result;
  78577. };
  78578. const proxy = async (params) => {
  78579. const { method, mode, params: sqlParams, sql, typings } = params;
  78580. let result;
  78581. switch (mode) {
  78582. case "array":
  78583. result = (sqlParams == null ? void 0 : sqlParams.length) ? await client.withSQLRowMode("array").querySQL(sql, sqlParams) : await client.withSQLRowMode("array").querySQL(sql);
  78584. break;
  78585. case "object":
  78586. result = (sqlParams == null ? void 0 : sqlParams.length) ? await client.querySQL(sql, sqlParams) : await client.querySQL(sql);
  78587. break;
  78588. }
  78589. return result;
  78590. };
  78591. const transactionProxy = async (queries) => {
  78592. const result = [];
  78593. try {
  78594. await client.transaction(async (tx) => {
  78595. for (const query2 of queries) {
  78596. const res = await tx.querySQL(query2.sql);
  78597. result.push(res);
  78598. }
  78599. });
  78600. } catch (error2) {
  78601. result.push(error2);
  78602. }
  78603. return result;
  78604. };
  78605. return { packageName: "gel", query, proxy, transactionProxy };
  78606. }
  78607. console.error(
  78608. "To connect to gel database - please install 'edgedb' driver"
  78609. );
  78610. process.exit(1);
  78611. };
  78612. parseSingleStoreCredentials = (credentials2) => {
  78613. if ("url" in credentials2) {
  78614. const url = credentials2.url;
  78615. const connectionUrl = new URL(url);
  78616. const pathname = connectionUrl.pathname;
  78617. const database = pathname.split("/")[pathname.split("/").length - 1];
  78618. if (!database) {
  78619. console.error(
  78620. "You should specify a database name in connection string (singlestore://USER:PASSWORD@HOST:PORT/DATABASE)"
  78621. );
  78622. process.exit(1);
  78623. }
  78624. return { database, url };
  78625. } else {
  78626. return {
  78627. database: credentials2.database,
  78628. credentials: credentials2
  78629. };
  78630. }
  78631. };
  78632. connectToSingleStore = async (it) => {
  78633. const result = parseSingleStoreCredentials(it);
  78634. if (await checkPackage("mysql2")) {
  78635. const { createConnection } = await import("mysql2/promise");
  78636. const { drizzle } = await import("drizzle-orm/singlestore");
  78637. const { migrate: migrate2 } = await import("drizzle-orm/singlestore/migrator");
  78638. const connection = result.url ? await createConnection(result.url) : await createConnection(result.credentials);
  78639. const db = drizzle(connection);
  78640. const migrateFn = async (config) => {
  78641. return migrate2(db, config);
  78642. };
  78643. await connection.connect();
  78644. const query = async (sql, params) => {
  78645. const res = await connection.execute(sql, params);
  78646. return res[0];
  78647. };
  78648. const proxy = async (params) => {
  78649. const result2 = await connection.query({
  78650. sql: params.sql,
  78651. values: params.params,
  78652. rowsAsArray: params.mode === "array"
  78653. });
  78654. return result2[0];
  78655. };
  78656. const transactionProxy = async (queries) => {
  78657. const results = [];
  78658. try {
  78659. await connection.beginTransaction();
  78660. for (const query2 of queries) {
  78661. const res = await connection.query(query2.sql);
  78662. results.push(res[0]);
  78663. }
  78664. await connection.commit();
  78665. } catch (error2) {
  78666. await connection.rollback();
  78667. results.push(error2);
  78668. }
  78669. return results;
  78670. };
  78671. return {
  78672. db: { query },
  78673. packageName: "mysql2",
  78674. proxy,
  78675. transactionProxy,
  78676. database: result.database,
  78677. migrate: migrateFn
  78678. };
  78679. }
  78680. console.error(
  78681. "To connect to SingleStore database - please install 'mysql2' driver"
  78682. );
  78683. process.exit(1);
  78684. };
  78685. parseMysqlCredentials = (credentials2) => {
  78686. if ("url" in credentials2) {
  78687. const url = credentials2.url;
  78688. const connectionUrl = new URL(url);
  78689. const pathname = connectionUrl.pathname;
  78690. const database = pathname.split("/")[pathname.split("/").length - 1];
  78691. if (!database) {
  78692. console.error(
  78693. "You should specify a database name in connection string (mysql://USER:PASSWORD@HOST:PORT/DATABASE)"
  78694. );
  78695. process.exit(1);
  78696. }
  78697. return { database, url };
  78698. } else {
  78699. return {
  78700. database: credentials2.database,
  78701. credentials: credentials2
  78702. };
  78703. }
  78704. };
  78705. connectToMySQL = async (it) => {
  78706. const result = parseMysqlCredentials(it);
  78707. if (await checkPackage("mysql2")) {
  78708. const { createConnection } = await import("mysql2/promise");
  78709. const { drizzle } = await import("drizzle-orm/mysql2");
  78710. const { migrate: migrate2 } = await import("drizzle-orm/mysql2/migrator");
  78711. const connection = result.url ? await createConnection(result.url) : await createConnection(result.credentials);
  78712. const db = drizzle(connection);
  78713. const migrateFn = async (config) => {
  78714. return migrate2(db, config);
  78715. };
  78716. const typeCast = (field, next) => {
  78717. if (field.type === "TIMESTAMP" || field.type === "DATETIME" || field.type === "DATE") {
  78718. return field.string();
  78719. }
  78720. return next();
  78721. };
  78722. await connection.connect();
  78723. const query = async (sql, params) => {
  78724. const res = await connection.execute({
  78725. sql,
  78726. values: params,
  78727. typeCast
  78728. });
  78729. return res[0];
  78730. };
  78731. const proxy = async (params) => {
  78732. const result2 = await connection.query({
  78733. sql: params.sql,
  78734. values: params.params,
  78735. rowsAsArray: params.mode === "array",
  78736. typeCast
  78737. });
  78738. return result2[0];
  78739. };
  78740. const transactionProxy = async (queries) => {
  78741. const results = [];
  78742. try {
  78743. await connection.beginTransaction();
  78744. for (const query2 of queries) {
  78745. const res = await connection.query(query2.sql);
  78746. results.push(res[0]);
  78747. }
  78748. await connection.commit();
  78749. } catch (error2) {
  78750. await connection.rollback();
  78751. results.push(error2);
  78752. }
  78753. return results;
  78754. };
  78755. return {
  78756. db: { query },
  78757. packageName: "mysql2",
  78758. proxy,
  78759. transactionProxy,
  78760. database: result.database,
  78761. migrate: migrateFn
  78762. };
  78763. }
  78764. if (await checkPackage("@planetscale/database")) {
  78765. const { Client } = await import("@planetscale/database");
  78766. const { drizzle } = await import("drizzle-orm/planetscale-serverless");
  78767. const { migrate: migrate2 } = await import("drizzle-orm/planetscale-serverless/migrator");
  78768. const connection = new Client(result);
  78769. const db = drizzle(connection);
  78770. const migrateFn = async (config) => {
  78771. return migrate2(db, config);
  78772. };
  78773. const query = async (sql, params) => {
  78774. const res = await connection.execute(sql, params);
  78775. return res.rows;
  78776. };
  78777. const proxy = async (params) => {
  78778. const result2 = await connection.execute(
  78779. params.sql,
  78780. params.params,
  78781. params.mode === "array" ? { as: "array" } : void 0
  78782. );
  78783. return result2.rows;
  78784. };
  78785. const transactionProxy = async (queries) => {
  78786. const results = [];
  78787. try {
  78788. await connection.transaction(async (tx) => {
  78789. for (const query2 of queries) {
  78790. const res = await tx.execute(query2.sql);
  78791. results.push(res.rows);
  78792. }
  78793. });
  78794. } catch (error2) {
  78795. results.push(error2);
  78796. }
  78797. return results;
  78798. };
  78799. return {
  78800. db: { query },
  78801. packageName: "@planetscale/database",
  78802. proxy,
  78803. transactionProxy,
  78804. database: result.database,
  78805. migrate: migrateFn
  78806. };
  78807. }
  78808. console.error(
  78809. "To connect to MySQL database - please install either of 'mysql2' or '@planetscale/database' drivers"
  78810. );
  78811. process.exit(1);
  78812. };
  78813. prepareSqliteParams = (params, driver2) => {
  78814. return params.map((param) => {
  78815. if (param && typeof param === "object" && "type" in param && "value" in param && param.type === "binary") {
  78816. const value = typeof param.value === "object" ? JSON.stringify(param.value) : param.value;
  78817. if (driver2 === "d1-http" || driver2 === "d1") {
  78818. return value;
  78819. }
  78820. return Buffer.from(value);
  78821. }
  78822. return param;
  78823. });
  78824. };
  78825. preparePGliteParams = (params) => {
  78826. return params.map((param) => {
  78827. if (param && typeof param === "object" && "type" in param && "value" in param && param.type === "binary") {
  78828. const value = typeof param.value === "object" ? JSON.stringify(param.value) : param.value;
  78829. return value;
  78830. }
  78831. return param;
  78832. });
  78833. };
  78834. connectToD1 = async (d1) => {
  78835. const db = {
  78836. query: async (sql, params) => {
  78837. const stmt = d1.prepare(sql);
  78838. const boundStmt = params && params.length > 0 ? stmt.bind(...params) : stmt;
  78839. const result = await boundStmt.all();
  78840. return result.results ?? [];
  78841. },
  78842. run: async (query) => {
  78843. const stmt = d1.prepare(query);
  78844. await stmt.run();
  78845. }
  78846. };
  78847. const proxy = async (params) => {
  78848. var _a2, _b;
  78849. const preparedParams = prepareSqliteParams(params.params || [], "d1");
  78850. const stmt = d1.prepare(params.sql);
  78851. const boundStmt = preparedParams.length > 0 ? stmt.bind(...preparedParams) : stmt;
  78852. try {
  78853. if (params.mode === "array") {
  78854. return await boundStmt.raw();
  78855. }
  78856. const result = await boundStmt.all();
  78857. return result.results ?? [];
  78858. } catch (error2) {
  78859. if (((_a2 = error2 == null ? void 0 : error2.message) == null ? void 0 : _a2.includes("SQLITE_AUTH")) || ((_b = error2 == null ? void 0 : error2.message) == null ? void 0 : _b.includes("not authorized"))) {
  78860. return [];
  78861. }
  78862. throw error2;
  78863. }
  78864. };
  78865. const transactionProxy = async (queries) => {
  78866. const results = [];
  78867. try {
  78868. const statements = queries.map((q3) => d1.prepare(q3.sql));
  78869. const batchResults = await d1.batch(statements);
  78870. for (const result of batchResults) {
  78871. results.push(result.results ?? []);
  78872. }
  78873. } catch (error2) {
  78874. results.push(error2);
  78875. }
  78876. return results;
  78877. };
  78878. const { drizzle } = await import("drizzle-orm/d1");
  78879. const { migrate: migrate2 } = await import("drizzle-orm/d1/migrator");
  78880. const drzl = drizzle(d1);
  78881. const migrateFn = async (config) => {
  78882. return migrate2(drzl, config);
  78883. };
  78884. return { ...db, packageName: "d1", proxy, transactionProxy, migrate: migrateFn };
  78885. };
  78886. connectToSQLite = async (credentials2) => {
  78887. if ("driver" in credentials2) {
  78888. const { driver: driver2 } = credentials2;
  78889. if (driver2 === "d1-http") {
  78890. const { drizzle } = await import("drizzle-orm/sqlite-proxy");
  78891. const { migrate: migrate2 } = await import("drizzle-orm/sqlite-proxy/migrator");
  78892. const remoteCallback = async (sql, params, method) => {
  78893. const res = await fetch2(
  78894. `https://api.cloudflare.com/client/v4/accounts/${credentials2.accountId}/d1/database/${credentials2.databaseId}/${method === "values" ? "raw" : "query"}`,
  78895. {
  78896. method: "POST",
  78897. body: JSON.stringify({ sql, params }),
  78898. headers: {
  78899. "Content-Type": "application/json",
  78900. Authorization: `Bearer ${credentials2.token}`
  78901. }
  78902. }
  78903. );
  78904. const data = await res.json();
  78905. if (!data.success) {
  78906. throw new Error(
  78907. data.errors.map((it) => `${it.code}: ${it.message}`).join("\n")
  78908. );
  78909. }
  78910. const result = data.result[0].results;
  78911. const rows = Array.isArray(result) ? result : result.rows;
  78912. return {
  78913. rows
  78914. };
  78915. };
  78916. const remoteBatchCallback = async (queries) => {
  78917. const sql = queries.map((q3) => q3.sql).join("; ");
  78918. const res = await fetch2(
  78919. `https://api.cloudflare.com/client/v4/accounts/${credentials2.accountId}/d1/database/${credentials2.databaseId}/query`,
  78920. {
  78921. method: "POST",
  78922. body: JSON.stringify({ sql }),
  78923. headers: {
  78924. "Content-Type": "application/json",
  78925. Authorization: `Bearer ${credentials2.token}`
  78926. }
  78927. }
  78928. );
  78929. const data = await res.json();
  78930. if (!data.success) {
  78931. throw new Error(
  78932. data.errors.map((it) => `${it.code}: ${it.message}`).join("\n")
  78933. );
  78934. }
  78935. const rows = data.result.map((result) => {
  78936. const res2 = result.results;
  78937. return Array.isArray(res2) ? res2 : res2.rows;
  78938. });
  78939. return {
  78940. rows
  78941. };
  78942. };
  78943. const drzl = drizzle(remoteCallback);
  78944. const migrateFn = async (config) => {
  78945. return migrate2(
  78946. drzl,
  78947. async (queries) => {
  78948. for (const query of queries) {
  78949. await remoteCallback(query, [], "run");
  78950. }
  78951. },
  78952. config
  78953. );
  78954. };
  78955. const db = {
  78956. query: async (sql, params) => {
  78957. const res = await remoteCallback(sql, params || [], "all");
  78958. return res.rows;
  78959. },
  78960. run: async (query) => {
  78961. await remoteCallback(query, [], "run");
  78962. }
  78963. };
  78964. const proxy = async (params) => {
  78965. const preparedParams = prepareSqliteParams(params.params || [], "d1-http");
  78966. const result = await remoteCallback(
  78967. params.sql,
  78968. preparedParams,
  78969. params.mode === "array" ? "values" : "all"
  78970. );
  78971. return result.rows;
  78972. };
  78973. const transactionProxy = async (queries) => {
  78974. const result = await remoteBatchCallback(queries);
  78975. return result.rows;
  78976. };
  78977. return { ...db, packageName: "d1-http", proxy, transactionProxy, migrate: migrateFn };
  78978. } else {
  78979. assertUnreachable(driver2);
  78980. }
  78981. }
  78982. if (await checkPackage("@libsql/client")) {
  78983. const { createClient } = await import("@libsql/client");
  78984. const { drizzle } = await import("drizzle-orm/libsql");
  78985. const { migrate: migrate2 } = await import("drizzle-orm/libsql/migrator");
  78986. const client = createClient({
  78987. url: normaliseSQLiteUrl(credentials2.url, "libsql")
  78988. });
  78989. const drzl = drizzle(client);
  78990. const migrateFn = async (config) => {
  78991. return migrate2(drzl, config);
  78992. };
  78993. const db = {
  78994. query: async (sql, params) => {
  78995. const res = await client.execute({ sql, args: params || [] });
  78996. return res.rows;
  78997. },
  78998. run: async (query) => {
  78999. await client.execute(query);
  79000. }
  79001. };
  79002. const proxy = async (params) => {
  79003. const preparedParams = prepareSqliteParams(params.params || []);
  79004. const result = await client.execute({
  79005. sql: params.sql,
  79006. args: preparedParams
  79007. });
  79008. if (params.mode === "array") {
  79009. return result.rows.map((row) => Object.values(row));
  79010. } else {
  79011. return result.rows;
  79012. }
  79013. };
  79014. const transactionProxy = async (queries) => {
  79015. const results = [];
  79016. let transaction = null;
  79017. try {
  79018. transaction = await client.transaction();
  79019. for (const query of queries) {
  79020. const result = await transaction.execute(query.sql);
  79021. results.push(result.rows);
  79022. }
  79023. await transaction.commit();
  79024. } catch (error2) {
  79025. results.push(error2);
  79026. await (transaction == null ? void 0 : transaction.rollback());
  79027. } finally {
  79028. transaction == null ? void 0 : transaction.close();
  79029. }
  79030. return results;
  79031. };
  79032. return { ...db, packageName: "@libsql/client", proxy, transactionProxy, migrate: migrateFn };
  79033. }
  79034. if (await checkPackage("better-sqlite3")) {
  79035. const { default: Database } = await import("better-sqlite3");
  79036. const { drizzle } = await import("drizzle-orm/better-sqlite3");
  79037. const { migrate: migrate2 } = await import("drizzle-orm/better-sqlite3/migrator");
  79038. const sqlite = new Database(
  79039. normaliseSQLiteUrl(credentials2.url, "better-sqlite")
  79040. );
  79041. const drzl = drizzle(sqlite);
  79042. const migrateFn = async (config) => {
  79043. return migrate2(drzl, config);
  79044. };
  79045. const db = {
  79046. query: async (sql, params = []) => {
  79047. return sqlite.prepare(sql).bind(params).all();
  79048. },
  79049. run: async (query) => {
  79050. sqlite.prepare(query).run();
  79051. }
  79052. };
  79053. const proxy = async (params) => {
  79054. const preparedParams = prepareSqliteParams(params.params || []);
  79055. if (params.method === "values" || params.method === "get" || params.method === "all") {
  79056. return sqlite.prepare(params.sql).raw(params.mode === "array").all(preparedParams);
  79057. }
  79058. sqlite.prepare(params.sql).run(preparedParams);
  79059. return [];
  79060. };
  79061. const transactionProxy = async (queries) => {
  79062. const results = [];
  79063. const tx = sqlite.transaction((queries2) => {
  79064. for (const query of queries2) {
  79065. let result = [];
  79066. if (query.method === "values" || query.method === "get" || query.method === "all") {
  79067. result = sqlite.prepare(query.sql).all();
  79068. } else {
  79069. sqlite.prepare(query.sql).run();
  79070. }
  79071. results.push(result);
  79072. }
  79073. });
  79074. try {
  79075. tx(queries);
  79076. } catch (error2) {
  79077. results.push(error2);
  79078. }
  79079. return results;
  79080. };
  79081. return { ...db, packageName: "better-sqlite3", proxy, transactionProxy, migrate: migrateFn };
  79082. }
  79083. console.log(
  79084. "Please install either 'better-sqlite3' or '@libsql/client' for Drizzle Kit to connect to SQLite databases"
  79085. );
  79086. process.exit(1);
  79087. };
  79088. connectToLibSQL = async (credentials2) => {
  79089. if (await checkPackage("@libsql/client")) {
  79090. const { createClient } = await import("@libsql/client");
  79091. const { drizzle } = await import("drizzle-orm/libsql");
  79092. const { migrate: migrate2 } = await import("drizzle-orm/libsql/migrator");
  79093. const client = createClient({
  79094. url: normaliseSQLiteUrl(credentials2.url, "libsql"),
  79095. authToken: credentials2.authToken
  79096. });
  79097. const drzl = drizzle(client);
  79098. const migrateFn = async (config) => {
  79099. return migrate2(drzl, config);
  79100. };
  79101. const db = {
  79102. query: async (sql, params) => {
  79103. const res = await client.execute({ sql, args: params || [] });
  79104. return res.rows;
  79105. },
  79106. run: async (query) => {
  79107. await client.execute(query);
  79108. },
  79109. batchWithPragma: async (queries) => {
  79110. await client.migrate(queries);
  79111. }
  79112. };
  79113. const proxy = async (params) => {
  79114. const preparedParams = prepareSqliteParams(params.params || []);
  79115. const result = await client.execute({
  79116. sql: params.sql,
  79117. args: preparedParams
  79118. });
  79119. if (params.mode === "array") {
  79120. return result.rows.map((row) => Object.values(row));
  79121. } else {
  79122. return result.rows;
  79123. }
  79124. };
  79125. const transactionProxy = async (queries) => {
  79126. const results = [];
  79127. let transaction = null;
  79128. try {
  79129. transaction = await client.transaction();
  79130. for (const query of queries) {
  79131. const result = await transaction.execute(query.sql);
  79132. results.push(result.rows);
  79133. }
  79134. await transaction.commit();
  79135. } catch (error2) {
  79136. results.push(error2);
  79137. await (transaction == null ? void 0 : transaction.rollback());
  79138. } finally {
  79139. transaction == null ? void 0 : transaction.close();
  79140. }
  79141. return results;
  79142. };
  79143. return { ...db, packageName: "@libsql/client", proxy, transactionProxy, migrate: migrateFn };
  79144. }
  79145. console.log(
  79146. "Please install '@libsql/client' for Drizzle Kit to connect to LibSQL databases"
  79147. );
  79148. process.exit(1);
  79149. };
  79150. }
  79151. });
  79152. // src/cli/selector-ui.ts
  79153. var import_hanji5, Select;
  79154. var init_selector_ui = __esm({
  79155. "src/cli/selector-ui.ts"() {
  79156. "use strict";
  79157. init_source();
  79158. import_hanji5 = __toESM(require_hanji());
  79159. Select = class extends import_hanji5.Prompt {
  79160. constructor(items) {
  79161. super();
  79162. this.on("attach", (terminal) => terminal.toggleCursor("hide"));
  79163. this.on("detach", (terminal) => terminal.toggleCursor("show"));
  79164. this.data = new import_hanji5.SelectState(
  79165. items.map((it) => ({ label: it, value: `${it}-value` }))
  79166. );
  79167. this.data.bind(this);
  79168. }
  79169. render(status) {
  79170. if (status === "submitted" || status === "aborted") return "";
  79171. let text = ``;
  79172. this.data.items.forEach((it, idx) => {
  79173. text += idx === this.data.selectedIdx ? `${source_default.green("\u276F " + it.label)}` : ` ${it.label}`;
  79174. text += idx != this.data.items.length - 1 ? "\n" : "";
  79175. });
  79176. return text;
  79177. }
  79178. result() {
  79179. return {
  79180. index: this.data.selectedIdx,
  79181. value: this.data.items[this.data.selectedIdx].value
  79182. };
  79183. }
  79184. };
  79185. }
  79186. });
  79187. // src/cli/commands/libSqlPushUtils.ts
  79188. var getOldTableName2, _moveDataStatements2, libSqlLogSuggestionsAndReturn;
  79189. var init_libSqlPushUtils = __esm({
  79190. "src/cli/commands/libSqlPushUtils.ts"() {
  79191. "use strict";
  79192. init_source();
  79193. init_utils2();
  79194. init_sqliteSchema();
  79195. init_sqlgenerator();
  79196. getOldTableName2 = (tableName, meta) => {
  79197. for (const key of Object.keys(meta.tables)) {
  79198. const value = meta.tables[key];
  79199. if (`"${tableName}"` === value) {
  79200. return key.substring(1, key.length - 1);
  79201. }
  79202. }
  79203. return tableName;
  79204. };
  79205. _moveDataStatements2 = (tableName, json, dataLoss = false) => {
  79206. const statements = [];
  79207. const newTableName = `__new_${tableName}`;
  79208. const tableColumns = Object.values(json.tables[tableName].columns);
  79209. const referenceData = Object.values(json.tables[tableName].foreignKeys);
  79210. const compositePKs = Object.values(
  79211. json.tables[tableName].compositePrimaryKeys
  79212. ).map((it) => SQLiteSquasher.unsquashPK(it));
  79213. const checkConstraints = Object.values(json.tables[tableName].checkConstraints);
  79214. const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
  79215. const mappedCheckConstraints = checkConstraints.map(
  79216. (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
  79217. );
  79218. statements.push(
  79219. new SQLiteCreateTableConvertor().convert({
  79220. type: "sqlite_create_table",
  79221. tableName: newTableName,
  79222. columns: tableColumns,
  79223. referenceData: fks,
  79224. compositePKs,
  79225. checkConstraints: mappedCheckConstraints
  79226. })
  79227. );
  79228. if (!dataLoss) {
  79229. const columns = Object.keys(json.tables[tableName].columns).map(
  79230. (c3) => `"${c3}"`
  79231. );
  79232. statements.push(
  79233. `INSERT INTO \`${newTableName}\`(${columns.join(
  79234. ", "
  79235. )}) SELECT ${columns.join(", ")} FROM \`${tableName}\`;`
  79236. );
  79237. }
  79238. statements.push(
  79239. new SQLiteDropTableConvertor().convert({
  79240. type: "drop_table",
  79241. tableName,
  79242. schema: ""
  79243. })
  79244. );
  79245. statements.push(
  79246. new SqliteRenameTableConvertor().convert({
  79247. fromSchema: "",
  79248. tableNameFrom: newTableName,
  79249. tableNameTo: tableName,
  79250. toSchema: "",
  79251. type: "rename_table"
  79252. })
  79253. );
  79254. for (const idx of Object.values(json.tables[tableName].indexes)) {
  79255. statements.push(
  79256. new CreateSqliteIndexConvertor().convert({
  79257. type: "create_index",
  79258. tableName,
  79259. schema: "",
  79260. data: idx
  79261. })
  79262. );
  79263. }
  79264. return statements;
  79265. };
  79266. libSqlLogSuggestionsAndReturn = async (connection, statements, json1, json2, meta) => {
  79267. let shouldAskForApprove = false;
  79268. const statementsToExecute = [];
  79269. const infoToPrint = [];
  79270. const tablesToRemove = [];
  79271. const columnsToRemove = [];
  79272. const tablesToTruncate = [];
  79273. for (const statement of statements) {
  79274. if (statement.type === "drop_table") {
  79275. const res = await connection.query(
  79276. `select count(*) as count from \`${statement.tableName}\``
  79277. );
  79278. const count = Number(res[0].count);
  79279. if (count > 0) {
  79280. infoToPrint.push(
  79281. `\xB7 You're about to delete ${source_default.underline(
  79282. statement.tableName
  79283. )} table with ${count} items`
  79284. );
  79285. tablesToRemove.push(statement.tableName);
  79286. shouldAskForApprove = true;
  79287. }
  79288. const fromJsonStatement = fromJson([statement], "turso", "push", json2);
  79289. statementsToExecute.push(
  79290. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  79291. );
  79292. } else if (statement.type === "alter_table_drop_column") {
  79293. const tableName = statement.tableName;
  79294. const res = await connection.query(
  79295. `select count(*) as count from \`${tableName}\``
  79296. );
  79297. const count = Number(res[0].count);
  79298. if (count > 0) {
  79299. infoToPrint.push(
  79300. `\xB7 You're about to delete ${source_default.underline(
  79301. statement.columnName
  79302. )} column in ${tableName} table with ${count} items`
  79303. );
  79304. columnsToRemove.push(`${tableName}_${statement.columnName}`);
  79305. shouldAskForApprove = true;
  79306. }
  79307. const fromJsonStatement = fromJson([statement], "turso", "push", json2);
  79308. statementsToExecute.push(
  79309. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  79310. );
  79311. } else if (statement.type === "sqlite_alter_table_add_column" && statement.column.notNull && !statement.column.default) {
  79312. const newTableName = statement.tableName;
  79313. const res = await connection.query(
  79314. `select count(*) as count from \`${newTableName}\``
  79315. );
  79316. const count = Number(res[0].count);
  79317. if (count > 0) {
  79318. infoToPrint.push(
  79319. `\xB7 You're about to add not-null ${source_default.underline(
  79320. statement.column.name
  79321. )} column without default value, which contains ${count} items`
  79322. );
  79323. tablesToTruncate.push(newTableName);
  79324. statementsToExecute.push(`delete from ${newTableName};`);
  79325. shouldAskForApprove = true;
  79326. }
  79327. const fromJsonStatement = fromJson([statement], "turso", "push", json2);
  79328. statementsToExecute.push(
  79329. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  79330. );
  79331. } else if (statement.type === "alter_table_alter_column_set_notnull") {
  79332. const tableName = statement.tableName;
  79333. if (statement.type === "alter_table_alter_column_set_notnull" && typeof statement.columnDefault === "undefined") {
  79334. const res = await connection.query(
  79335. `select count(*) as count from \`${tableName}\``
  79336. );
  79337. const count = Number(res[0].count);
  79338. if (count > 0) {
  79339. infoToPrint.push(
  79340. `\xB7 You're about to add not-null constraint to ${source_default.underline(
  79341. statement.columnName
  79342. )} column without default value, which contains ${count} items`
  79343. );
  79344. tablesToTruncate.push(tableName);
  79345. statementsToExecute.push(`delete from \`${tableName}\``);
  79346. shouldAskForApprove = true;
  79347. }
  79348. }
  79349. const modifyStatements = new LibSQLModifyColumn().convert(statement, json2);
  79350. statementsToExecute.push(
  79351. ...Array.isArray(modifyStatements) ? modifyStatements : [modifyStatements]
  79352. );
  79353. } else if (statement.type === "recreate_table") {
  79354. const tableName = statement.tableName;
  79355. let dataLoss = false;
  79356. const oldTableName = getOldTableName2(tableName, meta);
  79357. const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
  79358. const currentColumnNames = Object.keys(json2.tables[tableName].columns);
  79359. const { removedColumns, addedColumns } = findAddedAndRemoved(
  79360. prevColumnNames,
  79361. currentColumnNames
  79362. );
  79363. if (removedColumns.length) {
  79364. for (const removedColumn of removedColumns) {
  79365. const res = await connection.query(
  79366. `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
  79367. );
  79368. const count = Number(res[0].count);
  79369. if (count > 0) {
  79370. infoToPrint.push(
  79371. `\xB7 You're about to delete ${source_default.underline(
  79372. removedColumn
  79373. )} column in ${tableName} table with ${count} items`
  79374. );
  79375. columnsToRemove.push(removedColumn);
  79376. shouldAskForApprove = true;
  79377. }
  79378. }
  79379. }
  79380. if (addedColumns.length) {
  79381. for (const addedColumn of addedColumns) {
  79382. const [res] = await connection.query(
  79383. `select count(*) as count from \`${tableName}\``
  79384. );
  79385. const columnConf = json2.tables[tableName].columns[addedColumn];
  79386. const count = Number(res.count);
  79387. if (count > 0 && columnConf.notNull && !columnConf.default) {
  79388. dataLoss = true;
  79389. infoToPrint.push(
  79390. `\xB7 You're about to add not-null ${source_default.underline(
  79391. addedColumn
  79392. )} column without default value to table, which contains ${count} items`
  79393. );
  79394. shouldAskForApprove = true;
  79395. tablesToTruncate.push(tableName);
  79396. statementsToExecute.push(`DELETE FROM \`${tableName}\`;`);
  79397. }
  79398. }
  79399. }
  79400. const tablesReferencingCurrent = [];
  79401. for (const table6 of Object.values(json2.tables)) {
  79402. const tablesRefs = Object.values(json2.tables[table6.name].foreignKeys).filter((t4) => SQLiteSquasher.unsquashPushFK(t4).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
  79403. tablesReferencingCurrent.push(...tablesRefs);
  79404. }
  79405. if (!tablesReferencingCurrent.length) {
  79406. statementsToExecute.push(..._moveDataStatements2(tableName, json2, dataLoss));
  79407. continue;
  79408. }
  79409. statementsToExecute.push(
  79410. ..._moveDataStatements2(tableName, json2, dataLoss)
  79411. );
  79412. } else if (statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") {
  79413. const tableName = statement.tableName;
  79414. const res = await connection.query(
  79415. `select count("${statement.columnName}") as count from \`${tableName}\``
  79416. );
  79417. const count = Number(res[0].count);
  79418. if (count > 0) {
  79419. infoToPrint.push(
  79420. `\xB7 You're about to delete ${source_default.underline(
  79421. statement.columnName
  79422. )} column in ${tableName} table with ${count} items`
  79423. );
  79424. columnsToRemove.push(`${tableName}_${statement.columnName}`);
  79425. shouldAskForApprove = true;
  79426. }
  79427. const fromJsonStatement = fromJson([statement], "turso", "push", json2);
  79428. statementsToExecute.push(
  79429. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  79430. );
  79431. } else {
  79432. const fromJsonStatement = fromJson([statement], "turso", "push", json2);
  79433. statementsToExecute.push(
  79434. ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
  79435. );
  79436. }
  79437. }
  79438. return {
  79439. statementsToExecute: [...new Set(statementsToExecute)],
  79440. shouldAskForApprove,
  79441. infoToPrint,
  79442. columnsToRemove: [...new Set(columnsToRemove)],
  79443. tablesToTruncate: [...new Set(tablesToTruncate)],
  79444. tablesToRemove: [...new Set(tablesToRemove)]
  79445. };
  79446. };
  79447. }
  79448. });
  79449. // src/cli/commands/mysqlPushUtils.ts
  79450. var import_hanji6, filterStatements, logSuggestionsAndReturn2;
  79451. var init_mysqlPushUtils = __esm({
  79452. "src/cli/commands/mysqlPushUtils.ts"() {
  79453. "use strict";
  79454. init_source();
  79455. import_hanji6 = __toESM(require_hanji());
  79456. init_mysqlSchema();
  79457. init_selector_ui();
  79458. init_outputs();
  79459. filterStatements = (statements, currentSchema, prevSchema) => {
  79460. return statements.filter((statement) => {
  79461. if (statement.type === "alter_table_alter_column_set_type") {
  79462. if (statement.oldDataType.startsWith("tinyint") && statement.newDataType.startsWith("boolean")) {
  79463. return false;
  79464. }
  79465. if (statement.oldDataType.startsWith("bigint unsigned") && statement.newDataType.startsWith("serial")) {
  79466. return false;
  79467. }
  79468. if (statement.oldDataType.startsWith("serial") && statement.newDataType.startsWith("bigint unsigned")) {
  79469. return false;
  79470. }
  79471. } else if (statement.type === "alter_table_alter_column_set_default") {
  79472. if (statement.newDefaultValue === false && statement.oldDefaultValue === 0 && statement.newDataType === "boolean") {
  79473. return false;
  79474. }
  79475. if (statement.newDefaultValue === true && statement.oldDefaultValue === 1 && statement.newDataType === "boolean") {
  79476. return false;
  79477. }
  79478. } else if (statement.type === "delete_unique_constraint") {
  79479. const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
  79480. if (unsquashed.columns.length === 1 && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && prevSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].name === unsquashed.columns[0]) {
  79481. return false;
  79482. }
  79483. } else if (statement.type === "alter_table_alter_column_drop_notnull") {
  79484. const serialStatement = statements.find(
  79485. (it) => it.type === "alter_table_alter_column_set_type"
  79486. );
  79487. if ((serialStatement == null ? void 0 : serialStatement.oldDataType.startsWith("bigint unsigned")) && (serialStatement == null ? void 0 : serialStatement.newDataType.startsWith("serial")) && serialStatement.columnName === statement.columnName && serialStatement.tableName === statement.tableName) {
  79488. return false;
  79489. }
  79490. if (statement.newDataType === "serial" && !statement.columnNotNull) {
  79491. return false;
  79492. }
  79493. if (statement.columnAutoIncrement) {
  79494. return false;
  79495. }
  79496. }
  79497. return true;
  79498. });
  79499. };
  79500. logSuggestionsAndReturn2 = async (db, statements, json2) => {
  79501. let shouldAskForApprove = false;
  79502. const statementsToExecute = [];
  79503. const infoToPrint = [];
  79504. const tablesToRemove = [];
  79505. const columnsToRemove = [];
  79506. const schemasToRemove = [];
  79507. const tablesToTruncate = [];
  79508. for (const statement of statements) {
  79509. if (statement.type === "drop_table") {
  79510. const res = await db.query(
  79511. `select count(*) as count from \`${statement.tableName}\``
  79512. );
  79513. const count = Number(res[0].count);
  79514. if (count > 0) {
  79515. infoToPrint.push(
  79516. `\xB7 You're about to delete ${source_default.underline(
  79517. statement.tableName
  79518. )} table with ${count} items`
  79519. );
  79520. tablesToRemove.push(statement.tableName);
  79521. shouldAskForApprove = true;
  79522. }
  79523. } else if (statement.type === "alter_table_drop_column") {
  79524. const res = await db.query(
  79525. `select count(*) as count from \`${statement.tableName}\``
  79526. );
  79527. const count = Number(res[0].count);
  79528. if (count > 0) {
  79529. infoToPrint.push(
  79530. `\xB7 You're about to delete ${source_default.underline(
  79531. statement.columnName
  79532. )} column in ${statement.tableName} table with ${count} items`
  79533. );
  79534. columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
  79535. shouldAskForApprove = true;
  79536. }
  79537. } else if (statement.type === "drop_schema") {
  79538. const res = await db.query(
  79539. `select count(*) as count from information_schema.tables where table_schema = \`${statement.name}\`;`
  79540. );
  79541. const count = Number(res[0].count);
  79542. if (count > 0) {
  79543. infoToPrint.push(
  79544. `\xB7 You're about to delete ${source_default.underline(
  79545. statement.name
  79546. )} schema with ${count} tables`
  79547. );
  79548. schemasToRemove.push(statement.name);
  79549. shouldAskForApprove = true;
  79550. }
  79551. } else if (statement.type === "alter_table_alter_column_set_type") {
  79552. const res = await db.query(
  79553. `select count(*) as count from \`${statement.tableName}\``
  79554. );
  79555. const count = Number(res[0].count);
  79556. if (count > 0) {
  79557. infoToPrint.push(
  79558. `\xB7 You're about to change ${source_default.underline(
  79559. statement.columnName
  79560. )} column type from ${source_default.underline(
  79561. statement.oldDataType
  79562. )} to ${source_default.underline(statement.newDataType)} with ${count} items`
  79563. );
  79564. statementsToExecute.push(`truncate table ${statement.tableName};`);
  79565. tablesToTruncate.push(statement.tableName);
  79566. shouldAskForApprove = true;
  79567. }
  79568. } else if (statement.type === "alter_table_alter_column_drop_default") {
  79569. if (statement.columnNotNull) {
  79570. const res = await db.query(
  79571. `select count(*) as count from \`${statement.tableName}\``
  79572. );
  79573. const count = Number(res[0].count);
  79574. if (count > 0) {
  79575. infoToPrint.push(
  79576. `\xB7 You're about to remove default value from ${source_default.underline(
  79577. statement.columnName
  79578. )} not-null column with ${count} items`
  79579. );
  79580. tablesToTruncate.push(statement.tableName);
  79581. statementsToExecute.push(`truncate table ${statement.tableName};`);
  79582. shouldAskForApprove = true;
  79583. }
  79584. }
  79585. } else if (statement.type === "alter_table_alter_column_set_notnull") {
  79586. if (typeof statement.columnDefault === "undefined") {
  79587. const res = await db.query(
  79588. `select count(*) as count from \`${statement.tableName}\``
  79589. );
  79590. const count = Number(res[0].count);
  79591. if (count > 0) {
  79592. infoToPrint.push(
  79593. `\xB7 You're about to set not-null constraint to ${source_default.underline(
  79594. statement.columnName
  79595. )} column without default, which contains ${count} items`
  79596. );
  79597. tablesToTruncate.push(statement.tableName);
  79598. statementsToExecute.push(`truncate table ${statement.tableName};`);
  79599. shouldAskForApprove = true;
  79600. }
  79601. }
  79602. } else if (statement.type === "alter_table_alter_column_drop_pk") {
  79603. const res = await db.query(
  79604. `select count(*) as count from \`${statement.tableName}\``
  79605. );
  79606. if (Object.values(json2.tables[statement.tableName].columns).filter(
  79607. (column11) => column11.autoincrement
  79608. ).length > 0) {
  79609. console.log(
  79610. `${withStyle.errorWarning(
  79611. `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
  79612. )}`
  79613. );
  79614. process.exit(1);
  79615. }
  79616. const count = Number(res[0].count);
  79617. if (count > 0) {
  79618. infoToPrint.push(
  79619. `\xB7 You're about to change ${source_default.underline(
  79620. statement.tableName
  79621. )} primary key. This statements may fail and you table may left without primary key`
  79622. );
  79623. tablesToTruncate.push(statement.tableName);
  79624. shouldAskForApprove = true;
  79625. }
  79626. } else if (statement.type === "delete_composite_pk") {
  79627. if (Object.values(json2.tables[statement.tableName].columns).filter(
  79628. (column11) => column11.autoincrement
  79629. ).length > 0) {
  79630. console.log(
  79631. `${withStyle.errorWarning(
  79632. `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
  79633. )}`
  79634. );
  79635. process.exit(1);
  79636. }
  79637. } else if (statement.type === "alter_table_add_column") {
  79638. if (statement.column.notNull && typeof statement.column.default === "undefined") {
  79639. const res = await db.query(
  79640. `select count(*) as count from \`${statement.tableName}\``
  79641. );
  79642. const count = Number(res[0].count);
  79643. if (count > 0) {
  79644. infoToPrint.push(
  79645. `\xB7 You're about to add not-null ${source_default.underline(
  79646. statement.column.name
  79647. )} column without default value, which contains ${count} items`
  79648. );
  79649. tablesToTruncate.push(statement.tableName);
  79650. statementsToExecute.push(`truncate table ${statement.tableName};`);
  79651. shouldAskForApprove = true;
  79652. }
  79653. }
  79654. } else if (statement.type === "create_unique_constraint") {
  79655. const res = await db.query(
  79656. `select count(*) as count from \`${statement.tableName}\``
  79657. );
  79658. const count = Number(res[0].count);
  79659. if (count > 0) {
  79660. const unsquashedUnique = MySqlSquasher.unsquashUnique(statement.data);
  79661. console.log(
  79662. `\xB7 You're about to add ${source_default.underline(
  79663. unsquashedUnique.name
  79664. )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
  79665. statement.tableName
  79666. )} table?
  79667. `
  79668. );
  79669. const { status, data } = await (0, import_hanji6.render)(
  79670. new Select([
  79671. "No, add the constraint without truncating the table",
  79672. `Yes, truncate the table`
  79673. ])
  79674. );
  79675. if ((data == null ? void 0 : data.index) === 1) {
  79676. tablesToTruncate.push(statement.tableName);
  79677. statementsToExecute.push(`truncate table ${statement.tableName};`);
  79678. shouldAskForApprove = true;
  79679. }
  79680. }
  79681. }
  79682. }
  79683. return {
  79684. statementsToExecute,
  79685. shouldAskForApprove,
  79686. infoToPrint,
  79687. columnsToRemove: [...new Set(columnsToRemove)],
  79688. schemasToRemove: [...new Set(schemasToRemove)],
  79689. tablesToTruncate: [...new Set(tablesToTruncate)],
  79690. tablesToRemove: [...new Set(tablesToRemove)]
  79691. };
  79692. };
  79693. }
  79694. });
  79695. // src/cli/commands/pgPushUtils.ts
  79696. function concatSchemaAndTableName(schema6, table6) {
  79697. return schema6 ? `"${schema6}"."${table6}"` : `"${table6}"`;
  79698. }
  79699. function tableNameWithSchemaFrom(schema6, tableName, renamedSchemas, renamedTables) {
  79700. const newSchemaName = schema6 ? renamedSchemas[schema6] ? renamedSchemas[schema6] : schema6 : void 0;
  79701. const newTableName = renamedTables[concatSchemaAndTableName(newSchemaName, tableName)] ? renamedTables[concatSchemaAndTableName(newSchemaName, tableName)] : tableName;
  79702. return concatSchemaAndTableName(newSchemaName, newTableName);
  79703. }
  79704. var import_hanji7, pgSuggestions;
  79705. var init_pgPushUtils = __esm({
  79706. "src/cli/commands/pgPushUtils.ts"() {
  79707. "use strict";
  79708. init_source();
  79709. import_hanji7 = __toESM(require_hanji());
  79710. init_pgSchema();
  79711. init_sqlgenerator();
  79712. init_selector_ui();
  79713. pgSuggestions = async (db, statements) => {
  79714. let shouldAskForApprove = false;
  79715. const statementsToExecute = [];
  79716. const infoToPrint = [];
  79717. const tablesToRemove = [];
  79718. const columnsToRemove = [];
  79719. const schemasToRemove = [];
  79720. const tablesToTruncate = [];
  79721. const matViewsToRemove = [];
  79722. let renamedSchemas = {};
  79723. let renamedTables = {};
  79724. for (const statement of statements) {
  79725. if (statement.type === "rename_schema") {
  79726. renamedSchemas[statement.to] = statement.from;
  79727. } else if (statement.type === "rename_table") {
  79728. renamedTables[concatSchemaAndTableName(statement.toSchema, statement.tableNameTo)] = statement.tableNameFrom;
  79729. } else if (statement.type === "drop_table") {
  79730. const res = await db.query(
  79731. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  79732. );
  79733. const count = Number(res[0].count);
  79734. if (count > 0) {
  79735. infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.tableName)} table with ${count} items`);
  79736. tablesToRemove.push(statement.tableName);
  79737. shouldAskForApprove = true;
  79738. }
  79739. } else if (statement.type === "drop_view" && statement.materialized) {
  79740. const res = await db.query(`select count(*) as count from "${statement.schema ?? "public"}"."${statement.name}"`);
  79741. const count = Number(res[0].count);
  79742. if (count > 0) {
  79743. infoToPrint.push(
  79744. `\xB7 You're about to delete "${source_default.underline(statement.name)}" materialized view with ${count} items`
  79745. );
  79746. matViewsToRemove.push(statement.name);
  79747. shouldAskForApprove = true;
  79748. }
  79749. } else if (statement.type === "alter_table_drop_column") {
  79750. const res = await db.query(
  79751. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  79752. );
  79753. const count = Number(res[0].count);
  79754. if (count > 0) {
  79755. infoToPrint.push(
  79756. `\xB7 You're about to delete ${source_default.underline(statement.columnName)} column in ${statement.tableName} table with ${count} items`
  79757. );
  79758. columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
  79759. shouldAskForApprove = true;
  79760. }
  79761. } else if (statement.type === "drop_schema") {
  79762. const res = await db.query(
  79763. `select count(*) as count from information_schema.tables where table_schema = '${statement.name}';`
  79764. );
  79765. const count = Number(res[0].count);
  79766. if (count > 0) {
  79767. infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.name)} schema with ${count} tables`);
  79768. schemasToRemove.push(statement.name);
  79769. shouldAskForApprove = true;
  79770. }
  79771. } else if (statement.type === "alter_table_alter_column_set_type") {
  79772. const res = await db.query(
  79773. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  79774. );
  79775. const count = Number(res[0].count);
  79776. if (count > 0) {
  79777. infoToPrint.push(
  79778. `\xB7 You're about to change ${source_default.underline(statement.columnName)} column type from ${source_default.underline(statement.oldDataType)} to ${source_default.underline(
  79779. statement.newDataType
  79780. )} with ${count} items`
  79781. );
  79782. statementsToExecute.push(
  79783. `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
  79784. );
  79785. tablesToTruncate.push(statement.tableName);
  79786. shouldAskForApprove = true;
  79787. }
  79788. } else if (statement.type === "alter_table_alter_column_drop_pk") {
  79789. const res = await db.query(
  79790. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  79791. );
  79792. const count = Number(res[0].count);
  79793. if (count > 0) {
  79794. infoToPrint.push(
  79795. `\xB7 You're about to change ${source_default.underline(statement.tableName)} primary key. This statements may fail and you table may left without primary key`
  79796. );
  79797. tablesToTruncate.push(statement.tableName);
  79798. shouldAskForApprove = true;
  79799. }
  79800. const tableNameWithSchema = tableNameWithSchemaFrom(
  79801. statement.schema,
  79802. statement.tableName,
  79803. renamedSchemas,
  79804. renamedTables
  79805. );
  79806. const pkNameResponse = await db.query(
  79807. `SELECT constraint_name FROM information_schema.table_constraints
  79808. WHERE table_schema = '${typeof statement.schema === "undefined" || statement.schema === "" ? "public" : statement.schema}'
  79809. AND table_name = '${statement.tableName}'
  79810. AND constraint_type = 'PRIMARY KEY';`
  79811. );
  79812. statementsToExecute.push(
  79813. `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${pkNameResponse[0].constraint_name}"`
  79814. );
  79815. continue;
  79816. } else if (statement.type === "alter_table_add_column") {
  79817. if (statement.column.notNull && typeof statement.column.default === "undefined") {
  79818. const res = await db.query(
  79819. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  79820. );
  79821. const count = Number(res[0].count);
  79822. if (count > 0) {
  79823. infoToPrint.push(
  79824. `\xB7 You're about to add not-null ${source_default.underline(statement.column.name)} column without default value, which contains ${count} items`
  79825. );
  79826. tablesToTruncate.push(statement.tableName);
  79827. statementsToExecute.push(
  79828. `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
  79829. );
  79830. shouldAskForApprove = true;
  79831. }
  79832. }
  79833. } else if (statement.type === "create_unique_constraint") {
  79834. const res = await db.query(
  79835. `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
  79836. );
  79837. const count = Number(res[0].count);
  79838. if (count > 0) {
  79839. const unsquashedUnique = PgSquasher.unsquashUnique(statement.data);
  79840. console.log(
  79841. `\xB7 You're about to add ${source_default.underline(
  79842. unsquashedUnique.name
  79843. )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
  79844. statement.tableName
  79845. )} table?
  79846. `
  79847. );
  79848. const { status, data } = await (0, import_hanji7.render)(
  79849. new Select(["No, add the constraint without truncating the table", `Yes, truncate the table`])
  79850. );
  79851. if ((data == null ? void 0 : data.index) === 1) {
  79852. tablesToTruncate.push(statement.tableName);
  79853. statementsToExecute.push(
  79854. `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
  79855. );
  79856. shouldAskForApprove = true;
  79857. }
  79858. }
  79859. }
  79860. const stmnt = fromJson([statement], "postgresql", "push");
  79861. if (typeof stmnt !== "undefined") {
  79862. statementsToExecute.push(...stmnt);
  79863. }
  79864. }
  79865. return {
  79866. statementsToExecute: [...new Set(statementsToExecute)],
  79867. shouldAskForApprove,
  79868. infoToPrint,
  79869. matViewsToRemove: [...new Set(matViewsToRemove)],
  79870. columnsToRemove: [...new Set(columnsToRemove)],
  79871. schemasToRemove: [...new Set(schemasToRemove)],
  79872. tablesToTruncate: [...new Set(tablesToTruncate)],
  79873. tablesToRemove: [...new Set(tablesToRemove)]
  79874. };
  79875. };
  79876. }
  79877. });
  79878. // src/cli/commands/singlestorePushUtils.ts
  79879. function findColumnTypeAlternations(columns1, columns2) {
  79880. const changes = [];
  79881. for (const key in columns1) {
  79882. if (columns1.hasOwnProperty(key) && columns2.hasOwnProperty(key)) {
  79883. const col1 = columns1[key];
  79884. const col2 = columns2[key];
  79885. if (col1.type !== col2.type) {
  79886. changes.push(col2.name);
  79887. }
  79888. }
  79889. }
  79890. return changes;
  79891. }
  79892. var import_hanji8, filterStatements2, logSuggestionsAndReturn3;
  79893. var init_singlestorePushUtils = __esm({
  79894. "src/cli/commands/singlestorePushUtils.ts"() {
  79895. "use strict";
  79896. init_source();
  79897. import_hanji8 = __toESM(require_hanji());
  79898. init_sqlgenerator();
  79899. init_singlestoreSchema();
  79900. init_utils2();
  79901. init_selector_ui();
  79902. init_outputs();
  79903. filterStatements2 = (statements, currentSchema, prevSchema) => {
  79904. return statements.filter((statement) => {
  79905. if (statement.type === "alter_table_alter_column_set_type") {
  79906. if (statement.oldDataType.startsWith("tinyint") && statement.newDataType.startsWith("boolean")) {
  79907. return false;
  79908. }
  79909. if (statement.oldDataType.startsWith("bigint unsigned") && statement.newDataType.startsWith("serial")) {
  79910. return false;
  79911. }
  79912. if (statement.oldDataType.startsWith("serial") && statement.newDataType.startsWith("bigint unsigned")) {
  79913. return false;
  79914. }
  79915. } else if (statement.type === "alter_table_alter_column_set_default") {
  79916. if (statement.newDefaultValue === false && statement.oldDefaultValue === 0 && statement.newDataType === "boolean") {
  79917. return false;
  79918. }
  79919. if (statement.newDefaultValue === true && statement.oldDefaultValue === 1 && statement.newDataType === "boolean") {
  79920. return false;
  79921. }
  79922. } else if (statement.type === "delete_unique_constraint") {
  79923. const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
  79924. if (unsquashed.columns.length === 1 && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && prevSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].name === unsquashed.columns[0]) {
  79925. return false;
  79926. }
  79927. } else if (statement.type === "alter_table_alter_column_drop_notnull") {
  79928. const serialStatement = statements.find(
  79929. (it) => it.type === "alter_table_alter_column_set_type"
  79930. );
  79931. if ((serialStatement == null ? void 0 : serialStatement.oldDataType.startsWith("bigint unsigned")) && (serialStatement == null ? void 0 : serialStatement.newDataType.startsWith("serial")) && serialStatement.columnName === statement.columnName && serialStatement.tableName === statement.tableName) {
  79932. return false;
  79933. }
  79934. if (statement.newDataType === "serial" && !statement.columnNotNull) {
  79935. return false;
  79936. }
  79937. if (statement.columnAutoIncrement) {
  79938. return false;
  79939. }
  79940. }
  79941. return true;
  79942. });
  79943. };
  79944. logSuggestionsAndReturn3 = async (db, statements, json2, json1) => {
  79945. let shouldAskForApprove = false;
  79946. const statementsToExecute = [];
  79947. const infoToPrint = [];
  79948. const tablesToRemove = [];
  79949. const columnsToRemove = [];
  79950. const schemasToRemove = [];
  79951. const tablesToTruncate = [];
  79952. for (const statement of statements) {
  79953. if (statement.type === "drop_table") {
  79954. const res = await db.query(
  79955. `select count(*) as count from \`${statement.tableName}\``
  79956. );
  79957. const count = Number(res[0].count);
  79958. if (count > 0) {
  79959. infoToPrint.push(
  79960. `\xB7 You're about to delete ${source_default.underline(
  79961. statement.tableName
  79962. )} table with ${count} items`
  79963. );
  79964. tablesToRemove.push(statement.tableName);
  79965. shouldAskForApprove = true;
  79966. }
  79967. } else if (statement.type === "alter_table_drop_column") {
  79968. const res = await db.query(
  79969. `select count(*) as count from \`${statement.tableName}\``
  79970. );
  79971. const count = Number(res[0].count);
  79972. if (count > 0) {
  79973. infoToPrint.push(
  79974. `\xB7 You're about to delete ${source_default.underline(
  79975. statement.columnName
  79976. )} column in ${statement.tableName} table with ${count} items`
  79977. );
  79978. columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
  79979. shouldAskForApprove = true;
  79980. }
  79981. } else if (statement.type === "drop_schema") {
  79982. const res = await db.query(
  79983. `select count(*) as count from information_schema.tables where table_schema = \`${statement.name}\`;`
  79984. );
  79985. const count = Number(res[0].count);
  79986. if (count > 0) {
  79987. infoToPrint.push(
  79988. `\xB7 You're about to delete ${source_default.underline(
  79989. statement.name
  79990. )} schema with ${count} tables`
  79991. );
  79992. schemasToRemove.push(statement.name);
  79993. shouldAskForApprove = true;
  79994. }
  79995. } else if (statement.type === "alter_table_alter_column_set_type") {
  79996. const res = await db.query(
  79997. `select count(*) as count from \`${statement.tableName}\``
  79998. );
  79999. const count = Number(res[0].count);
  80000. if (count > 0) {
  80001. infoToPrint.push(
  80002. `\xB7 You're about to change ${source_default.underline(
  80003. statement.columnName
  80004. )} column type from ${source_default.underline(
  80005. statement.oldDataType
  80006. )} to ${source_default.underline(statement.newDataType)} with ${count} items`
  80007. );
  80008. statementsToExecute.push(`truncate table ${statement.tableName};`);
  80009. tablesToTruncate.push(statement.tableName);
  80010. shouldAskForApprove = true;
  80011. }
  80012. } else if (statement.type === "alter_table_alter_column_drop_default") {
  80013. if (statement.columnNotNull) {
  80014. const res = await db.query(
  80015. `select count(*) as count from \`${statement.tableName}\``
  80016. );
  80017. const count = Number(res[0].count);
  80018. if (count > 0) {
  80019. infoToPrint.push(
  80020. `\xB7 You're about to remove default value from ${source_default.underline(
  80021. statement.columnName
  80022. )} not-null column with ${count} items`
  80023. );
  80024. tablesToTruncate.push(statement.tableName);
  80025. statementsToExecute.push(`truncate table ${statement.tableName};`);
  80026. shouldAskForApprove = true;
  80027. }
  80028. }
  80029. } else if (statement.type === "alter_table_alter_column_set_notnull") {
  80030. if (typeof statement.columnDefault === "undefined") {
  80031. const res = await db.query(
  80032. `select count(*) as count from \`${statement.tableName}\``
  80033. );
  80034. const count = Number(res[0].count);
  80035. if (count > 0) {
  80036. infoToPrint.push(
  80037. `\xB7 You're about to set not-null constraint to ${source_default.underline(
  80038. statement.columnName
  80039. )} column without default, which contains ${count} items`
  80040. );
  80041. tablesToTruncate.push(statement.tableName);
  80042. statementsToExecute.push(`truncate table ${statement.tableName};`);
  80043. shouldAskForApprove = true;
  80044. }
  80045. }
  80046. } else if (statement.type === "alter_table_alter_column_drop_pk") {
  80047. const res = await db.query(
  80048. `select count(*) as count from \`${statement.tableName}\``
  80049. );
  80050. if (Object.values(json2.tables[statement.tableName].columns).filter(
  80051. (column11) => column11.autoincrement
  80052. ).length > 0) {
  80053. console.log(
  80054. `${withStyle.errorWarning(
  80055. `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
  80056. )}`
  80057. );
  80058. process.exit(1);
  80059. }
  80060. const count = Number(res[0].count);
  80061. if (count > 0) {
  80062. infoToPrint.push(
  80063. `\xB7 You're about to change ${source_default.underline(
  80064. statement.tableName
  80065. )} primary key. This statements may fail and you table may left without primary key`
  80066. );
  80067. tablesToTruncate.push(statement.tableName);
  80068. shouldAskForApprove = true;
  80069. }
  80070. } else if (statement.type === "delete_composite_pk") {
  80071. if (Object.values(json2.tables[statement.tableName].columns).filter(
  80072. (column11) => column11.autoincrement
  80073. ).length > 0) {
  80074. console.log(
  80075. `${withStyle.errorWarning(
  80076. `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
  80077. )}`
  80078. );
  80079. process.exit(1);
  80080. }
  80081. } else if (statement.type === "alter_table_add_column") {
  80082. if (statement.column.notNull && typeof statement.column.default === "undefined") {
  80083. const res = await db.query(
  80084. `select count(*) as count from \`${statement.tableName}\``
  80085. );
  80086. const count = Number(res[0].count);
  80087. if (count > 0) {
  80088. infoToPrint.push(
  80089. `\xB7 You're about to add not-null ${source_default.underline(
  80090. statement.column.name
  80091. )} column without default value, which contains ${count} items`
  80092. );
  80093. tablesToTruncate.push(statement.tableName);
  80094. statementsToExecute.push(`truncate table ${statement.tableName};`);
  80095. shouldAskForApprove = true;
  80096. }
  80097. }
  80098. } else if (statement.type === "create_unique_constraint") {
  80099. const res = await db.query(
  80100. `select count(*) as count from \`${statement.tableName}\``
  80101. );
  80102. const count = Number(res[0].count);
  80103. if (count > 0) {
  80104. const unsquashedUnique = SingleStoreSquasher.unsquashUnique(statement.data);
  80105. console.log(
  80106. `\xB7 You're about to add ${source_default.underline(
  80107. unsquashedUnique.name
  80108. )} unique constraint to the table, which contains ${count} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
  80109. statement.tableName
  80110. )} table?
  80111. `
  80112. );
  80113. const { status, data } = await (0, import_hanji8.render)(
  80114. new Select([
  80115. "No, add the constraint without truncating the table",
  80116. `Yes, truncate the table`
  80117. ])
  80118. );
  80119. if ((data == null ? void 0 : data.index) === 1) {
  80120. tablesToTruncate.push(statement.tableName);
  80121. statementsToExecute.push(`truncate table ${statement.tableName};`);
  80122. shouldAskForApprove = true;
  80123. }
  80124. }
  80125. } else if (statement.type === "singlestore_recreate_table") {
  80126. const tableName = statement.tableName;
  80127. const prevColumns = json1.tables[tableName].columns;
  80128. const currentColumns = json2.tables[tableName].columns;
  80129. const { removedColumns, addedColumns } = findAddedAndRemoved(
  80130. Object.keys(prevColumns),
  80131. Object.keys(currentColumns)
  80132. );
  80133. if (removedColumns.length) {
  80134. for (const removedColumn of removedColumns) {
  80135. const res = await db.query(
  80136. `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
  80137. );
  80138. const count = Number(res[0].count);
  80139. if (count > 0) {
  80140. infoToPrint.push(
  80141. `\xB7 You're about to delete ${source_default.underline(
  80142. removedColumn
  80143. )} column in ${tableName} table with ${count} items`
  80144. );
  80145. columnsToRemove.push(removedColumn);
  80146. shouldAskForApprove = true;
  80147. }
  80148. }
  80149. }
  80150. if (addedColumns.length) {
  80151. for (const addedColumn of addedColumns) {
  80152. const [res] = await db.query(
  80153. `select count(*) as count from \`${tableName}\``
  80154. );
  80155. const columnConf = json2.tables[tableName].columns[addedColumn];
  80156. const count = Number(res.count);
  80157. if (count > 0 && columnConf.notNull && !columnConf.default) {
  80158. infoToPrint.push(
  80159. `\xB7 You're about to add not-null ${source_default.underline(
  80160. addedColumn
  80161. )} column without default value to table, which contains ${count} items`
  80162. );
  80163. shouldAskForApprove = true;
  80164. tablesToTruncate.push(tableName);
  80165. statementsToExecute.push(`TRUNCATE TABLE \`${tableName}\`;`);
  80166. }
  80167. }
  80168. }
  80169. const columnWithChangedType = findColumnTypeAlternations(prevColumns, currentColumns);
  80170. for (const column11 of columnWithChangedType) {
  80171. const [res] = await db.query(
  80172. `select count(*) as count from \`${tableName}\` WHERE \`${tableName}\`.\`${column11}\` IS NOT NULL;`
  80173. );
  80174. const count = Number(res.count);
  80175. if (count > 0) {
  80176. infoToPrint.push(
  80177. `\xB7 You're about recreate ${source_default.underline(tableName)} table with data type changing for ${source_default.underline(
  80178. column11
  80179. )} column, which contains ${count} items`
  80180. );
  80181. shouldAskForApprove = true;
  80182. tablesToTruncate.push(tableName);
  80183. statementsToExecute.push(`TRUNCATE TABLE \`${tableName}\`;`);
  80184. }
  80185. }
  80186. }
  80187. const stmnt = fromJson([statement], "singlestore", "push");
  80188. if (typeof stmnt !== "undefined") {
  80189. statementsToExecute.push(...stmnt);
  80190. }
  80191. }
  80192. return {
  80193. statementsToExecute,
  80194. shouldAskForApprove,
  80195. infoToPrint,
  80196. columnsToRemove: [...new Set(columnsToRemove)],
  80197. schemasToRemove: [...new Set(schemasToRemove)],
  80198. tablesToTruncate: [...new Set(tablesToTruncate)],
  80199. tablesToRemove: [...new Set(tablesToRemove)]
  80200. };
  80201. };
  80202. }
  80203. });
  80204. // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js
  80205. var posixClasses, braceEscape, regexpEscape, rangesToString, parseClass;
  80206. var init_brace_expressions = __esm({
  80207. "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js"() {
  80208. posixClasses = {
  80209. "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
  80210. "[:alpha:]": ["\\p{L}\\p{Nl}", true],
  80211. "[:ascii:]": ["\\x00-\\x7f", false],
  80212. "[:blank:]": ["\\p{Zs}\\t", true],
  80213. "[:cntrl:]": ["\\p{Cc}", true],
  80214. "[:digit:]": ["\\p{Nd}", true],
  80215. "[:graph:]": ["\\p{Z}\\p{C}", true, true],
  80216. "[:lower:]": ["\\p{Ll}", true],
  80217. "[:print:]": ["\\p{C}", true],
  80218. "[:punct:]": ["\\p{P}", true],
  80219. "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
  80220. "[:upper:]": ["\\p{Lu}", true],
  80221. "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
  80222. "[:xdigit:]": ["A-Fa-f0-9", false]
  80223. };
  80224. braceEscape = (s4) => s4.replace(/[[\]\\-]/g, "\\$&");
  80225. regexpEscape = (s4) => s4.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  80226. rangesToString = (ranges) => ranges.join("");
  80227. parseClass = (glob2, position) => {
  80228. const pos = position;
  80229. if (glob2.charAt(pos) !== "[") {
  80230. throw new Error("not in a brace expression");
  80231. }
  80232. const ranges = [];
  80233. const negs = [];
  80234. let i4 = pos + 1;
  80235. let sawStart = false;
  80236. let uflag = false;
  80237. let escaping = false;
  80238. let negate = false;
  80239. let endPos = pos;
  80240. let rangeStart = "";
  80241. WHILE: while (i4 < glob2.length) {
  80242. const c3 = glob2.charAt(i4);
  80243. if ((c3 === "!" || c3 === "^") && i4 === pos + 1) {
  80244. negate = true;
  80245. i4++;
  80246. continue;
  80247. }
  80248. if (c3 === "]" && sawStart && !escaping) {
  80249. endPos = i4 + 1;
  80250. break;
  80251. }
  80252. sawStart = true;
  80253. if (c3 === "\\") {
  80254. if (!escaping) {
  80255. escaping = true;
  80256. i4++;
  80257. continue;
  80258. }
  80259. }
  80260. if (c3 === "[" && !escaping) {
  80261. for (const [cls, [unip, u3, neg]] of Object.entries(posixClasses)) {
  80262. if (glob2.startsWith(cls, i4)) {
  80263. if (rangeStart) {
  80264. return ["$.", false, glob2.length - pos, true];
  80265. }
  80266. i4 += cls.length;
  80267. if (neg)
  80268. negs.push(unip);
  80269. else
  80270. ranges.push(unip);
  80271. uflag = uflag || u3;
  80272. continue WHILE;
  80273. }
  80274. }
  80275. }
  80276. escaping = false;
  80277. if (rangeStart) {
  80278. if (c3 > rangeStart) {
  80279. ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c3));
  80280. } else if (c3 === rangeStart) {
  80281. ranges.push(braceEscape(c3));
  80282. }
  80283. rangeStart = "";
  80284. i4++;
  80285. continue;
  80286. }
  80287. if (glob2.startsWith("-]", i4 + 1)) {
  80288. ranges.push(braceEscape(c3 + "-"));
  80289. i4 += 2;
  80290. continue;
  80291. }
  80292. if (glob2.startsWith("-", i4 + 1)) {
  80293. rangeStart = c3;
  80294. i4 += 2;
  80295. continue;
  80296. }
  80297. ranges.push(braceEscape(c3));
  80298. i4++;
  80299. }
  80300. if (endPos < i4) {
  80301. return ["", false, 0, false];
  80302. }
  80303. if (!ranges.length && !negs.length) {
  80304. return ["$.", false, glob2.length - pos, true];
  80305. }
  80306. if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
  80307. const r4 = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  80308. return [regexpEscape(r4), false, endPos - pos, false];
  80309. }
  80310. const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
  80311. const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
  80312. const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
  80313. return [comb, uflag, endPos - pos, true];
  80314. };
  80315. }
  80316. });
  80317. // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/escape.js
  80318. var escape;
  80319. var init_escape = __esm({
  80320. "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/escape.js"() {
  80321. escape = (s4, { windowsPathsNoEscape = false } = {}) => {
  80322. return windowsPathsNoEscape ? s4.replace(/[?*()[\]]/g, "[$&]") : s4.replace(/[?*()[\]\\]/g, "\\$&");
  80323. };
  80324. }
  80325. });
  80326. // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js
  80327. var unescape2;
  80328. var init_unescape = __esm({
  80329. "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js"() {
  80330. unescape2 = (s4, { windowsPathsNoEscape = false } = {}) => {
  80331. return windowsPathsNoEscape ? s4.replace(/\[([^\/\\])\]/g, "$1") : s4.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
  80332. };
  80333. }
  80334. });
  80335. // ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/index.js
  80336. var import_brace_expansion, minimatch, starDotExtRE, starDotExtTest, starDotExtTestDot, starDotExtTestNocase, starDotExtTestNocaseDot, starDotStarRE, starDotStarTest, starDotStarTestDot, dotStarRE, dotStarTest, starRE, starTest, starTestDot, qmarksRE, qmarksTestNocase, qmarksTestNocaseDot, qmarksTestDot, qmarksTest, qmarksTestNoExt, qmarksTestNoExtDot, defaultPlatform, path3, sep, GLOBSTAR, plTypes, qmark, star, twoStarDot, twoStarNoDot, charSet, reSpecials, addPatternStartSet, filter, ext, defaults, braceExpand, MAX_PATTERN_LENGTH, assertValidPattern, makeRe, match, globUnescape, globMagic, regExpEscape, Minimatch;
  80337. var init_mjs = __esm({
  80338. "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/index.js"() {
  80339. import_brace_expansion = __toESM(require_brace_expansion(), 1);
  80340. init_brace_expressions();
  80341. init_escape();
  80342. init_unescape();
  80343. init_escape();
  80344. init_unescape();
  80345. minimatch = (p3, pattern, options = {}) => {
  80346. assertValidPattern(pattern);
  80347. if (!options.nocomment && pattern.charAt(0) === "#") {
  80348. return false;
  80349. }
  80350. return new Minimatch(pattern, options).match(p3);
  80351. };
  80352. starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  80353. starDotExtTest = (ext2) => (f5) => !f5.startsWith(".") && f5.endsWith(ext2);
  80354. starDotExtTestDot = (ext2) => (f5) => f5.endsWith(ext2);
  80355. starDotExtTestNocase = (ext2) => {
  80356. ext2 = ext2.toLowerCase();
  80357. return (f5) => !f5.startsWith(".") && f5.toLowerCase().endsWith(ext2);
  80358. };
  80359. starDotExtTestNocaseDot = (ext2) => {
  80360. ext2 = ext2.toLowerCase();
  80361. return (f5) => f5.toLowerCase().endsWith(ext2);
  80362. };
  80363. starDotStarRE = /^\*+\.\*+$/;
  80364. starDotStarTest = (f5) => !f5.startsWith(".") && f5.includes(".");
  80365. starDotStarTestDot = (f5) => f5 !== "." && f5 !== ".." && f5.includes(".");
  80366. dotStarRE = /^\.\*+$/;
  80367. dotStarTest = (f5) => f5 !== "." && f5 !== ".." && f5.startsWith(".");
  80368. starRE = /^\*+$/;
  80369. starTest = (f5) => f5.length !== 0 && !f5.startsWith(".");
  80370. starTestDot = (f5) => f5.length !== 0 && f5 !== "." && f5 !== "..";
  80371. qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  80372. qmarksTestNocase = ([$0, ext2 = ""]) => {
  80373. const noext = qmarksTestNoExt([$0]);
  80374. if (!ext2)
  80375. return noext;
  80376. ext2 = ext2.toLowerCase();
  80377. return (f5) => noext(f5) && f5.toLowerCase().endsWith(ext2);
  80378. };
  80379. qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
  80380. const noext = qmarksTestNoExtDot([$0]);
  80381. if (!ext2)
  80382. return noext;
  80383. ext2 = ext2.toLowerCase();
  80384. return (f5) => noext(f5) && f5.toLowerCase().endsWith(ext2);
  80385. };
  80386. qmarksTestDot = ([$0, ext2 = ""]) => {
  80387. const noext = qmarksTestNoExtDot([$0]);
  80388. return !ext2 ? noext : (f5) => noext(f5) && f5.endsWith(ext2);
  80389. };
  80390. qmarksTest = ([$0, ext2 = ""]) => {
  80391. const noext = qmarksTestNoExt([$0]);
  80392. return !ext2 ? noext : (f5) => noext(f5) && f5.endsWith(ext2);
  80393. };
  80394. qmarksTestNoExt = ([$0]) => {
  80395. const len = $0.length;
  80396. return (f5) => f5.length === len && !f5.startsWith(".");
  80397. };
  80398. qmarksTestNoExtDot = ([$0]) => {
  80399. const len = $0.length;
  80400. return (f5) => f5.length === len && f5 !== "." && f5 !== "..";
  80401. };
  80402. defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
  80403. path3 = {
  80404. win32: { sep: "\\" },
  80405. posix: { sep: "/" }
  80406. };
  80407. sep = defaultPlatform === "win32" ? path3.win32.sep : path3.posix.sep;
  80408. minimatch.sep = sep;
  80409. GLOBSTAR = Symbol("globstar **");
  80410. minimatch.GLOBSTAR = GLOBSTAR;
  80411. plTypes = {
  80412. "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
  80413. "?": { open: "(?:", close: ")?" },
  80414. "+": { open: "(?:", close: ")+" },
  80415. "*": { open: "(?:", close: ")*" },
  80416. "@": { open: "(?:", close: ")" }
  80417. };
  80418. qmark = "[^/]";
  80419. star = qmark + "*?";
  80420. twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
  80421. twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
  80422. charSet = (s4) => s4.split("").reduce((set, c3) => {
  80423. set[c3] = true;
  80424. return set;
  80425. }, {});
  80426. reSpecials = charSet("().*{}+?[]^$\\!");
  80427. addPatternStartSet = charSet("[.(");
  80428. filter = (pattern, options = {}) => (p3) => minimatch(p3, pattern, options);
  80429. minimatch.filter = filter;
  80430. ext = (a3, b3 = {}) => Object.assign({}, a3, b3);
  80431. defaults = (def) => {
  80432. if (!def || typeof def !== "object" || !Object.keys(def).length) {
  80433. return minimatch;
  80434. }
  80435. const orig = minimatch;
  80436. const m4 = (p3, pattern, options = {}) => orig(p3, pattern, ext(def, options));
  80437. return Object.assign(m4, {
  80438. Minimatch: class Minimatch extends orig.Minimatch {
  80439. constructor(pattern, options = {}) {
  80440. super(pattern, ext(def, options));
  80441. }
  80442. static defaults(options) {
  80443. return orig.defaults(ext(def, options)).Minimatch;
  80444. }
  80445. },
  80446. unescape: (s4, options = {}) => orig.unescape(s4, ext(def, options)),
  80447. escape: (s4, options = {}) => orig.escape(s4, ext(def, options)),
  80448. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  80449. defaults: (options) => orig.defaults(ext(def, options)),
  80450. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  80451. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  80452. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  80453. sep: orig.sep,
  80454. GLOBSTAR
  80455. });
  80456. };
  80457. minimatch.defaults = defaults;
  80458. braceExpand = (pattern, options = {}) => {
  80459. assertValidPattern(pattern);
  80460. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  80461. return [pattern];
  80462. }
  80463. return (0, import_brace_expansion.default)(pattern);
  80464. };
  80465. minimatch.braceExpand = braceExpand;
  80466. MAX_PATTERN_LENGTH = 1024 * 64;
  80467. assertValidPattern = (pattern) => {
  80468. if (typeof pattern !== "string") {
  80469. throw new TypeError("invalid pattern");
  80470. }
  80471. if (pattern.length > MAX_PATTERN_LENGTH) {
  80472. throw new TypeError("pattern is too long");
  80473. }
  80474. };
  80475. makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  80476. minimatch.makeRe = makeRe;
  80477. match = (list, pattern, options = {}) => {
  80478. const mm = new Minimatch(pattern, options);
  80479. list = list.filter((f5) => mm.match(f5));
  80480. if (mm.options.nonull && !list.length) {
  80481. list.push(pattern);
  80482. }
  80483. return list;
  80484. };
  80485. minimatch.match = match;
  80486. globUnescape = (s4) => s4.replace(/\\(.)/g, "$1");
  80487. globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  80488. regExpEscape = (s4) => s4.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  80489. Minimatch = class {
  80490. options;
  80491. set;
  80492. pattern;
  80493. windowsPathsNoEscape;
  80494. nonegate;
  80495. negate;
  80496. comment;
  80497. empty;
  80498. preserveMultipleSlashes;
  80499. partial;
  80500. globSet;
  80501. globParts;
  80502. nocase;
  80503. isWindows;
  80504. platform;
  80505. windowsNoMagicRoot;
  80506. regexp;
  80507. constructor(pattern, options = {}) {
  80508. assertValidPattern(pattern);
  80509. options = options || {};
  80510. this.options = options;
  80511. this.pattern = pattern;
  80512. this.platform = options.platform || defaultPlatform;
  80513. this.isWindows = this.platform === "win32";
  80514. this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  80515. if (this.windowsPathsNoEscape) {
  80516. this.pattern = this.pattern.replace(/\\/g, "/");
  80517. }
  80518. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  80519. this.regexp = null;
  80520. this.negate = false;
  80521. this.nonegate = !!options.nonegate;
  80522. this.comment = false;
  80523. this.empty = false;
  80524. this.partial = !!options.partial;
  80525. this.nocase = !!this.options.nocase;
  80526. this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
  80527. this.globSet = [];
  80528. this.globParts = [];
  80529. this.set = [];
  80530. this.make();
  80531. }
  80532. hasMagic() {
  80533. if (this.options.magicalBraces && this.set.length > 1) {
  80534. return true;
  80535. }
  80536. for (const pattern of this.set) {
  80537. for (const part of pattern) {
  80538. if (typeof part !== "string")
  80539. return true;
  80540. }
  80541. }
  80542. return false;
  80543. }
  80544. debug(..._3) {
  80545. }
  80546. make() {
  80547. const pattern = this.pattern;
  80548. const options = this.options;
  80549. if (!options.nocomment && pattern.charAt(0) === "#") {
  80550. this.comment = true;
  80551. return;
  80552. }
  80553. if (!pattern) {
  80554. this.empty = true;
  80555. return;
  80556. }
  80557. this.parseNegate();
  80558. this.globSet = [...new Set(this.braceExpand())];
  80559. if (options.debug) {
  80560. this.debug = (...args) => console.error(...args);
  80561. }
  80562. this.debug(this.pattern, this.globSet);
  80563. const rawGlobParts = this.globSet.map((s4) => this.slashSplit(s4));
  80564. this.globParts = this.preprocess(rawGlobParts);
  80565. this.debug(this.pattern, this.globParts);
  80566. let set = this.globParts.map((s4, _3, __) => {
  80567. if (this.isWindows && this.windowsNoMagicRoot) {
  80568. const isUNC = s4[0] === "" && s4[1] === "" && (s4[2] === "?" || !globMagic.test(s4[2])) && !globMagic.test(s4[3]);
  80569. const isDrive = /^[a-z]:/i.test(s4[0]);
  80570. if (isUNC) {
  80571. return [...s4.slice(0, 4), ...s4.slice(4).map((ss) => this.parse(ss))];
  80572. } else if (isDrive) {
  80573. return [s4[0], ...s4.slice(1).map((ss) => this.parse(ss))];
  80574. }
  80575. }
  80576. return s4.map((ss) => this.parse(ss));
  80577. });
  80578. this.debug(this.pattern, set);
  80579. this.set = set.filter((s4) => s4.indexOf(false) === -1);
  80580. if (this.isWindows) {
  80581. for (let i4 = 0; i4 < this.set.length; i4++) {
  80582. const p3 = this.set[i4];
  80583. if (p3[0] === "" && p3[1] === "" && this.globParts[i4][2] === "?" && typeof p3[3] === "string" && /^[a-z]:$/i.test(p3[3])) {
  80584. p3[2] = "?";
  80585. }
  80586. }
  80587. }
  80588. this.debug(this.pattern, this.set);
  80589. }
  80590. // various transforms to equivalent pattern sets that are
  80591. // faster to process in a filesystem walk. The goal is to
  80592. // eliminate what we can, and push all ** patterns as far
  80593. // to the right as possible, even if it increases the number
  80594. // of patterns that we have to process.
  80595. preprocess(globParts) {
  80596. if (this.options.noglobstar) {
  80597. for (let i4 = 0; i4 < globParts.length; i4++) {
  80598. for (let j3 = 0; j3 < globParts[i4].length; j3++) {
  80599. if (globParts[i4][j3] === "**") {
  80600. globParts[i4][j3] = "*";
  80601. }
  80602. }
  80603. }
  80604. }
  80605. const { optimizationLevel = 1 } = this.options;
  80606. if (optimizationLevel >= 2) {
  80607. globParts = this.firstPhasePreProcess(globParts);
  80608. globParts = this.secondPhasePreProcess(globParts);
  80609. } else if (optimizationLevel >= 1) {
  80610. globParts = this.levelOneOptimize(globParts);
  80611. } else {
  80612. globParts = this.adjascentGlobstarOptimize(globParts);
  80613. }
  80614. return globParts;
  80615. }
  80616. // just get rid of adjascent ** portions
  80617. adjascentGlobstarOptimize(globParts) {
  80618. return globParts.map((parts) => {
  80619. let gs = -1;
  80620. while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
  80621. let i4 = gs;
  80622. while (parts[i4 + 1] === "**") {
  80623. i4++;
  80624. }
  80625. if (i4 !== gs) {
  80626. parts.splice(gs, i4 - gs);
  80627. }
  80628. }
  80629. return parts;
  80630. });
  80631. }
  80632. // get rid of adjascent ** and resolve .. portions
  80633. levelOneOptimize(globParts) {
  80634. return globParts.map((parts) => {
  80635. parts = parts.reduce((set, part) => {
  80636. const prev = set[set.length - 1];
  80637. if (part === "**" && prev === "**") {
  80638. return set;
  80639. }
  80640. if (part === "..") {
  80641. if (prev && prev !== ".." && prev !== "." && prev !== "**") {
  80642. set.pop();
  80643. return set;
  80644. }
  80645. }
  80646. set.push(part);
  80647. return set;
  80648. }, []);
  80649. return parts.length === 0 ? [""] : parts;
  80650. });
  80651. }
  80652. levelTwoFileOptimize(parts) {
  80653. if (!Array.isArray(parts)) {
  80654. parts = this.slashSplit(parts);
  80655. }
  80656. let didSomething = false;
  80657. do {
  80658. didSomething = false;
  80659. if (!this.preserveMultipleSlashes) {
  80660. for (let i4 = 1; i4 < parts.length - 1; i4++) {
  80661. const p3 = parts[i4];
  80662. if (i4 === 1 && p3 === "" && parts[0] === "")
  80663. continue;
  80664. if (p3 === "." || p3 === "") {
  80665. didSomething = true;
  80666. parts.splice(i4, 1);
  80667. i4--;
  80668. }
  80669. }
  80670. if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
  80671. didSomething = true;
  80672. parts.pop();
  80673. }
  80674. }
  80675. let dd = 0;
  80676. while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
  80677. const p3 = parts[dd - 1];
  80678. if (p3 && p3 !== "." && p3 !== ".." && p3 !== "**") {
  80679. didSomething = true;
  80680. parts.splice(dd - 1, 2);
  80681. dd -= 2;
  80682. }
  80683. }
  80684. } while (didSomething);
  80685. return parts.length === 0 ? [""] : parts;
  80686. }
  80687. // First phase: single-pattern processing
  80688. // <pre> is 1 or more portions
  80689. // <rest> is 1 or more portions
  80690. // <p> is any portion other than ., .., '', or **
  80691. // <e> is . or ''
  80692. //
  80693. // **/.. is *brutal* for filesystem walking performance, because
  80694. // it effectively resets the recursive walk each time it occurs,
  80695. // and ** cannot be reduced out by a .. pattern part like a regexp
  80696. // or most strings (other than .., ., and '') can be.
  80697. //
  80698. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  80699. // <pre>/<e>/<rest> -> <pre>/<rest>
  80700. // <pre>/<p>/../<rest> -> <pre>/<rest>
  80701. // **/**/<rest> -> **/<rest>
  80702. //
  80703. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  80704. // this WOULD be allowed if ** did follow symlinks, or * didn't
  80705. firstPhasePreProcess(globParts) {
  80706. let didSomething = false;
  80707. do {
  80708. didSomething = false;
  80709. for (let parts of globParts) {
  80710. let gs = -1;
  80711. while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
  80712. let gss = gs;
  80713. while (parts[gss + 1] === "**") {
  80714. gss++;
  80715. }
  80716. if (gss > gs) {
  80717. parts.splice(gs + 1, gss - gs);
  80718. }
  80719. let next = parts[gs + 1];
  80720. const p3 = parts[gs + 2];
  80721. const p22 = parts[gs + 3];
  80722. if (next !== "..")
  80723. continue;
  80724. if (!p3 || p3 === "." || p3 === ".." || !p22 || p22 === "." || p22 === "..") {
  80725. continue;
  80726. }
  80727. didSomething = true;
  80728. parts.splice(gs, 1);
  80729. const other = parts.slice(0);
  80730. other[gs] = "**";
  80731. globParts.push(other);
  80732. gs--;
  80733. }
  80734. if (!this.preserveMultipleSlashes) {
  80735. for (let i4 = 1; i4 < parts.length - 1; i4++) {
  80736. const p3 = parts[i4];
  80737. if (i4 === 1 && p3 === "" && parts[0] === "")
  80738. continue;
  80739. if (p3 === "." || p3 === "") {
  80740. didSomething = true;
  80741. parts.splice(i4, 1);
  80742. i4--;
  80743. }
  80744. }
  80745. if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
  80746. didSomething = true;
  80747. parts.pop();
  80748. }
  80749. }
  80750. let dd = 0;
  80751. while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
  80752. const p3 = parts[dd - 1];
  80753. if (p3 && p3 !== "." && p3 !== ".." && p3 !== "**") {
  80754. didSomething = true;
  80755. const needDot = dd === 1 && parts[dd + 1] === "**";
  80756. const splin = needDot ? ["."] : [];
  80757. parts.splice(dd - 1, 2, ...splin);
  80758. if (parts.length === 0)
  80759. parts.push("");
  80760. dd -= 2;
  80761. }
  80762. }
  80763. }
  80764. } while (didSomething);
  80765. return globParts;
  80766. }
  80767. // second phase: multi-pattern dedupes
  80768. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  80769. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  80770. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  80771. //
  80772. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  80773. // ^-- not valid because ** doens't follow symlinks
  80774. secondPhasePreProcess(globParts) {
  80775. for (let i4 = 0; i4 < globParts.length - 1; i4++) {
  80776. for (let j3 = i4 + 1; j3 < globParts.length; j3++) {
  80777. const matched = this.partsMatch(globParts[i4], globParts[j3], !this.preserveMultipleSlashes);
  80778. if (!matched)
  80779. continue;
  80780. globParts[i4] = matched;
  80781. globParts[j3] = [];
  80782. }
  80783. }
  80784. return globParts.filter((gs) => gs.length);
  80785. }
  80786. partsMatch(a3, b3, emptyGSMatch = false) {
  80787. let ai = 0;
  80788. let bi = 0;
  80789. let result = [];
  80790. let which = "";
  80791. while (ai < a3.length && bi < b3.length) {
  80792. if (a3[ai] === b3[bi]) {
  80793. result.push(which === "b" ? b3[bi] : a3[ai]);
  80794. ai++;
  80795. bi++;
  80796. } else if (emptyGSMatch && a3[ai] === "**" && b3[bi] === a3[ai + 1]) {
  80797. result.push(a3[ai]);
  80798. ai++;
  80799. } else if (emptyGSMatch && b3[bi] === "**" && a3[ai] === b3[bi + 1]) {
  80800. result.push(b3[bi]);
  80801. bi++;
  80802. } else if (a3[ai] === "*" && b3[bi] && (this.options.dot || !b3[bi].startsWith(".")) && b3[bi] !== "**") {
  80803. if (which === "b")
  80804. return false;
  80805. which = "a";
  80806. result.push(a3[ai]);
  80807. ai++;
  80808. bi++;
  80809. } else if (b3[bi] === "*" && a3[ai] && (this.options.dot || !a3[ai].startsWith(".")) && a3[ai] !== "**") {
  80810. if (which === "a")
  80811. return false;
  80812. which = "b";
  80813. result.push(b3[bi]);
  80814. ai++;
  80815. bi++;
  80816. } else {
  80817. return false;
  80818. }
  80819. }
  80820. return a3.length === b3.length && result;
  80821. }
  80822. parseNegate() {
  80823. if (this.nonegate)
  80824. return;
  80825. const pattern = this.pattern;
  80826. let negate = false;
  80827. let negateOffset = 0;
  80828. for (let i4 = 0; i4 < pattern.length && pattern.charAt(i4) === "!"; i4++) {
  80829. negate = !negate;
  80830. negateOffset++;
  80831. }
  80832. if (negateOffset)
  80833. this.pattern = pattern.slice(negateOffset);
  80834. this.negate = negate;
  80835. }
  80836. // set partial to true to test if, for example,
  80837. // "/a/b" matches the start of "/*/b/*/d"
  80838. // Partial means, if you run out of file before you run
  80839. // out of pattern, then that's fine, as long as all
  80840. // the parts match.
  80841. matchOne(file, pattern, partial = false) {
  80842. const options = this.options;
  80843. if (this.isWindows) {
  80844. const fileUNC = file[0] === "" && file[1] === "" && file[2] === "?" && typeof file[3] === "string" && /^[a-z]:$/i.test(file[3]);
  80845. const patternUNC = pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
  80846. if (fileUNC && patternUNC) {
  80847. const fd = file[3];
  80848. const pd = pattern[3];
  80849. if (fd.toLowerCase() === pd.toLowerCase()) {
  80850. file[3] = pd;
  80851. }
  80852. } else if (patternUNC && typeof file[0] === "string") {
  80853. const pd = pattern[3];
  80854. const fd = file[0];
  80855. if (pd.toLowerCase() === fd.toLowerCase()) {
  80856. pattern[3] = fd;
  80857. pattern = pattern.slice(3);
  80858. }
  80859. } else if (fileUNC && typeof pattern[0] === "string") {
  80860. const fd = file[3];
  80861. if (fd.toLowerCase() === pattern[0].toLowerCase()) {
  80862. pattern[0] = fd;
  80863. file = file.slice(3);
  80864. }
  80865. }
  80866. }
  80867. const { optimizationLevel = 1 } = this.options;
  80868. if (optimizationLevel >= 2) {
  80869. file = this.levelTwoFileOptimize(file);
  80870. }
  80871. this.debug("matchOne", this, { file, pattern });
  80872. this.debug("matchOne", file.length, pattern.length);
  80873. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  80874. this.debug("matchOne loop");
  80875. var p3 = pattern[pi];
  80876. var f5 = file[fi];
  80877. this.debug(pattern, p3, f5);
  80878. if (p3 === false) {
  80879. return false;
  80880. }
  80881. if (p3 === GLOBSTAR) {
  80882. this.debug("GLOBSTAR", [pattern, p3, f5]);
  80883. var fr = fi;
  80884. var pr = pi + 1;
  80885. if (pr === pl) {
  80886. this.debug("** at the end");
  80887. for (; fi < fl; fi++) {
  80888. if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
  80889. return false;
  80890. }
  80891. return true;
  80892. }
  80893. while (fr < fl) {
  80894. var swallowee = file[fr];
  80895. this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
  80896. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  80897. this.debug("globstar found match!", fr, fl, swallowee);
  80898. return true;
  80899. } else {
  80900. if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
  80901. this.debug("dot detected!", file, fr, pattern, pr);
  80902. break;
  80903. }
  80904. this.debug("globstar swallow a segment, and continue");
  80905. fr++;
  80906. }
  80907. }
  80908. if (partial) {
  80909. this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
  80910. if (fr === fl) {
  80911. return true;
  80912. }
  80913. }
  80914. return false;
  80915. }
  80916. let hit;
  80917. if (typeof p3 === "string") {
  80918. hit = f5 === p3;
  80919. this.debug("string match", p3, f5, hit);
  80920. } else {
  80921. hit = p3.test(f5);
  80922. this.debug("pattern match", p3, f5, hit);
  80923. }
  80924. if (!hit)
  80925. return false;
  80926. }
  80927. if (fi === fl && pi === pl) {
  80928. return true;
  80929. } else if (fi === fl) {
  80930. return partial;
  80931. } else if (pi === pl) {
  80932. return fi === fl - 1 && file[fi] === "";
  80933. } else {
  80934. throw new Error("wtf?");
  80935. }
  80936. }
  80937. braceExpand() {
  80938. return braceExpand(this.pattern, this.options);
  80939. }
  80940. parse(pattern) {
  80941. assertValidPattern(pattern);
  80942. const options = this.options;
  80943. if (pattern === "**")
  80944. return GLOBSTAR;
  80945. if (pattern === "")
  80946. return "";
  80947. let m4;
  80948. let fastTest = null;
  80949. if (m4 = pattern.match(starRE)) {
  80950. fastTest = options.dot ? starTestDot : starTest;
  80951. } else if (m4 = pattern.match(starDotExtRE)) {
  80952. fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m4[1]);
  80953. } else if (m4 = pattern.match(qmarksRE)) {
  80954. fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m4);
  80955. } else if (m4 = pattern.match(starDotStarRE)) {
  80956. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  80957. } else if (m4 = pattern.match(dotStarRE)) {
  80958. fastTest = dotStarTest;
  80959. }
  80960. let re = "";
  80961. let hasMagic = false;
  80962. let escaping = false;
  80963. const patternListStack = [];
  80964. const negativeLists = [];
  80965. let stateChar = false;
  80966. let uflag = false;
  80967. let pl;
  80968. let dotTravAllowed = pattern.charAt(0) === ".";
  80969. let dotFileAllowed = options.dot || dotTravAllowed;
  80970. const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
  80971. const subPatternStart = (p3) => p3.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
  80972. const clearStateChar = () => {
  80973. if (stateChar) {
  80974. switch (stateChar) {
  80975. case "*":
  80976. re += star;
  80977. hasMagic = true;
  80978. break;
  80979. case "?":
  80980. re += qmark;
  80981. hasMagic = true;
  80982. break;
  80983. default:
  80984. re += "\\" + stateChar;
  80985. break;
  80986. }
  80987. this.debug("clearStateChar %j %j", stateChar, re);
  80988. stateChar = false;
  80989. }
  80990. };
  80991. for (let i4 = 0, c3; i4 < pattern.length && (c3 = pattern.charAt(i4)); i4++) {
  80992. this.debug("%s %s %s %j", pattern, i4, re, c3);
  80993. if (escaping) {
  80994. if (c3 === "/") {
  80995. return false;
  80996. }
  80997. if (reSpecials[c3]) {
  80998. re += "\\";
  80999. }
  81000. re += c3;
  81001. escaping = false;
  81002. continue;
  81003. }
  81004. switch (c3) {
  81005. // Should already be path-split by now.
  81006. /* c8 ignore start */
  81007. case "/": {
  81008. return false;
  81009. }
  81010. /* c8 ignore stop */
  81011. case "\\":
  81012. clearStateChar();
  81013. escaping = true;
  81014. continue;
  81015. // the various stateChar values
  81016. // for the "extglob" stuff.
  81017. case "?":
  81018. case "*":
  81019. case "+":
  81020. case "@":
  81021. case "!":
  81022. this.debug("%s %s %s %j <-- stateChar", pattern, i4, re, c3);
  81023. this.debug("call clearStateChar %j", stateChar);
  81024. clearStateChar();
  81025. stateChar = c3;
  81026. if (options.noext)
  81027. clearStateChar();
  81028. continue;
  81029. case "(": {
  81030. if (!stateChar) {
  81031. re += "\\(";
  81032. continue;
  81033. }
  81034. const plEntry = {
  81035. type: stateChar,
  81036. start: i4 - 1,
  81037. reStart: re.length,
  81038. open: plTypes[stateChar].open,
  81039. close: plTypes[stateChar].close
  81040. };
  81041. this.debug(this.pattern, " ", plEntry);
  81042. patternListStack.push(plEntry);
  81043. re += plEntry.open;
  81044. if (plEntry.start === 0 && plEntry.type !== "!") {
  81045. dotTravAllowed = true;
  81046. re += subPatternStart(pattern.slice(i4 + 1));
  81047. }
  81048. this.debug("plType %j %j", stateChar, re);
  81049. stateChar = false;
  81050. continue;
  81051. }
  81052. case ")": {
  81053. const plEntry = patternListStack[patternListStack.length - 1];
  81054. if (!plEntry) {
  81055. re += "\\)";
  81056. continue;
  81057. }
  81058. patternListStack.pop();
  81059. clearStateChar();
  81060. hasMagic = true;
  81061. pl = plEntry;
  81062. re += pl.close;
  81063. if (pl.type === "!") {
  81064. negativeLists.push(Object.assign(pl, { reEnd: re.length }));
  81065. }
  81066. continue;
  81067. }
  81068. case "|": {
  81069. const plEntry = patternListStack[patternListStack.length - 1];
  81070. if (!plEntry) {
  81071. re += "\\|";
  81072. continue;
  81073. }
  81074. clearStateChar();
  81075. re += "|";
  81076. if (plEntry.start === 0 && plEntry.type !== "!") {
  81077. dotTravAllowed = true;
  81078. re += subPatternStart(pattern.slice(i4 + 1));
  81079. }
  81080. continue;
  81081. }
  81082. // these are mostly the same in regexp and glob
  81083. case "[":
  81084. clearStateChar();
  81085. const [src, needUflag, consumed, magic] = parseClass(pattern, i4);
  81086. if (consumed) {
  81087. re += src;
  81088. uflag = uflag || needUflag;
  81089. i4 += consumed - 1;
  81090. hasMagic = hasMagic || magic;
  81091. } else {
  81092. re += "\\[";
  81093. }
  81094. continue;
  81095. case "]":
  81096. re += "\\" + c3;
  81097. continue;
  81098. default:
  81099. clearStateChar();
  81100. re += regExpEscape(c3);
  81101. break;
  81102. }
  81103. }
  81104. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
  81105. let tail;
  81106. tail = re.slice(pl.reStart + pl.open.length);
  81107. this.debug(this.pattern, "setting tail", re, pl);
  81108. tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_3, $1, $2) => {
  81109. if (!$2) {
  81110. $2 = "\\";
  81111. }
  81112. return $1 + $1 + $2 + "|";
  81113. });
  81114. this.debug("tail=%j\n %s", tail, tail, pl, re);
  81115. const t4 = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
  81116. hasMagic = true;
  81117. re = re.slice(0, pl.reStart) + t4 + "\\(" + tail;
  81118. }
  81119. clearStateChar();
  81120. if (escaping) {
  81121. re += "\\\\";
  81122. }
  81123. const addPatternStart = addPatternStartSet[re.charAt(0)];
  81124. for (let n3 = negativeLists.length - 1; n3 > -1; n3--) {
  81125. const nl = negativeLists[n3];
  81126. const nlBefore = re.slice(0, nl.reStart);
  81127. const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
  81128. let nlAfter = re.slice(nl.reEnd);
  81129. const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
  81130. const closeParensBefore = nlBefore.split(")").length;
  81131. const openParensBefore = nlBefore.split("(").length - closeParensBefore;
  81132. let cleanAfter = nlAfter;
  81133. for (let i4 = 0; i4 < openParensBefore; i4++) {
  81134. cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
  81135. }
  81136. nlAfter = cleanAfter;
  81137. const dollar = nlAfter === "" ? "(?:$|\\/)" : "";
  81138. re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
  81139. }
  81140. if (re !== "" && hasMagic) {
  81141. re = "(?=.)" + re;
  81142. }
  81143. if (addPatternStart) {
  81144. re = patternStart() + re;
  81145. }
  81146. if (options.nocase && !hasMagic && !options.nocaseMagicOnly) {
  81147. hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
  81148. }
  81149. if (!hasMagic) {
  81150. return globUnescape(re);
  81151. }
  81152. const flags = (options.nocase ? "i" : "") + (uflag ? "u" : "");
  81153. try {
  81154. const ext2 = fastTest ? {
  81155. _glob: pattern,
  81156. _src: re,
  81157. test: fastTest
  81158. } : {
  81159. _glob: pattern,
  81160. _src: re
  81161. };
  81162. return Object.assign(new RegExp("^" + re + "$", flags), ext2);
  81163. } catch (er) {
  81164. this.debug("invalid regexp", er);
  81165. return new RegExp("$.");
  81166. }
  81167. }
  81168. makeRe() {
  81169. if (this.regexp || this.regexp === false)
  81170. return this.regexp;
  81171. const set = this.set;
  81172. if (!set.length) {
  81173. this.regexp = false;
  81174. return this.regexp;
  81175. }
  81176. const options = this.options;
  81177. const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
  81178. const flags = options.nocase ? "i" : "";
  81179. let re = set.map((pattern) => {
  81180. const pp = pattern.map((p3) => typeof p3 === "string" ? regExpEscape(p3) : p3 === GLOBSTAR ? GLOBSTAR : p3._src);
  81181. pp.forEach((p3, i4) => {
  81182. const next = pp[i4 + 1];
  81183. const prev = pp[i4 - 1];
  81184. if (p3 !== GLOBSTAR || prev === GLOBSTAR) {
  81185. return;
  81186. }
  81187. if (prev === void 0) {
  81188. if (next !== void 0 && next !== GLOBSTAR) {
  81189. pp[i4 + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
  81190. } else {
  81191. pp[i4] = twoStar;
  81192. }
  81193. } else if (next === void 0) {
  81194. pp[i4 - 1] = prev + "(?:\\/|" + twoStar + ")?";
  81195. } else if (next !== GLOBSTAR) {
  81196. pp[i4 - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
  81197. pp[i4 + 1] = GLOBSTAR;
  81198. }
  81199. });
  81200. return pp.filter((p3) => p3 !== GLOBSTAR).join("/");
  81201. }).join("|");
  81202. re = "^(?:" + re + ")$";
  81203. if (this.negate)
  81204. re = "^(?!" + re + ").*$";
  81205. try {
  81206. this.regexp = new RegExp(re, flags);
  81207. } catch (ex) {
  81208. this.regexp = false;
  81209. }
  81210. return this.regexp;
  81211. }
  81212. slashSplit(p3) {
  81213. if (this.preserveMultipleSlashes) {
  81214. return p3.split("/");
  81215. } else if (this.isWindows && /^\/\/[^\/]+/.test(p3)) {
  81216. return ["", ...p3.split(/\/+/)];
  81217. } else {
  81218. return p3.split(/\/+/);
  81219. }
  81220. }
  81221. match(f5, partial = this.partial) {
  81222. this.debug("match", f5, this.pattern);
  81223. if (this.comment) {
  81224. return false;
  81225. }
  81226. if (this.empty) {
  81227. return f5 === "";
  81228. }
  81229. if (f5 === "/" && partial) {
  81230. return true;
  81231. }
  81232. const options = this.options;
  81233. if (this.isWindows) {
  81234. f5 = f5.split("\\").join("/");
  81235. }
  81236. const ff = this.slashSplit(f5);
  81237. this.debug(this.pattern, "split", ff);
  81238. const set = this.set;
  81239. this.debug(this.pattern, "set", set);
  81240. let filename = ff[ff.length - 1];
  81241. if (!filename) {
  81242. for (let i4 = ff.length - 2; !filename && i4 >= 0; i4--) {
  81243. filename = ff[i4];
  81244. }
  81245. }
  81246. for (let i4 = 0; i4 < set.length; i4++) {
  81247. const pattern = set[i4];
  81248. let file = ff;
  81249. if (options.matchBase && pattern.length === 1) {
  81250. file = [filename];
  81251. }
  81252. const hit = this.matchOne(file, pattern, partial);
  81253. if (hit) {
  81254. if (options.flipNegate) {
  81255. return true;
  81256. }
  81257. return !this.negate;
  81258. }
  81259. }
  81260. if (options.flipNegate) {
  81261. return false;
  81262. }
  81263. return this.negate;
  81264. }
  81265. static defaults(def) {
  81266. return minimatch.defaults(def).Minimatch;
  81267. }
  81268. };
  81269. minimatch.Minimatch = Minimatch;
  81270. minimatch.escape = escape;
  81271. minimatch.unescape = unescape2;
  81272. }
  81273. });
  81274. // src/cli/commands/mysqlIntrospect.ts
  81275. var mysqlIntrospect_exports = {};
  81276. __export(mysqlIntrospect_exports, {
  81277. mysqlPushIntrospect: () => mysqlPushIntrospect
  81278. });
  81279. var import_hanji9, mysqlPushIntrospect;
  81280. var init_mysqlIntrospect = __esm({
  81281. "src/cli/commands/mysqlIntrospect.ts"() {
  81282. "use strict";
  81283. import_hanji9 = __toESM(require_hanji());
  81284. init_mjs();
  81285. init_global();
  81286. init_mysqlSerializer();
  81287. init_views();
  81288. mysqlPushIntrospect = async (db, databaseName, filters) => {
  81289. const matchers = filters.map((it) => {
  81290. return new Minimatch(it);
  81291. });
  81292. const filter2 = (tableName) => {
  81293. if (matchers.length === 0) return true;
  81294. let flags = [];
  81295. for (let matcher of matchers) {
  81296. if (matcher.negate) {
  81297. if (!matcher.match(tableName)) {
  81298. flags.push(false);
  81299. }
  81300. }
  81301. if (matcher.match(tableName)) {
  81302. flags.push(true);
  81303. }
  81304. }
  81305. if (flags.length > 0) {
  81306. return flags.every(Boolean);
  81307. }
  81308. return false;
  81309. };
  81310. const progress = new ProgressView(
  81311. "Pulling schema from database...",
  81312. "Pulling schema from database..."
  81313. );
  81314. const res = await (0, import_hanji9.renderWithTask)(
  81315. progress,
  81316. fromDatabase(db, databaseName, filter2)
  81317. );
  81318. const schema6 = { id: originUUID, prevId: "", ...res };
  81319. const { internal, ...schemaWithoutInternals } = schema6;
  81320. return { schema: schemaWithoutInternals };
  81321. };
  81322. }
  81323. });
  81324. // src/cli/commands/singlestoreIntrospect.ts
  81325. var singlestoreIntrospect_exports = {};
  81326. __export(singlestoreIntrospect_exports, {
  81327. singlestorePushIntrospect: () => singlestorePushIntrospect
  81328. });
  81329. var import_hanji10, singlestorePushIntrospect;
  81330. var init_singlestoreIntrospect = __esm({
  81331. "src/cli/commands/singlestoreIntrospect.ts"() {
  81332. "use strict";
  81333. import_hanji10 = __toESM(require_hanji());
  81334. init_mjs();
  81335. init_global();
  81336. init_singlestoreSerializer();
  81337. init_views();
  81338. singlestorePushIntrospect = async (db, databaseName, filters) => {
  81339. const matchers = filters.map((it) => {
  81340. return new Minimatch(it);
  81341. });
  81342. const filter2 = (tableName) => {
  81343. if (matchers.length === 0) return true;
  81344. let flags = [];
  81345. for (let matcher of matchers) {
  81346. if (matcher.negate) {
  81347. if (!matcher.match(tableName)) {
  81348. flags.push(false);
  81349. }
  81350. }
  81351. if (matcher.match(tableName)) {
  81352. flags.push(true);
  81353. }
  81354. }
  81355. if (flags.length > 0) {
  81356. return flags.every(Boolean);
  81357. }
  81358. return false;
  81359. };
  81360. const progress = new ProgressView(
  81361. "Pulling schema from database...",
  81362. "Pulling schema from database..."
  81363. );
  81364. const res = await (0, import_hanji10.renderWithTask)(
  81365. progress,
  81366. fromDatabase4(db, databaseName, filter2)
  81367. );
  81368. const schema6 = { id: originUUID, prevId: "", ...res };
  81369. const { internal, ...schemaWithoutInternals } = schema6;
  81370. return { schema: schemaWithoutInternals };
  81371. };
  81372. }
  81373. });
  81374. // src/cli/commands/pgIntrospect.ts
  81375. var pgIntrospect_exports = {};
  81376. __export(pgIntrospect_exports, {
  81377. pgPushIntrospect: () => pgPushIntrospect
  81378. });
  81379. var import_hanji11, pgPushIntrospect;
  81380. var init_pgIntrospect = __esm({
  81381. "src/cli/commands/pgIntrospect.ts"() {
  81382. "use strict";
  81383. import_hanji11 = __toESM(require_hanji());
  81384. init_mjs();
  81385. init_global();
  81386. init_pgSerializer();
  81387. init_views();
  81388. pgPushIntrospect = async (db, filters, schemaFilters, entities, tsSchema) => {
  81389. const matchers = filters.map((it) => {
  81390. return new Minimatch(it);
  81391. });
  81392. const filter2 = (tableName) => {
  81393. if (matchers.length === 0) return true;
  81394. let flags = [];
  81395. for (let matcher of matchers) {
  81396. if (matcher.negate) {
  81397. if (!matcher.match(tableName)) {
  81398. flags.push(false);
  81399. }
  81400. }
  81401. if (matcher.match(tableName)) {
  81402. flags.push(true);
  81403. }
  81404. }
  81405. if (flags.length > 0) {
  81406. return flags.every(Boolean);
  81407. }
  81408. return false;
  81409. };
  81410. const progress = new ProgressView(
  81411. "Pulling schema from database...",
  81412. "Pulling schema from database..."
  81413. );
  81414. const res = await (0, import_hanji11.renderWithTask)(
  81415. progress,
  81416. fromDatabase2(db, filter2, schemaFilters, entities, void 0, tsSchema)
  81417. );
  81418. const schema6 = { id: originUUID, prevId: "", ...res };
  81419. const { internal, ...schemaWithoutInternals } = schema6;
  81420. return { schema: schemaWithoutInternals };
  81421. };
  81422. }
  81423. });
  81424. // src/introspect-sqlite.ts
  81425. var import_casing2, sqliteImportsList, indexName4, objToStatement2, relations, escapeColumnKey, withCasing, dbColumnName, schemaToTypeScript, isCyclic, isSelf, mapColumnDefault, column6, createTableColumns, createTableIndexes, createTableUniques, createTableChecks, createTablePKs, createTableFKs;
  81426. var init_introspect_sqlite = __esm({
  81427. "src/introspect-sqlite.ts"() {
  81428. "use strict";
  81429. import_casing2 = require("drizzle-orm/casing");
  81430. init_utils();
  81431. init_global();
  81432. sqliteImportsList = /* @__PURE__ */ new Set([
  81433. "sqliteTable",
  81434. "integer",
  81435. "real",
  81436. "text",
  81437. "numeric",
  81438. "blob"
  81439. ]);
  81440. indexName4 = (tableName, columns) => {
  81441. return `${tableName}_${columns.join("_")}_index`;
  81442. };
  81443. objToStatement2 = (json) => {
  81444. json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
  81445. const keys = Object.keys(json);
  81446. if (keys.length === 0) return;
  81447. let statement = "{ ";
  81448. statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
  81449. statement += " }";
  81450. return statement;
  81451. };
  81452. relations = /* @__PURE__ */ new Set();
  81453. escapeColumnKey = (value) => {
  81454. if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
  81455. return `"${value}"`;
  81456. }
  81457. return value;
  81458. };
  81459. withCasing = (value, casing2) => {
  81460. if (casing2 === "preserve") {
  81461. return escapeColumnKey(value);
  81462. }
  81463. if (casing2 === "camel") {
  81464. return escapeColumnKey(value.camelCase());
  81465. }
  81466. return value;
  81467. };
  81468. dbColumnName = ({ name, casing: casing2, withMode = false }) => {
  81469. if (casing2 === "preserve") {
  81470. return "";
  81471. }
  81472. if (casing2 === "camel") {
  81473. return (0, import_casing2.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
  81474. }
  81475. assertUnreachable(casing2);
  81476. };
  81477. schemaToTypeScript = (schema6, casing2) => {
  81478. Object.values(schema6.tables).forEach((table6) => {
  81479. Object.values(table6.foreignKeys).forEach((fk5) => {
  81480. const relation = `${fk5.tableFrom}-${fk5.tableTo}`;
  81481. relations.add(relation);
  81482. });
  81483. });
  81484. const imports = Object.values(schema6.tables).reduce(
  81485. (res, it) => {
  81486. const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
  81487. const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
  81488. const pkImports = Object.values(it.compositePrimaryKeys).map(
  81489. (it2) => "primaryKey"
  81490. );
  81491. const uniqueImports = Object.values(it.uniqueConstraints).map(
  81492. (it2) => "unique"
  81493. );
  81494. const checkImports = Object.values(it.checkConstraints).map(
  81495. (it2) => "check"
  81496. );
  81497. res.sqlite.push(...idxImports);
  81498. res.sqlite.push(...fkImpots);
  81499. res.sqlite.push(...pkImports);
  81500. res.sqlite.push(...uniqueImports);
  81501. res.sqlite.push(...checkImports);
  81502. const columnImports = Object.values(it.columns).map((col) => {
  81503. return col.type;
  81504. }).filter((type) => {
  81505. return sqliteImportsList.has(type);
  81506. });
  81507. res.sqlite.push(...columnImports);
  81508. return res;
  81509. },
  81510. { sqlite: [] }
  81511. );
  81512. Object.values(schema6.views).forEach((it) => {
  81513. imports.sqlite.push("sqliteView");
  81514. const columnImports = Object.values(it.columns).map((col) => {
  81515. return col.type;
  81516. }).filter((type) => {
  81517. return sqliteImportsList.has(type);
  81518. });
  81519. imports.sqlite.push(...columnImports);
  81520. });
  81521. const tableStatements = Object.values(schema6.tables).map((table6) => {
  81522. const func = "sqliteTable";
  81523. let statement = "";
  81524. if (imports.sqlite.includes(withCasing(table6.name, casing2))) {
  81525. statement = `// Table name is in conflict with ${withCasing(
  81526. table6.name,
  81527. casing2
  81528. )} import.
  81529. // Please change to any other name, that is not in imports list
  81530. `;
  81531. }
  81532. statement += `export const ${withCasing(table6.name, casing2)} = ${func}("${table6.name}", {
  81533. `;
  81534. statement += createTableColumns(
  81535. Object.values(table6.columns),
  81536. Object.values(table6.foreignKeys),
  81537. casing2
  81538. );
  81539. statement += "}";
  81540. const filteredFKs = Object.values(table6.foreignKeys).filter((it) => {
  81541. return it.columnsFrom.length > 1 || isSelf(it);
  81542. });
  81543. if (Object.keys(table6.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table6.compositePrimaryKeys).length > 0 || Object.keys(table6.uniqueConstraints).length > 0 || Object.keys(table6.checkConstraints).length > 0) {
  81544. statement += ",\n";
  81545. statement += "(table) => [";
  81546. statement += createTableIndexes(
  81547. table6.name,
  81548. Object.values(table6.indexes),
  81549. casing2
  81550. );
  81551. statement += createTableFKs(Object.values(filteredFKs), casing2);
  81552. statement += createTablePKs(
  81553. Object.values(table6.compositePrimaryKeys),
  81554. casing2
  81555. );
  81556. statement += createTableUniques(
  81557. Object.values(table6.uniqueConstraints),
  81558. casing2
  81559. );
  81560. statement += createTableChecks(
  81561. Object.values(table6.checkConstraints),
  81562. casing2
  81563. );
  81564. statement += "\n]";
  81565. }
  81566. statement += ");";
  81567. return statement;
  81568. });
  81569. const viewsStatements = Object.values(schema6.views).map((view5) => {
  81570. var _a2;
  81571. const func = "sqliteView";
  81572. let statement = "";
  81573. if (imports.sqlite.includes(withCasing(view5.name, casing2))) {
  81574. statement = `// Table name is in conflict with ${withCasing(
  81575. view5.name,
  81576. casing2
  81577. )} import.
  81578. // Please change to any other name, that is not in imports list
  81579. `;
  81580. }
  81581. statement += `export const ${withCasing(view5.name, casing2)} = ${func}("${view5.name}", {
  81582. `;
  81583. statement += createTableColumns(
  81584. Object.values(view5.columns),
  81585. [],
  81586. casing2
  81587. );
  81588. statement += "})";
  81589. statement += `.as(sql\`${(_a2 = view5.definition) == null ? void 0 : _a2.replaceAll("`", "\\`")}\`);`;
  81590. return statement;
  81591. });
  81592. const uniqueSqliteImports = [
  81593. "sqliteTable",
  81594. "AnySQLiteColumn",
  81595. ...new Set(imports.sqlite)
  81596. ];
  81597. const importsTs = `import { ${uniqueSqliteImports.join(
  81598. ", "
  81599. )} } from "drizzle-orm/sqlite-core"
  81600. import { sql } from "drizzle-orm"
  81601. `;
  81602. let decalrations = tableStatements.join("\n\n");
  81603. decalrations += "\n\n";
  81604. decalrations += viewsStatements.join("\n\n");
  81605. const file = importsTs + decalrations;
  81606. const schemaEntry = `
  81607. {
  81608. ${Object.values(schema6.tables).map((it) => withCasing(it.name, casing2)).join(",")}
  81609. }
  81610. `;
  81611. return { file, imports: importsTs, decalrations, schemaEntry };
  81612. };
  81613. isCyclic = (fk5) => {
  81614. const key = `${fk5.tableFrom}-${fk5.tableTo}`;
  81615. const reverse = `${fk5.tableTo}-${fk5.tableFrom}`;
  81616. return relations.has(key) && relations.has(reverse);
  81617. };
  81618. isSelf = (fk5) => {
  81619. return fk5.tableFrom === fk5.tableTo;
  81620. };
  81621. mapColumnDefault = (defaultValue) => {
  81622. if (typeof defaultValue === "string" && defaultValue.startsWith("(") && defaultValue.endsWith(")")) {
  81623. return `sql\`${defaultValue}\``;
  81624. }
  81625. if (defaultValue === "NULL") {
  81626. return `sql\`NULL\``;
  81627. }
  81628. if (typeof defaultValue === "string") {
  81629. return defaultValue.substring(1, defaultValue.length - 1).replaceAll('"', '\\"').replaceAll("''", "'");
  81630. }
  81631. return defaultValue;
  81632. };
  81633. column6 = (type, name, defaultValue, autoincrement, casing2) => {
  81634. let lowered = type;
  81635. casing2 = casing2;
  81636. if (lowered === "integer") {
  81637. let out = `${withCasing(name, casing2)}: integer(${dbColumnName({ name, casing: casing2 })})`;
  81638. out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault(defaultValue)})` : "";
  81639. return out;
  81640. }
  81641. if (lowered === "real") {
  81642. let out = `${withCasing(name, casing2)}: real(${dbColumnName({ name, casing: casing2 })})`;
  81643. out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
  81644. return out;
  81645. }
  81646. if (lowered.startsWith("text")) {
  81647. const match2 = lowered.match(/\d+/);
  81648. let out;
  81649. if (match2) {
  81650. out = `${withCasing(name, casing2)}: text(${dbColumnName({ name, casing: casing2, withMode: true })}{ length: ${match2[0]} })`;
  81651. } else {
  81652. out = `${withCasing(name, casing2)}: text(${dbColumnName({ name, casing: casing2 })})`;
  81653. }
  81654. out += defaultValue ? `.default("${mapColumnDefault(defaultValue)}")` : "";
  81655. return out;
  81656. }
  81657. if (lowered === "blob") {
  81658. let out = `${withCasing(name, casing2)}: blob(${dbColumnName({ name, casing: casing2 })})`;
  81659. out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
  81660. return out;
  81661. }
  81662. if (lowered === "numeric") {
  81663. let out = `${withCasing(name, casing2)}: numeric(${dbColumnName({ name, casing: casing2 })})`;
  81664. out += defaultValue ? `.default(${mapColumnDefault(defaultValue)})` : "";
  81665. return out;
  81666. }
  81667. return `// Warning: Can't parse ${type} from database
  81668. // ${type}Type: ${type}("${name}")`;
  81669. };
  81670. createTableColumns = (columns, fks, casing2) => {
  81671. let statement = "";
  81672. const oneColumnsFKs = Object.values(fks).filter((it) => {
  81673. return !isSelf(it);
  81674. }).filter((it) => it.columnsFrom.length === 1);
  81675. const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
  81676. const arr = res[it.columnsFrom[0]] || [];
  81677. arr.push(it);
  81678. res[it.columnsFrom[0]] = arr;
  81679. return res;
  81680. }, {});
  81681. columns.forEach((it) => {
  81682. statement += " ";
  81683. statement += column6(it.type, it.name, it.default, it.autoincrement, casing2);
  81684. statement += it.primaryKey ? `.primaryKey(${it.autoincrement ? "{ autoIncrement: true }" : ""})` : "";
  81685. statement += it.notNull ? ".notNull()" : "";
  81686. statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as.replace(/`/g, "\\`").slice(1, -1)}\`, { mode: "${it.generated.type}" })` : "";
  81687. const fks2 = fkByColumnName[it.name];
  81688. if (fks2) {
  81689. const fksStatement = fks2.map((it2) => {
  81690. const onDelete = it2.onDelete && it2.onDelete !== "no action" ? it2.onDelete : null;
  81691. const onUpdate = it2.onUpdate && it2.onUpdate !== "no action" ? it2.onUpdate : null;
  81692. const params = { onDelete, onUpdate };
  81693. const typeSuffix = isCyclic(it2) ? ": AnySQLiteColumn" : "";
  81694. const paramsStr = objToStatement2(params);
  81695. if (paramsStr) {
  81696. return `.references(()${typeSuffix} => ${withCasing(
  81697. it2.tableTo,
  81698. casing2
  81699. )}.${withCasing(it2.columnsTo[0], casing2)}, ${paramsStr} )`;
  81700. }
  81701. return `.references(()${typeSuffix} => ${withCasing(
  81702. it2.tableTo,
  81703. casing2
  81704. )}.${withCasing(it2.columnsTo[0], casing2)})`;
  81705. }).join("");
  81706. statement += fksStatement;
  81707. }
  81708. statement += ",\n";
  81709. });
  81710. return statement;
  81711. };
  81712. createTableIndexes = (tableName, idxs, casing2) => {
  81713. let statement = "";
  81714. idxs.forEach((it) => {
  81715. let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
  81716. idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
  81717. idxKey = withCasing(idxKey, casing2);
  81718. const indexGeneratedName = indexName4(tableName, it.columns);
  81719. const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
  81720. statement += `
  81721. `;
  81722. statement += it.isUnique ? "uniqueIndex(" : "index(";
  81723. statement += `${escapedIndexName})`;
  81724. statement += `.on(${it.columns.map((it2) => `table.${withCasing(it2, casing2)}`).join(", ")}),`;
  81725. });
  81726. return statement;
  81727. };
  81728. createTableUniques = (unqs, casing2) => {
  81729. let statement = "";
  81730. unqs.forEach((it) => {
  81731. const idxKey = withCasing(it.name, casing2);
  81732. statement += `
  81733. `;
  81734. statement += "unique(";
  81735. statement += `"${it.name}")`;
  81736. statement += `.on(${it.columns.map((it2) => `table.${withCasing(it2, casing2)}`).join(", ")}),`;
  81737. });
  81738. return statement;
  81739. };
  81740. createTableChecks = (checks, casing2) => {
  81741. let statement = "";
  81742. checks.forEach((it) => {
  81743. statement += `
  81744. `;
  81745. statement += "check(";
  81746. statement += `"${it.name}", `;
  81747. statement += `sql\`${it.value}\`)`;
  81748. statement += `,`;
  81749. });
  81750. return statement;
  81751. };
  81752. createTablePKs = (pks, casing2) => {
  81753. let statement = "";
  81754. pks.forEach((it, i4) => {
  81755. statement += `
  81756. `;
  81757. statement += "primaryKey({ columns: [";
  81758. statement += `${it.columns.map((c3) => {
  81759. return `table.${withCasing(c3, casing2)}`;
  81760. }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
  81761. statement += ")";
  81762. });
  81763. return statement;
  81764. };
  81765. createTableFKs = (fks, casing2) => {
  81766. let statement = "";
  81767. fks.forEach((it) => {
  81768. const isSelf5 = it.tableTo === it.tableFrom;
  81769. const tableTo = isSelf5 ? "table" : `${withCasing(it.tableTo, casing2)}`;
  81770. statement += `
  81771. `;
  81772. statement += `foreignKey(() => ({
  81773. `;
  81774. statement += ` columns: [${it.columnsFrom.map((i4) => `table.${withCasing(i4, casing2)}`).join(", ")}],
  81775. `;
  81776. statement += ` foreignColumns: [${it.columnsTo.map((i4) => `${tableTo}.${withCasing(i4, casing2)}`).join(", ")}],
  81777. `;
  81778. statement += ` name: "${it.name}"
  81779. `;
  81780. statement += ` }))`;
  81781. statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
  81782. statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
  81783. statement += `,`;
  81784. });
  81785. return statement;
  81786. };
  81787. }
  81788. });
  81789. // src/cli/commands/sqliteIntrospect.ts
  81790. var sqliteIntrospect_exports = {};
  81791. __export(sqliteIntrospect_exports, {
  81792. sqliteIntrospect: () => sqliteIntrospect,
  81793. sqlitePushIntrospect: () => sqlitePushIntrospect
  81794. });
  81795. var import_hanji12, sqliteIntrospect, sqlitePushIntrospect;
  81796. var init_sqliteIntrospect = __esm({
  81797. "src/cli/commands/sqliteIntrospect.ts"() {
  81798. "use strict";
  81799. import_hanji12 = __toESM(require_hanji());
  81800. init_mjs();
  81801. init_global();
  81802. init_introspect_sqlite();
  81803. init_sqliteSerializer();
  81804. init_views();
  81805. sqliteIntrospect = async (credentials2, filters, casing2) => {
  81806. const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  81807. const db = await connectToSQLite2(credentials2);
  81808. const matchers = filters.map((it) => {
  81809. return new Minimatch(it);
  81810. });
  81811. const filter2 = (tableName) => {
  81812. if (matchers.length === 0) return true;
  81813. let flags = [];
  81814. for (let matcher of matchers) {
  81815. if (matcher.negate) {
  81816. if (!matcher.match(tableName)) {
  81817. flags.push(false);
  81818. }
  81819. }
  81820. if (matcher.match(tableName)) {
  81821. flags.push(true);
  81822. }
  81823. }
  81824. if (flags.length > 0) {
  81825. return flags.every(Boolean);
  81826. }
  81827. return false;
  81828. };
  81829. const progress = new IntrospectProgress();
  81830. const res = await (0, import_hanji12.renderWithTask)(
  81831. progress,
  81832. fromDatabase3(db, filter2, (stage, count, status) => {
  81833. progress.update(stage, count, status);
  81834. })
  81835. );
  81836. const schema6 = { id: originUUID, prevId: "", ...res };
  81837. const ts = schemaToTypeScript(schema6, casing2);
  81838. return { schema: schema6, ts };
  81839. };
  81840. sqlitePushIntrospect = async (db, filters) => {
  81841. const matchers = filters.map((it) => {
  81842. return new Minimatch(it);
  81843. });
  81844. const filter2 = (tableName) => {
  81845. if (matchers.length === 0) return true;
  81846. let flags = [];
  81847. for (let matcher of matchers) {
  81848. if (matcher.negate) {
  81849. if (!matcher.match(tableName)) {
  81850. flags.push(false);
  81851. }
  81852. }
  81853. if (matcher.match(tableName)) {
  81854. flags.push(true);
  81855. }
  81856. }
  81857. if (flags.length > 0) {
  81858. return flags.every(Boolean);
  81859. }
  81860. return false;
  81861. };
  81862. const progress = new ProgressView(
  81863. "Pulling schema from database...",
  81864. "Pulling schema from database..."
  81865. );
  81866. const res = await (0, import_hanji12.renderWithTask)(progress, fromDatabase3(db, filter2));
  81867. const schema6 = { id: originUUID, prevId: "", ...res };
  81868. return { schema: schema6 };
  81869. };
  81870. }
  81871. });
  81872. // src/cli/commands/push.ts
  81873. var push_exports = {};
  81874. __export(push_exports, {
  81875. libSQLPush: () => libSQLPush,
  81876. mysqlPush: () => mysqlPush,
  81877. pgPush: () => pgPush,
  81878. singlestorePush: () => singlestorePush,
  81879. sqlitePush: () => sqlitePush
  81880. });
  81881. var import_crypto6, import_hanji13, mysqlPush, singlestorePush, pgPush, sqlitePush, libSQLPush;
  81882. var init_push = __esm({
  81883. "src/cli/commands/push.ts"() {
  81884. "use strict";
  81885. init_source();
  81886. import_crypto6 = require("crypto");
  81887. import_hanji13 = __toESM(require_hanji());
  81888. init_serializer();
  81889. init_sqlgenerator();
  81890. init_selector_ui();
  81891. init_outputs();
  81892. init_libSqlPushUtils();
  81893. init_mysqlPushUtils();
  81894. init_pgPushUtils();
  81895. init_singlestorePushUtils();
  81896. init_sqlitePushUtils();
  81897. mysqlPush = async (schemaPath, credentials2, tablesFilter, strict, verbose, force, casing2) => {
  81898. const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  81899. const { mysqlPushIntrospect: mysqlPushIntrospect2 } = await Promise.resolve().then(() => (init_mysqlIntrospect(), mysqlIntrospect_exports));
  81900. const { db, database } = await connectToMySQL2(credentials2);
  81901. const { schema: schema6 } = await mysqlPushIntrospect2(db, database, tablesFilter);
  81902. const { prepareMySQLPush: prepareMySQLPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
  81903. const statements = await prepareMySQLPush2(schemaPath, schema6, casing2);
  81904. const filteredStatements = filterStatements(
  81905. statements.statements ?? [],
  81906. statements.validatedCur,
  81907. statements.validatedPrev
  81908. );
  81909. try {
  81910. if (filteredStatements.length === 0) {
  81911. (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
  81912. } else {
  81913. const {
  81914. shouldAskForApprove,
  81915. statementsToExecute,
  81916. columnsToRemove,
  81917. tablesToRemove,
  81918. tablesToTruncate,
  81919. infoToPrint
  81920. } = await logSuggestionsAndReturn2(
  81921. db,
  81922. filteredStatements,
  81923. statements.validatedCur
  81924. );
  81925. const filteredSqlStatements = fromJson(filteredStatements, "mysql");
  81926. const uniqueSqlStatementsToExecute = [];
  81927. statementsToExecute.forEach((ss) => {
  81928. if (!uniqueSqlStatementsToExecute.includes(ss)) {
  81929. uniqueSqlStatementsToExecute.push(ss);
  81930. }
  81931. });
  81932. const uniqueFilteredSqlStatements = [];
  81933. filteredSqlStatements.forEach((ss) => {
  81934. if (!uniqueFilteredSqlStatements.includes(ss)) {
  81935. uniqueFilteredSqlStatements.push(ss);
  81936. }
  81937. });
  81938. if (verbose) {
  81939. console.log();
  81940. console.log(
  81941. withStyle.warning("You are about to execute current statements:")
  81942. );
  81943. console.log();
  81944. console.log(
  81945. [...uniqueSqlStatementsToExecute, ...uniqueFilteredSqlStatements].map((s4) => source_default.blue(s4)).join("\n")
  81946. );
  81947. console.log();
  81948. }
  81949. if (!force && strict) {
  81950. if (!shouldAskForApprove) {
  81951. const { status, data } = await (0, import_hanji13.render)(
  81952. new Select(["No, abort", `Yes, I want to execute all statements`])
  81953. );
  81954. if ((data == null ? void 0 : data.index) === 0) {
  81955. (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
  81956. process.exit(0);
  81957. }
  81958. }
  81959. }
  81960. if (!force && shouldAskForApprove) {
  81961. console.log(withStyle.warning("Found data-loss statements:"));
  81962. console.log(infoToPrint.join("\n"));
  81963. console.log();
  81964. console.log(
  81965. source_default.red.bold(
  81966. "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
  81967. )
  81968. );
  81969. console.log(source_default.white("Do you still want to push changes?"));
  81970. const { status, data } = await (0, import_hanji13.render)(
  81971. new Select([
  81972. "No, abort",
  81973. `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
  81974. ])
  81975. );
  81976. if ((data == null ? void 0 : data.index) === 0) {
  81977. (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
  81978. process.exit(0);
  81979. }
  81980. }
  81981. for (const dStmnt of uniqueSqlStatementsToExecute) {
  81982. await db.query(dStmnt);
  81983. }
  81984. for (const statement of uniqueFilteredSqlStatements) {
  81985. await db.query(statement);
  81986. }
  81987. if (filteredStatements.length > 0) {
  81988. (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
  81989. } else {
  81990. (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
  81991. }
  81992. }
  81993. } catch (e4) {
  81994. console.log(e4);
  81995. }
  81996. };
  81997. singlestorePush = async (schemaPath, credentials2, tablesFilter, strict, verbose, force, casing2) => {
  81998. const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  81999. const { singlestorePushIntrospect: singlestorePushIntrospect2 } = await Promise.resolve().then(() => (init_singlestoreIntrospect(), singlestoreIntrospect_exports));
  82000. const { db, database } = await connectToSingleStore2(credentials2);
  82001. const { schema: schema6 } = await singlestorePushIntrospect2(
  82002. db,
  82003. database,
  82004. tablesFilter
  82005. );
  82006. const { prepareSingleStorePush: prepareSingleStorePush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
  82007. const statements = await prepareSingleStorePush2(schemaPath, schema6, casing2);
  82008. const filteredStatements = filterStatements2(
  82009. statements.statements ?? [],
  82010. statements.validatedCur,
  82011. statements.validatedPrev
  82012. );
  82013. try {
  82014. if (filteredStatements.length === 0) {
  82015. (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
  82016. } else {
  82017. const {
  82018. shouldAskForApprove,
  82019. statementsToExecute,
  82020. columnsToRemove,
  82021. tablesToRemove,
  82022. tablesToTruncate,
  82023. infoToPrint,
  82024. schemasToRemove
  82025. } = await logSuggestionsAndReturn3(
  82026. db,
  82027. filteredStatements,
  82028. statements.validatedCur,
  82029. statements.validatedPrev
  82030. );
  82031. if (verbose) {
  82032. console.log();
  82033. console.log(
  82034. withStyle.warning("You are about to execute current statements:")
  82035. );
  82036. console.log();
  82037. console.log(statementsToExecute.map((s4) => source_default.blue(s4)).join("\n"));
  82038. console.log();
  82039. }
  82040. if (!force && strict) {
  82041. if (!shouldAskForApprove) {
  82042. const { status, data } = await (0, import_hanji13.render)(
  82043. new Select(["No, abort", `Yes, I want to execute all statements`])
  82044. );
  82045. if ((data == null ? void 0 : data.index) === 0) {
  82046. (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
  82047. process.exit(0);
  82048. }
  82049. }
  82050. }
  82051. if (!force && shouldAskForApprove) {
  82052. console.log(withStyle.warning("Found data-loss statements:"));
  82053. console.log(infoToPrint.join("\n"));
  82054. console.log();
  82055. console.log(
  82056. source_default.red.bold(
  82057. "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
  82058. )
  82059. );
  82060. console.log(source_default.white("Do you still want to push changes?"));
  82061. const { status, data } = await (0, import_hanji13.render)(
  82062. new Select([
  82063. "No, abort",
  82064. `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
  82065. ])
  82066. );
  82067. if ((data == null ? void 0 : data.index) === 0) {
  82068. (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
  82069. process.exit(0);
  82070. }
  82071. }
  82072. for (const dStmnt of statementsToExecute) {
  82073. await db.query(dStmnt);
  82074. }
  82075. if (filteredStatements.length > 0) {
  82076. (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
  82077. } else {
  82078. (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
  82079. }
  82080. }
  82081. } catch (e4) {
  82082. console.log(e4);
  82083. }
  82084. };
  82085. pgPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, schemasFilter, entities, force, casing2) => {
  82086. const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  82087. const { pgPushIntrospect: pgPushIntrospect2 } = await Promise.resolve().then(() => (init_pgIntrospect(), pgIntrospect_exports));
  82088. const db = await preparePostgresDB2(credentials2);
  82089. const serialized = await serializePg(schemaPath, casing2, schemasFilter);
  82090. const { schema: schema6 } = await pgPushIntrospect2(db, tablesFilter, schemasFilter, entities, serialized);
  82091. const { preparePgPush: preparePgPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
  82092. const statements = await preparePgPush2(
  82093. { id: (0, import_crypto6.randomUUID)(), prevId: schema6.id, ...serialized },
  82094. schema6
  82095. );
  82096. try {
  82097. if (statements.sqlStatements.length === 0) {
  82098. (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
  82099. } else {
  82100. const {
  82101. shouldAskForApprove,
  82102. statementsToExecute,
  82103. columnsToRemove,
  82104. tablesToRemove,
  82105. matViewsToRemove,
  82106. tablesToTruncate,
  82107. infoToPrint,
  82108. schemasToRemove
  82109. } = await pgSuggestions(db, statements.statements);
  82110. if (verbose) {
  82111. console.log();
  82112. console.log(
  82113. withStyle.warning("You are about to execute current statements:")
  82114. );
  82115. console.log();
  82116. console.log(statementsToExecute.map((s4) => source_default.blue(s4)).join("\n"));
  82117. console.log();
  82118. }
  82119. if (!force && strict) {
  82120. if (!shouldAskForApprove) {
  82121. const { status, data } = await (0, import_hanji13.render)(
  82122. new Select(["No, abort", `Yes, I want to execute all statements`])
  82123. );
  82124. if ((data == null ? void 0 : data.index) === 0) {
  82125. (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
  82126. process.exit(0);
  82127. }
  82128. }
  82129. }
  82130. if (!force && shouldAskForApprove) {
  82131. console.log(withStyle.warning("Found data-loss statements:"));
  82132. console.log(infoToPrint.join("\n"));
  82133. console.log();
  82134. console.log(
  82135. source_default.red.bold(
  82136. "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
  82137. )
  82138. );
  82139. console.log(source_default.white("Do you still want to push changes?"));
  82140. const { status, data } = await (0, import_hanji13.render)(
  82141. new Select([
  82142. "No, abort",
  82143. `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}${matViewsToRemove.length > 0 ? ` remove ${matViewsToRemove.length} ${matViewsToRemove.length > 1 ? "materialized views" : "materialize view"},` : " "}`.replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
  82144. ])
  82145. );
  82146. if ((data == null ? void 0 : data.index) === 0) {
  82147. (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
  82148. process.exit(0);
  82149. }
  82150. }
  82151. for (const dStmnt of statementsToExecute) {
  82152. await db.query(dStmnt);
  82153. }
  82154. if (statements.statements.length > 0) {
  82155. (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
  82156. } else {
  82157. (0, import_hanji13.render)(`[${source_default.blue("i")}] No changes detected`);
  82158. }
  82159. }
  82160. } catch (e4) {
  82161. console.error(e4);
  82162. }
  82163. };
  82164. sqlitePush = async (schemaPath, verbose, strict, credentials2, tablesFilter, force, casing2) => {
  82165. const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  82166. const { sqlitePushIntrospect: sqlitePushIntrospect2 } = await Promise.resolve().then(() => (init_sqliteIntrospect(), sqliteIntrospect_exports));
  82167. const db = await connectToSQLite2(credentials2);
  82168. const { schema: schema6 } = await sqlitePushIntrospect2(db, tablesFilter);
  82169. const { prepareSQLitePush: prepareSQLitePush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
  82170. const statements = await prepareSQLitePush2(schemaPath, schema6, casing2);
  82171. if (statements.sqlStatements.length === 0) {
  82172. (0, import_hanji13.render)(`
  82173. [${source_default.blue("i")}] No changes detected`);
  82174. } else {
  82175. const {
  82176. shouldAskForApprove,
  82177. statementsToExecute,
  82178. columnsToRemove,
  82179. tablesToRemove,
  82180. tablesToTruncate,
  82181. infoToPrint,
  82182. schemasToRemove
  82183. } = await logSuggestionsAndReturn(
  82184. db,
  82185. statements.statements,
  82186. statements.squashedPrev,
  82187. statements.squashedCur,
  82188. statements.meta
  82189. );
  82190. if (verbose && statementsToExecute.length > 0) {
  82191. console.log();
  82192. console.log(
  82193. withStyle.warning("You are about to execute current statements:")
  82194. );
  82195. console.log();
  82196. console.log(statementsToExecute.map((s4) => source_default.blue(s4)).join("\n"));
  82197. console.log();
  82198. }
  82199. if (!force && strict) {
  82200. if (!shouldAskForApprove) {
  82201. const { status, data } = await (0, import_hanji13.render)(
  82202. new Select(["No, abort", `Yes, I want to execute all statements`])
  82203. );
  82204. if ((data == null ? void 0 : data.index) === 0) {
  82205. (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
  82206. process.exit(0);
  82207. }
  82208. }
  82209. }
  82210. if (!force && shouldAskForApprove) {
  82211. console.log(withStyle.warning("Found data-loss statements:"));
  82212. console.log(infoToPrint.join("\n"));
  82213. console.log();
  82214. console.log(
  82215. source_default.red.bold(
  82216. "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
  82217. )
  82218. );
  82219. console.log(source_default.white("Do you still want to push changes?"));
  82220. const { status, data } = await (0, import_hanji13.render)(
  82221. new Select([
  82222. "No, abort",
  82223. `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.trimEnd().replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
  82224. ])
  82225. );
  82226. if ((data == null ? void 0 : data.index) === 0) {
  82227. (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
  82228. process.exit(0);
  82229. }
  82230. }
  82231. if (statementsToExecute.length === 0) {
  82232. (0, import_hanji13.render)(`
  82233. [${source_default.blue("i")}] No changes detected`);
  82234. } else {
  82235. const isNotD1 = !("driver" in credentials2 && credentials2.driver === "d1-http");
  82236. isNotD1 ?? await db.run("begin");
  82237. try {
  82238. for (const dStmnt of statementsToExecute) {
  82239. await db.run(dStmnt);
  82240. }
  82241. isNotD1 ?? await db.run("commit");
  82242. } catch (e4) {
  82243. console.error(e4);
  82244. isNotD1 ?? await db.run("rollback");
  82245. process.exit(1);
  82246. }
  82247. (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
  82248. }
  82249. }
  82250. };
  82251. libSQLPush = async (schemaPath, verbose, strict, credentials2, tablesFilter, force, casing2) => {
  82252. const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  82253. const { sqlitePushIntrospect: sqlitePushIntrospect2 } = await Promise.resolve().then(() => (init_sqliteIntrospect(), sqliteIntrospect_exports));
  82254. const db = await connectToLibSQL2(credentials2);
  82255. const { schema: schema6 } = await sqlitePushIntrospect2(db, tablesFilter);
  82256. const { prepareLibSQLPush: prepareLibSQLPush2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
  82257. const statements = await prepareLibSQLPush2(schemaPath, schema6, casing2);
  82258. if (statements.sqlStatements.length === 0) {
  82259. (0, import_hanji13.render)(`
  82260. [${source_default.blue("i")}] No changes detected`);
  82261. } else {
  82262. const {
  82263. shouldAskForApprove,
  82264. statementsToExecute,
  82265. columnsToRemove,
  82266. tablesToRemove,
  82267. tablesToTruncate,
  82268. infoToPrint
  82269. } = await libSqlLogSuggestionsAndReturn(
  82270. db,
  82271. statements.statements,
  82272. statements.squashedPrev,
  82273. statements.squashedCur,
  82274. statements.meta
  82275. );
  82276. if (verbose && statementsToExecute.length > 0) {
  82277. console.log();
  82278. console.log(
  82279. withStyle.warning("You are about to execute current statements:")
  82280. );
  82281. console.log();
  82282. console.log(statementsToExecute.map((s4) => source_default.blue(s4)).join("\n"));
  82283. console.log();
  82284. }
  82285. if (!force && strict) {
  82286. if (!shouldAskForApprove) {
  82287. const { status, data } = await (0, import_hanji13.render)(
  82288. new Select(["No, abort", `Yes, I want to execute all statements`])
  82289. );
  82290. if ((data == null ? void 0 : data.index) === 0) {
  82291. (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
  82292. process.exit(0);
  82293. }
  82294. }
  82295. }
  82296. if (!force && shouldAskForApprove) {
  82297. console.log(withStyle.warning("Found data-loss statements:"));
  82298. console.log(infoToPrint.join("\n"));
  82299. console.log();
  82300. console.log(
  82301. source_default.red.bold(
  82302. "THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED\n"
  82303. )
  82304. );
  82305. console.log(source_default.white("Do you still want to push changes?"));
  82306. const { status, data } = await (0, import_hanji13.render)(
  82307. new Select([
  82308. "No, abort",
  82309. `Yes, I want to${tablesToRemove.length > 0 ? ` remove ${tablesToRemove.length} ${tablesToRemove.length > 1 ? "tables" : "table"},` : " "}${columnsToRemove.length > 0 ? ` remove ${columnsToRemove.length} ${columnsToRemove.length > 1 ? "columns" : "column"},` : " "}${tablesToTruncate.length > 0 ? ` truncate ${tablesToTruncate.length} ${tablesToTruncate.length > 1 ? "tables" : "table"}` : ""}`.trimEnd().replace(/(^,)|(,$)/g, "").replace(/ +(?= )/g, "")
  82310. ])
  82311. );
  82312. if ((data == null ? void 0 : data.index) === 0) {
  82313. (0, import_hanji13.render)(`[${source_default.red("x")}] All changes were aborted`);
  82314. process.exit(0);
  82315. }
  82316. }
  82317. if (statementsToExecute.length === 0) {
  82318. (0, import_hanji13.render)(`
  82319. [${source_default.blue("i")}] No changes detected`);
  82320. } else {
  82321. await db.batchWithPragma(statementsToExecute);
  82322. (0, import_hanji13.render)(`[${source_default.green("\u2713")}] Changes applied`);
  82323. }
  82324. }
  82325. };
  82326. }
  82327. });
  82328. // ../node_modules/.pnpm/pluralize@8.0.0/node_modules/pluralize/pluralize.js
  82329. var require_pluralize = __commonJS({
  82330. "../node_modules/.pnpm/pluralize@8.0.0/node_modules/pluralize/pluralize.js"(exports2, module2) {
  82331. (function(root, pluralize) {
  82332. if (typeof require === "function" && typeof exports2 === "object" && typeof module2 === "object") {
  82333. module2.exports = pluralize();
  82334. } else if (typeof define === "function" && define.amd) {
  82335. define(function() {
  82336. return pluralize();
  82337. });
  82338. } else {
  82339. root.pluralize = pluralize();
  82340. }
  82341. })(exports2, function() {
  82342. var pluralRules = [];
  82343. var singularRules = [];
  82344. var uncountables = {};
  82345. var irregularPlurals = {};
  82346. var irregularSingles = {};
  82347. function sanitizeRule(rule) {
  82348. if (typeof rule === "string") {
  82349. return new RegExp("^" + rule + "$", "i");
  82350. }
  82351. return rule;
  82352. }
  82353. function restoreCase(word, token) {
  82354. if (word === token) return token;
  82355. if (word === word.toLowerCase()) return token.toLowerCase();
  82356. if (word === word.toUpperCase()) return token.toUpperCase();
  82357. if (word[0] === word[0].toUpperCase()) {
  82358. return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase();
  82359. }
  82360. return token.toLowerCase();
  82361. }
  82362. function interpolate(str, args) {
  82363. return str.replace(/\$(\d{1,2})/g, function(match2, index6) {
  82364. return args[index6] || "";
  82365. });
  82366. }
  82367. function replace(word, rule) {
  82368. return word.replace(rule[0], function(match2, index6) {
  82369. var result = interpolate(rule[1], arguments);
  82370. if (match2 === "") {
  82371. return restoreCase(word[index6 - 1], result);
  82372. }
  82373. return restoreCase(match2, result);
  82374. });
  82375. }
  82376. function sanitizeWord(token, word, rules) {
  82377. if (!token.length || uncountables.hasOwnProperty(token)) {
  82378. return word;
  82379. }
  82380. var len = rules.length;
  82381. while (len--) {
  82382. var rule = rules[len];
  82383. if (rule[0].test(word)) return replace(word, rule);
  82384. }
  82385. return word;
  82386. }
  82387. function replaceWord(replaceMap, keepMap, rules) {
  82388. return function(word) {
  82389. var token = word.toLowerCase();
  82390. if (keepMap.hasOwnProperty(token)) {
  82391. return restoreCase(word, token);
  82392. }
  82393. if (replaceMap.hasOwnProperty(token)) {
  82394. return restoreCase(word, replaceMap[token]);
  82395. }
  82396. return sanitizeWord(token, word, rules);
  82397. };
  82398. }
  82399. function checkWord(replaceMap, keepMap, rules, bool) {
  82400. return function(word) {
  82401. var token = word.toLowerCase();
  82402. if (keepMap.hasOwnProperty(token)) return true;
  82403. if (replaceMap.hasOwnProperty(token)) return false;
  82404. return sanitizeWord(token, token, rules) === token;
  82405. };
  82406. }
  82407. function pluralize(word, count, inclusive) {
  82408. var pluralized = count === 1 ? pluralize.singular(word) : pluralize.plural(word);
  82409. return (inclusive ? count + " " : "") + pluralized;
  82410. }
  82411. pluralize.plural = replaceWord(
  82412. irregularSingles,
  82413. irregularPlurals,
  82414. pluralRules
  82415. );
  82416. pluralize.isPlural = checkWord(
  82417. irregularSingles,
  82418. irregularPlurals,
  82419. pluralRules
  82420. );
  82421. pluralize.singular = replaceWord(
  82422. irregularPlurals,
  82423. irregularSingles,
  82424. singularRules
  82425. );
  82426. pluralize.isSingular = checkWord(
  82427. irregularPlurals,
  82428. irregularSingles,
  82429. singularRules
  82430. );
  82431. pluralize.addPluralRule = function(rule, replacement) {
  82432. pluralRules.push([sanitizeRule(rule), replacement]);
  82433. };
  82434. pluralize.addSingularRule = function(rule, replacement) {
  82435. singularRules.push([sanitizeRule(rule), replacement]);
  82436. };
  82437. pluralize.addUncountableRule = function(word) {
  82438. if (typeof word === "string") {
  82439. uncountables[word.toLowerCase()] = true;
  82440. return;
  82441. }
  82442. pluralize.addPluralRule(word, "$0");
  82443. pluralize.addSingularRule(word, "$0");
  82444. };
  82445. pluralize.addIrregularRule = function(single, plural2) {
  82446. plural2 = plural2.toLowerCase();
  82447. single = single.toLowerCase();
  82448. irregularSingles[single] = plural2;
  82449. irregularPlurals[plural2] = single;
  82450. };
  82451. [
  82452. // Pronouns.
  82453. ["I", "we"],
  82454. ["me", "us"],
  82455. ["he", "they"],
  82456. ["she", "they"],
  82457. ["them", "them"],
  82458. ["myself", "ourselves"],
  82459. ["yourself", "yourselves"],
  82460. ["itself", "themselves"],
  82461. ["herself", "themselves"],
  82462. ["himself", "themselves"],
  82463. ["themself", "themselves"],
  82464. ["is", "are"],
  82465. ["was", "were"],
  82466. ["has", "have"],
  82467. ["this", "these"],
  82468. ["that", "those"],
  82469. // Words ending in with a consonant and `o`.
  82470. ["echo", "echoes"],
  82471. ["dingo", "dingoes"],
  82472. ["volcano", "volcanoes"],
  82473. ["tornado", "tornadoes"],
  82474. ["torpedo", "torpedoes"],
  82475. // Ends with `us`.
  82476. ["genus", "genera"],
  82477. ["viscus", "viscera"],
  82478. // Ends with `ma`.
  82479. ["stigma", "stigmata"],
  82480. ["stoma", "stomata"],
  82481. ["dogma", "dogmata"],
  82482. ["lemma", "lemmata"],
  82483. ["schema", "schemata"],
  82484. ["anathema", "anathemata"],
  82485. // Other irregular rules.
  82486. ["ox", "oxen"],
  82487. ["axe", "axes"],
  82488. ["die", "dice"],
  82489. ["yes", "yeses"],
  82490. ["foot", "feet"],
  82491. ["eave", "eaves"],
  82492. ["goose", "geese"],
  82493. ["tooth", "teeth"],
  82494. ["quiz", "quizzes"],
  82495. ["human", "humans"],
  82496. ["proof", "proofs"],
  82497. ["carve", "carves"],
  82498. ["valve", "valves"],
  82499. ["looey", "looies"],
  82500. ["thief", "thieves"],
  82501. ["groove", "grooves"],
  82502. ["pickaxe", "pickaxes"],
  82503. ["passerby", "passersby"]
  82504. ].forEach(function(rule) {
  82505. return pluralize.addIrregularRule(rule[0], rule[1]);
  82506. });
  82507. [
  82508. [/s?$/i, "s"],
  82509. [/[^\u0000-\u007F]$/i, "$0"],
  82510. [/([^aeiou]ese)$/i, "$1"],
  82511. [/(ax|test)is$/i, "$1es"],
  82512. [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, "$1es"],
  82513. [/(e[mn]u)s?$/i, "$1s"],
  82514. [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, "$1"],
  82515. [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, "$1i"],
  82516. [/(alumn|alg|vertebr)(?:a|ae)$/i, "$1ae"],
  82517. [/(seraph|cherub)(?:im)?$/i, "$1im"],
  82518. [/(her|at|gr)o$/i, "$1oes"],
  82519. [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, "$1a"],
  82520. [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, "$1a"],
  82521. [/sis$/i, "ses"],
  82522. [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, "$1$2ves"],
  82523. [/([^aeiouy]|qu)y$/i, "$1ies"],
  82524. [/([^ch][ieo][ln])ey$/i, "$1ies"],
  82525. [/(x|ch|ss|sh|zz)$/i, "$1es"],
  82526. [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, "$1ices"],
  82527. [/\b((?:tit)?m|l)(?:ice|ouse)$/i, "$1ice"],
  82528. [/(pe)(?:rson|ople)$/i, "$1ople"],
  82529. [/(child)(?:ren)?$/i, "$1ren"],
  82530. [/eaux$/i, "$0"],
  82531. [/m[ae]n$/i, "men"],
  82532. ["thou", "you"]
  82533. ].forEach(function(rule) {
  82534. return pluralize.addPluralRule(rule[0], rule[1]);
  82535. });
  82536. [
  82537. [/s$/i, ""],
  82538. [/(ss)$/i, "$1"],
  82539. [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, "$1fe"],
  82540. [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, "$1f"],
  82541. [/ies$/i, "y"],
  82542. [/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, "$1ie"],
  82543. [/\b(mon|smil)ies$/i, "$1ey"],
  82544. [/\b((?:tit)?m|l)ice$/i, "$1ouse"],
  82545. [/(seraph|cherub)im$/i, "$1"],
  82546. [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, "$1"],
  82547. [/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, "$1sis"],
  82548. [/(movie|twelve|abuse|e[mn]u)s$/i, "$1"],
  82549. [/(test)(?:is|es)$/i, "$1is"],
  82550. [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, "$1us"],
  82551. [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, "$1um"],
  82552. [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, "$1on"],
  82553. [/(alumn|alg|vertebr)ae$/i, "$1a"],
  82554. [/(cod|mur|sil|vert|ind)ices$/i, "$1ex"],
  82555. [/(matr|append)ices$/i, "$1ix"],
  82556. [/(pe)(rson|ople)$/i, "$1rson"],
  82557. [/(child)ren$/i, "$1"],
  82558. [/(eau)x?$/i, "$1"],
  82559. [/men$/i, "man"]
  82560. ].forEach(function(rule) {
  82561. return pluralize.addSingularRule(rule[0], rule[1]);
  82562. });
  82563. [
  82564. // Singular words with no plurals.
  82565. "adulthood",
  82566. "advice",
  82567. "agenda",
  82568. "aid",
  82569. "aircraft",
  82570. "alcohol",
  82571. "ammo",
  82572. "analytics",
  82573. "anime",
  82574. "athletics",
  82575. "audio",
  82576. "bison",
  82577. "blood",
  82578. "bream",
  82579. "buffalo",
  82580. "butter",
  82581. "carp",
  82582. "cash",
  82583. "chassis",
  82584. "chess",
  82585. "clothing",
  82586. "cod",
  82587. "commerce",
  82588. "cooperation",
  82589. "corps",
  82590. "debris",
  82591. "diabetes",
  82592. "digestion",
  82593. "elk",
  82594. "energy",
  82595. "equipment",
  82596. "excretion",
  82597. "expertise",
  82598. "firmware",
  82599. "flounder",
  82600. "fun",
  82601. "gallows",
  82602. "garbage",
  82603. "graffiti",
  82604. "hardware",
  82605. "headquarters",
  82606. "health",
  82607. "herpes",
  82608. "highjinks",
  82609. "homework",
  82610. "housework",
  82611. "information",
  82612. "jeans",
  82613. "justice",
  82614. "kudos",
  82615. "labour",
  82616. "literature",
  82617. "machinery",
  82618. "mackerel",
  82619. "mail",
  82620. "media",
  82621. "mews",
  82622. "moose",
  82623. "music",
  82624. "mud",
  82625. "manga",
  82626. "news",
  82627. "only",
  82628. "personnel",
  82629. "pike",
  82630. "plankton",
  82631. "pliers",
  82632. "police",
  82633. "pollution",
  82634. "premises",
  82635. "rain",
  82636. "research",
  82637. "rice",
  82638. "salmon",
  82639. "scissors",
  82640. "series",
  82641. "sewage",
  82642. "shambles",
  82643. "shrimp",
  82644. "software",
  82645. "species",
  82646. "staff",
  82647. "swine",
  82648. "tennis",
  82649. "traffic",
  82650. "transportation",
  82651. "trout",
  82652. "tuna",
  82653. "wealth",
  82654. "welfare",
  82655. "whiting",
  82656. "wildebeest",
  82657. "wildlife",
  82658. "you",
  82659. /pok[eé]mon$/i,
  82660. // Regexes.
  82661. /[^aeiou]ese$/i,
  82662. // "chinese", "japanese"
  82663. /deer$/i,
  82664. // "deer", "reindeer"
  82665. /fish$/i,
  82666. // "fish", "blowfish", "angelfish"
  82667. /measles$/i,
  82668. /o[iu]s$/i,
  82669. // "carnivorous"
  82670. /pox$/i,
  82671. // "chickpox", "smallpox"
  82672. /sheep$/i
  82673. ].forEach(pluralize.addUncountableRule);
  82674. return pluralize;
  82675. });
  82676. }
  82677. });
  82678. // src/serializer/gelSerializer.ts
  82679. function stringFromDatabaseIdentityProperty2(field) {
  82680. return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
  82681. }
  82682. var import_drizzle_orm9, import_gel_core, indexName5, trimChar2, fromDatabase5, defaultForColumn2, getColumnsInfoQuery2;
  82683. var init_gelSerializer = __esm({
  82684. "src/serializer/gelSerializer.ts"() {
  82685. "use strict";
  82686. import_drizzle_orm9 = require("drizzle-orm");
  82687. import_gel_core = require("drizzle-orm/gel-core");
  82688. init_vector();
  82689. init_outputs();
  82690. init_utils2();
  82691. init_utils4();
  82692. indexName5 = (tableName, columns) => {
  82693. return `${tableName}_${columns.join("_")}_index`;
  82694. };
  82695. trimChar2 = (str, char) => {
  82696. let start = 0;
  82697. let end = str.length;
  82698. while (start < end && str[start] === char) ++start;
  82699. while (end > start && str[end - 1] === char) --end;
  82700. return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
  82701. };
  82702. fromDatabase5 = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback, tsSchema) => {
  82703. const result = {};
  82704. const policies = {};
  82705. const internals = { tables: {} };
  82706. const where = schemaFilters.map((t4) => `n.nspname = '${t4}'`).join(" or ");
  82707. const allTables = await db.query(
  82708. `SELECT
  82709. n.nspname::text AS table_schema,
  82710. c.relname::text AS table_name,
  82711. CASE
  82712. WHEN c.relkind = 'r' THEN 'table'
  82713. WHEN c.relkind = 'v' THEN 'view'
  82714. WHEN c.relkind = 'm' THEN 'materialized_view'
  82715. END AS type,
  82716. c.relrowsecurity AS rls_enabled
  82717. FROM
  82718. pg_catalog.pg_class c
  82719. JOIN
  82720. pg_catalog.pg_namespace n ON n.oid::text = c.relnamespace::text
  82721. WHERE
  82722. c.relkind IN ('r', 'v', 'm')
  82723. ${where === "" ? "" : ` AND ${where}`};`
  82724. );
  82725. const schemas = new Set(allTables.map((it) => it.table_schema));
  82726. const allSchemas = await db.query(`select s.nspname::text as table_schema
  82727. from pg_catalog.pg_namespace s
  82728. join pg_catalog.pg_user u on u.usesysid::text = s.nspowner::text
  82729. where nspname not in ('information_schema', 'pg_catalog', 'public')
  82730. and nspname::text not like 'pg_toast%'
  82731. and nspname::text not like 'pg_temp_%'
  82732. order by 1;`);
  82733. allSchemas.forEach((item) => {
  82734. if (schemaFilters.includes(item.table_schema)) {
  82735. schemas.add(item.table_schema);
  82736. }
  82737. });
  82738. let columnsCount = 0;
  82739. let indexesCount = 0;
  82740. let foreignKeysCount = 0;
  82741. let tableCount = 0;
  82742. const sequencesToReturn = {};
  82743. const all = allTables.filter((it) => it.type === "table").map((row) => {
  82744. return new Promise(async (res, rej) => {
  82745. var _a2, _b, _c, _d, _e, _f;
  82746. const tableName = row.table_name;
  82747. if (!tablesFilter(tableName)) return res("");
  82748. tableCount += 1;
  82749. const tableSchema = row.table_schema;
  82750. try {
  82751. const columnToReturn = {};
  82752. const indexToReturn = {};
  82753. const foreignKeysToReturn = {};
  82754. const primaryKeys = {};
  82755. const tableResponse = await getColumnsInfoQuery2({ schema: tableSchema, table: tableName, db });
  82756. columnsCount += tableResponse.length;
  82757. if (progressCallback) {
  82758. progressCallback("columns", columnsCount, "fetching");
  82759. }
  82760. const tableForeignKeys = await db.query(
  82761. `SELECT
  82762. con.contype::text AS constraint_type,
  82763. nsp.nspname::text AS constraint_schema,
  82764. con.conname::text AS constraint_name,
  82765. rel.relname::text AS table_name,
  82766. att.attname::text AS column_name,
  82767. fnsp.nspname::text AS foreign_table_schema,
  82768. frel.relname::text AS foreign_table_name,
  82769. fatt.attname::text AS foreign_column_name,
  82770. CASE con.confupdtype
  82771. WHEN 'a' THEN 'NO ACTION'
  82772. WHEN 'r' THEN 'RESTRICT'
  82773. WHEN 'n' THEN 'SET NULL'
  82774. WHEN 'c' THEN 'CASCADE'
  82775. WHEN 'd' THEN 'SET DEFAULT'
  82776. END AS update_rule,
  82777. CASE con.confdeltype
  82778. WHEN 'a' THEN 'NO ACTION'
  82779. WHEN 'r' THEN 'RESTRICT'
  82780. WHEN 'n' THEN 'SET NULL'
  82781. WHEN 'c' THEN 'CASCADE'
  82782. WHEN 'd' THEN 'SET DEFAULT'
  82783. END AS delete_rule
  82784. FROM
  82785. pg_catalog.pg_constraint con
  82786. JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
  82787. JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
  82788. LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
  82789. AND att.attrelid = con.conrelid
  82790. LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
  82791. LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
  82792. LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
  82793. AND fatt.attrelid = con.confrelid
  82794. WHERE
  82795. nsp.nspname = '${tableSchema}'
  82796. AND rel.relname = '${tableName}'
  82797. AND con.contype IN ('f');`
  82798. );
  82799. foreignKeysCount += tableForeignKeys.length;
  82800. if (progressCallback) {
  82801. progressCallback("fks", foreignKeysCount, "fetching");
  82802. }
  82803. for (const fk5 of tableForeignKeys) {
  82804. const columnFrom = fk5.column_name;
  82805. const tableTo = fk5.foreign_table_name;
  82806. const columnTo = fk5.foreign_column_name;
  82807. const schemaTo = fk5.foreign_table_schema;
  82808. const foreignKeyName = fk5.constraint_name;
  82809. const onUpdate = (_a2 = fk5.update_rule) == null ? void 0 : _a2.toLowerCase();
  82810. const onDelete = (_b = fk5.delete_rule) == null ? void 0 : _b.toLowerCase();
  82811. if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
  82812. foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
  82813. foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
  82814. } else {
  82815. foreignKeysToReturn[foreignKeyName] = {
  82816. name: foreignKeyName,
  82817. tableFrom: tableName,
  82818. tableTo,
  82819. schemaTo,
  82820. columnsFrom: [columnFrom],
  82821. columnsTo: [columnTo],
  82822. onDelete,
  82823. onUpdate
  82824. };
  82825. }
  82826. foreignKeysToReturn[foreignKeyName].columnsFrom = [
  82827. ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
  82828. ];
  82829. foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
  82830. }
  82831. for (const columnResponse of tableResponse) {
  82832. const columnName = columnResponse.column_name;
  82833. if (columnName === "__type__") continue;
  82834. const columnAdditionalDT = columnResponse.additional_dt;
  82835. const columnDimensions = columnResponse.array_dimensions;
  82836. const enumType2 = columnResponse.enum_name;
  82837. let columnType = columnResponse.data_type;
  82838. const defaultValueRes = columnResponse.column_default;
  82839. const isGenerated = columnResponse.is_generated === "ALWAYS";
  82840. const generationExpression = columnResponse.generation_expression;
  82841. const isIdentity = columnResponse.is_identity === "YES";
  82842. const identityGeneration = columnResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
  82843. const identityStart = columnResponse.identity_start;
  82844. const identityIncrement = columnResponse.identity_increment;
  82845. const identityMaximum = columnResponse.identity_maximum;
  82846. const identityMinimum = columnResponse.identity_minimum;
  82847. const identityCycle = columnResponse.identity_cycle === "YES";
  82848. const identityName = columnResponse.seq_name;
  82849. let columnTypeMapped = columnType;
  82850. if (columnAdditionalDT === "ARRAY") {
  82851. if (typeof internals.tables[tableName] === "undefined") {
  82852. internals.tables[tableName] = {
  82853. columns: {
  82854. [columnName]: {
  82855. isArray: true,
  82856. dimensions: columnDimensions,
  82857. rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
  82858. }
  82859. }
  82860. };
  82861. } else {
  82862. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  82863. internals.tables[tableName].columns[columnName] = {
  82864. isArray: true,
  82865. dimensions: columnDimensions,
  82866. rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
  82867. };
  82868. }
  82869. }
  82870. }
  82871. const defaultValue = defaultForColumn2(columnResponse, internals, tableName);
  82872. if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
  82873. if (typeof internals.tables[tableName] === "undefined") {
  82874. internals.tables[tableName] = {
  82875. columns: {
  82876. [columnName]: {
  82877. isDefaultAnExpression: true
  82878. }
  82879. }
  82880. };
  82881. } else {
  82882. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  82883. internals.tables[tableName].columns[columnName] = {
  82884. isDefaultAnExpression: true
  82885. };
  82886. } else {
  82887. internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
  82888. }
  82889. }
  82890. }
  82891. if (columnTypeMapped.startsWith("numeric(")) {
  82892. columnTypeMapped = columnTypeMapped.replace(",", ", ");
  82893. }
  82894. if (columnAdditionalDT === "ARRAY") {
  82895. for (let i4 = 1; i4 < Number(columnDimensions); i4++) {
  82896. columnTypeMapped += "[]";
  82897. }
  82898. }
  82899. if (columnTypeMapped.includes("tuple<") || columnTypeMapped.includes("range")) continue;
  82900. columnTypeMapped = trimChar2(columnTypeMapped, '"');
  82901. columnTypeMapped = columnTypeMapped.replace("pg_catalog.", "");
  82902. columnTypeMapped = columnTypeMapped.replace("float4[]", "real[]").replace("float8[]", "double precision[]").replace('"numeric"[]', "numeric[]").replace('"time"[]', "time without time zone[]").replace(
  82903. "int2[]",
  82904. "smallint[]"
  82905. ).replace(
  82906. "int4[]",
  82907. "integer[]"
  82908. ).replace(
  82909. "int8[]",
  82910. "bigint[]"
  82911. ).replace(
  82912. "bool[]",
  82913. "boolean[]"
  82914. );
  82915. columnToReturn[columnName] = {
  82916. name: columnName,
  82917. type: (
  82918. // filter vectors, but in future we should filter any extension that was installed by user
  82919. columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry"].includes(enumType2) ? enumType2 : columnTypeMapped
  82920. ),
  82921. typeSchema: void 0,
  82922. // typeSchema: enumsToReturn[`${typeSchema}.${enumType}`] !== undefined
  82923. // ? enumsToReturn[`${typeSchema}.${enumType}`].schema
  82924. // : undefined,
  82925. primaryKey: columnName === "id",
  82926. default: defaultValue,
  82927. notNull: columnResponse.is_nullable === "NO",
  82928. generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
  82929. identity: isIdentity ? {
  82930. type: identityGeneration,
  82931. name: identityName,
  82932. increment: stringFromDatabaseIdentityProperty2(identityIncrement),
  82933. minValue: stringFromDatabaseIdentityProperty2(identityMinimum),
  82934. maxValue: stringFromDatabaseIdentityProperty2(identityMaximum),
  82935. startWith: stringFromDatabaseIdentityProperty2(identityStart),
  82936. cache: ((_c = sequencesToReturn[identityName]) == null ? void 0 : _c.cache) ? (_d = sequencesToReturn[identityName]) == null ? void 0 : _d.cache : ((_e = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _e.cache) ? (_f = sequencesToReturn[`${tableSchema}.${identityName}`]) == null ? void 0 : _f.cache : void 0,
  82937. cycle: identityCycle,
  82938. schema: tableSchema
  82939. } : void 0
  82940. };
  82941. if (identityName && typeof identityName === "string") {
  82942. delete sequencesToReturn[`${tableSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
  82943. delete sequencesToReturn[identityName];
  82944. }
  82945. }
  82946. const dbIndexes = await db.query(
  82947. `SELECT DISTINCT ON (t.relname, ic.relname, k.i) t.relname::text as table_name, ic.relname::text AS indexname,
  82948. k.i AS index_order,
  82949. i.indisunique as is_unique,
  82950. am.amname::text as method,
  82951. ic.reloptions as with,
  82952. coalesce(a.attname,
  82953. (('{' || pg_get_expr(
  82954. i.indexprs,
  82955. i.indrelid
  82956. )
  82957. || '}')::text[]
  82958. )[k.i]
  82959. )::text AS column_name,
  82960. CASE
  82961. WHEN pg_get_expr(i.indexprs, i.indrelid) IS NOT NULL THEN 1
  82962. ELSE 0
  82963. END AS is_expression,
  82964. i.indoption[k.i-1] & 1 = 1 AS descending,
  82965. i.indoption[k.i-1] & 2 = 2 AS nulls_first,
  82966. pg_get_expr(
  82967. i.indpred,
  82968. i.indrelid
  82969. ) as where,
  82970. opc.opcname::text
  82971. FROM pg_class t
  82972. LEFT JOIN pg_index i ON t.oid = i.indrelid
  82973. LEFT JOIN pg_class ic ON ic.oid = i.indexrelid
  82974. CROSS JOIN LATERAL (SELECT unnest(i.indkey), generate_subscripts(i.indkey, 1) + 1) AS k(attnum, i)
  82975. LEFT JOIN pg_attribute AS a
  82976. ON i.indrelid = a.attrelid AND k.attnum = a.attnum
  82977. JOIN pg_namespace c on c.oid = t.relnamespace
  82978. LEFT JOIN pg_am AS am ON ic.relam = am.oid
  82979. JOIN pg_opclass opc ON opc.oid = ANY(i.indclass)
  82980. WHERE
  82981. c.nspname = '${tableSchema}' AND
  82982. t.relname = '${tableName}';`
  82983. );
  82984. const dbIndexFromConstraint = await db.query(
  82985. `SELECT
  82986. idx.indexrelname::text AS index_name,
  82987. idx.relname::text AS table_name,
  82988. schemaname::text,
  82989. CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
  82990. FROM
  82991. pg_stat_user_indexes idx
  82992. LEFT JOIN
  82993. pg_constraint con ON con.conindid = idx.indexrelid
  82994. WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
  82995. group by index_name, table_name,schemaname, generated_by_constraint;`
  82996. );
  82997. const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
  82998. (it) => it.index_name
  82999. );
  83000. for (const dbIndex of dbIndexes) {
  83001. const indexName6 = dbIndex.indexname;
  83002. const indexColumnName = dbIndex.column_name;
  83003. const indexIsUnique = dbIndex.is_unique;
  83004. const indexMethod = dbIndex.method;
  83005. const indexWith = dbIndex.with;
  83006. const indexWhere = dbIndex.where;
  83007. const opclass = dbIndex.opcname;
  83008. const isExpression = dbIndex.is_expression === 1;
  83009. const desc = dbIndex.descending;
  83010. const nullsFirst = dbIndex.nulls_first;
  83011. const mappedWith = {};
  83012. if (indexWith !== null) {
  83013. indexWith.forEach((it) => {
  83014. const splitted = it.split("=");
  83015. mappedWith[splitted[0]] = splitted[1];
  83016. });
  83017. }
  83018. if (idxsInConsteraint.includes(indexName6)) continue;
  83019. if (typeof indexToReturn[indexName6] !== "undefined") {
  83020. indexToReturn[indexName6].columns.push({
  83021. expression: indexColumnName,
  83022. asc: !desc,
  83023. nulls: nullsFirst ? "first" : "last",
  83024. opclass,
  83025. isExpression
  83026. });
  83027. } else {
  83028. indexToReturn[indexName6] = {
  83029. name: indexName6,
  83030. columns: [
  83031. {
  83032. expression: indexColumnName,
  83033. asc: !desc,
  83034. nulls: nullsFirst ? "first" : "last",
  83035. opclass,
  83036. isExpression
  83037. }
  83038. ],
  83039. isUnique: indexIsUnique,
  83040. // should not be a part of diff detects
  83041. concurrently: false,
  83042. method: indexMethod,
  83043. where: indexWhere === null ? void 0 : indexWhere,
  83044. with: mappedWith
  83045. };
  83046. }
  83047. }
  83048. indexesCount += Object.keys(indexToReturn).length;
  83049. if (progressCallback) {
  83050. progressCallback("indexes", indexesCount, "fetching");
  83051. }
  83052. result[`${tableSchema}.${tableName}`] = {
  83053. name: tableName,
  83054. schema: tableSchema !== "public" ? tableSchema : "",
  83055. columns: columnToReturn,
  83056. indexes: indexToReturn,
  83057. foreignKeys: foreignKeysToReturn,
  83058. compositePrimaryKeys: primaryKeys,
  83059. uniqueConstraints: {},
  83060. // uniqueConstrains,
  83061. checkConstraints: {},
  83062. // checkConstraints,
  83063. policies: {},
  83064. // policiesByTable[`${tableSchema}.${tableName}`] ?? {},
  83065. isRLSEnabled: row.rls_enabled
  83066. };
  83067. } catch (e4) {
  83068. rej(e4);
  83069. return;
  83070. }
  83071. res("");
  83072. });
  83073. });
  83074. if (progressCallback) {
  83075. progressCallback("tables", tableCount, "done");
  83076. }
  83077. for await (const _3 of all) {
  83078. }
  83079. if (progressCallback) {
  83080. progressCallback("columns", columnsCount, "done");
  83081. progressCallback("indexes", indexesCount, "done");
  83082. progressCallback("fks", foreignKeysCount, "done");
  83083. }
  83084. const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
  83085. return {
  83086. version: "1",
  83087. dialect: "gel",
  83088. tables: result,
  83089. enums: {},
  83090. schemas: schemasObject,
  83091. sequences: sequencesToReturn,
  83092. roles: {},
  83093. // rolesToReturn,
  83094. policies,
  83095. views: {},
  83096. // views,
  83097. _meta: {
  83098. schemas: {},
  83099. tables: {},
  83100. columns: {}
  83101. },
  83102. internal: internals
  83103. };
  83104. };
  83105. defaultForColumn2 = (column11, internals, tableName) => {
  83106. var _a2, _b;
  83107. const columnName = column11.column_name;
  83108. const isArray = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[columnName]) == null ? void 0 : _b.isArray) ?? false;
  83109. if (column11.column_default === null || column11.column_default === void 0) return void 0;
  83110. if (column11.column_default.endsWith("[]")) {
  83111. column11.column_default = column11.column_default.slice(0, -2);
  83112. }
  83113. column11.column_default = column11.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
  83114. const columnDefaultAsString = column11.column_default.toString();
  83115. if (isArray) {
  83116. return columnDefaultAsString;
  83117. }
  83118. if (["integer", "smallint", "bigint", "double precision", "real"].includes(column11.data_type)) {
  83119. if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString)) {
  83120. return Number(columnDefaultAsString);
  83121. } else {
  83122. if (typeof internals.tables[tableName] === "undefined") {
  83123. internals.tables[tableName] = {
  83124. columns: {
  83125. [columnName]: {
  83126. isDefaultAnExpression: true
  83127. }
  83128. }
  83129. };
  83130. } else {
  83131. if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
  83132. internals.tables[tableName].columns[columnName] = {
  83133. isDefaultAnExpression: true
  83134. };
  83135. } else {
  83136. internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
  83137. }
  83138. }
  83139. return columnDefaultAsString;
  83140. }
  83141. } else if (column11.data_type.includes("numeric")) {
  83142. return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
  83143. } else if (column11.data_type === "json" || column11.data_type === "jsonb") {
  83144. return `'${columnDefaultAsString}'`;
  83145. } else if (column11.data_type === "boolean") {
  83146. return column11.column_default === "true";
  83147. } else if (columnDefaultAsString === "NULL") {
  83148. return `NULL`;
  83149. } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) {
  83150. return columnDefaultAsString;
  83151. } else {
  83152. return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
  83153. }
  83154. };
  83155. getColumnsInfoQuery2 = ({ schema: schema6, table: table6, db }) => {
  83156. return db.query(
  83157. `SELECT
  83158. a.attrelid::regclass::text AS table_name, -- Table, view, or materialized view name
  83159. a.attname::text AS column_name, -- Column name
  83160. CASE
  83161. WHEN NOT a.attisdropped THEN
  83162. CASE
  83163. WHEN a.attnotnull THEN 'NO'
  83164. ELSE 'YES'
  83165. END
  83166. ELSE NULL
  83167. END AS is_nullable, -- NULL or NOT NULL constraint
  83168. a.attndims AS array_dimensions, -- Array dimensions
  83169. CASE
  83170. WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
  83171. AND EXISTS (
  83172. SELECT FROM pg_attrdef ad
  83173. WHERE ad.adrelid = a.attrelid
  83174. AND ad.adnum = a.attnum
  83175. AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval('''
  83176. || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
  83177. )
  83178. THEN CASE a.atttypid
  83179. WHEN 'int'::regtype THEN 'serial'
  83180. WHEN 'int8'::regtype THEN 'bigserial'
  83181. WHEN 'int2'::regtype THEN 'smallserial'
  83182. END
  83183. ELSE format_type(a.atttypid, a.atttypmod)
  83184. END AS data_type, -- Column data type
  83185. -- ns.nspname AS type_schema, -- Schema name
  83186. c.column_default::text, -- Column default value
  83187. c.data_type::text AS additional_dt, -- Data type from information_schema
  83188. c.udt_name::text AS enum_name, -- Enum type (if applicable)
  83189. c.is_generated::text, -- Is it a generated column?
  83190. c.generation_expression::text, -- Generation expression (if generated)
  83191. c.is_identity::text, -- Is it an identity column?
  83192. c.identity_generation::text, -- Identity generation strategy (ALWAYS or BY DEFAULT)
  83193. c.identity_start::text, -- Start value of identity column
  83194. c.identity_increment::text, -- Increment for identity column
  83195. c.identity_maximum::text, -- Maximum value for identity column
  83196. c.identity_minimum::text, -- Minimum value for identity column
  83197. c.identity_cycle::text, -- Does the identity column cycle?
  83198. ns.nspname::text AS type_schema -- Schema of the enum type
  83199. FROM
  83200. pg_attribute a
  83201. JOIN
  83202. pg_class cls ON cls.oid = a.attrelid -- Join pg_class to get table/view/materialized view info
  83203. JOIN
  83204. pg_namespace ns ON ns.oid = cls.relnamespace -- Join namespace to get schema info
  83205. LEFT JOIN
  83206. information_schema.columns c ON c.column_name = a.attname
  83207. AND c.table_schema = ns.nspname
  83208. AND c.table_name = cls.relname -- Match schema and table/view name
  83209. LEFT JOIN
  83210. pg_type enum_t ON enum_t.oid = a.atttypid -- Join to get the type info
  83211. LEFT JOIN
  83212. pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace -- Join to get the enum schema
  83213. WHERE
  83214. a.attnum > 0 -- Valid column numbers only
  83215. AND NOT a.attisdropped -- Skip dropped columns
  83216. AND cls.relkind IN ('r', 'v', 'm') -- Include regular tables ('r'), views ('v'), and materialized views ('m')
  83217. AND ns.nspname::text = '${schema6}' -- Filter by schema
  83218. AND cls.relname::text = '${table6}' -- Filter by table name
  83219. ORDER BY
  83220. a.attnum; -- Order by column number`
  83221. );
  83222. };
  83223. }
  83224. });
  83225. // src/introspect-gel.ts
  83226. function generateIdentityParams(identity) {
  83227. let paramsObj = `{ name: "${identity.name}"`;
  83228. if (identity == null ? void 0 : identity.startWith) {
  83229. paramsObj += `, startWith: ${identity.startWith}`;
  83230. }
  83231. if (identity == null ? void 0 : identity.increment) {
  83232. paramsObj += `, increment: ${identity.increment}`;
  83233. }
  83234. if (identity == null ? void 0 : identity.minValue) {
  83235. paramsObj += `, minValue: ${identity.minValue}`;
  83236. }
  83237. if (identity == null ? void 0 : identity.maxValue) {
  83238. paramsObj += `, maxValue: ${identity.maxValue}`;
  83239. }
  83240. if (identity == null ? void 0 : identity.cache) {
  83241. paramsObj += `, cache: ${identity.cache}`;
  83242. }
  83243. if (identity == null ? void 0 : identity.cycle) {
  83244. paramsObj += `, cycle: true`;
  83245. }
  83246. paramsObj += " }";
  83247. if ((identity == null ? void 0 : identity.type) === "always") {
  83248. return `.generatedAlwaysAsIdentity(${paramsObj})`;
  83249. }
  83250. return `.generatedByDefaultAsIdentity(${paramsObj})`;
  83251. }
  83252. var import_casing3, gelImportsList, mapColumnDefault2, relations2, escapeColumnKey2, withCasing2, dbColumnName2, paramNameFor, schemaToTypeScript2, isCyclic2, isSelf2, buildArrayDefault, mapDefault, column7, dimensionsInArray, createTableColumns2, createTableIndexes2, createTablePKs2, createTablePolicies, createTableUniques2, createTableChecks2, createTableFKs2;
  83253. var init_introspect_gel = __esm({
  83254. "src/introspect-gel.ts"() {
  83255. "use strict";
  83256. init_utils();
  83257. import_casing3 = require("drizzle-orm/casing");
  83258. init_global();
  83259. init_gelSerializer();
  83260. init_utils2();
  83261. gelImportsList = /* @__PURE__ */ new Set([
  83262. "gelTable",
  83263. "smallint",
  83264. "integer",
  83265. "bigint",
  83266. "bigintT",
  83267. "boolean",
  83268. "bytes",
  83269. "dateDuration",
  83270. "decimal",
  83271. "doublePrecision",
  83272. "duration",
  83273. "json",
  83274. "localDate",
  83275. "localTime",
  83276. "real",
  83277. "relDuration",
  83278. "text",
  83279. "timestamp",
  83280. "timestamptz",
  83281. "uuid",
  83282. "time"
  83283. ]);
  83284. mapColumnDefault2 = (defaultValue, isExpression) => {
  83285. if (isExpression) {
  83286. return `sql\`${defaultValue}\``;
  83287. }
  83288. return defaultValue;
  83289. };
  83290. relations2 = /* @__PURE__ */ new Set();
  83291. escapeColumnKey2 = (value) => {
  83292. if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
  83293. return `"${value}"`;
  83294. }
  83295. return value;
  83296. };
  83297. withCasing2 = (value, casing2) => {
  83298. if (casing2 === "preserve") {
  83299. return escapeColumnKey2(value);
  83300. }
  83301. if (casing2 === "camel") {
  83302. return escapeColumnKey2(value.camelCase());
  83303. }
  83304. assertUnreachable(casing2);
  83305. };
  83306. dbColumnName2 = ({ name, casing: casing2, withMode = false }) => {
  83307. if (casing2 === "preserve") {
  83308. return "";
  83309. }
  83310. if (casing2 === "camel") {
  83311. return (0, import_casing3.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
  83312. }
  83313. assertUnreachable(casing2);
  83314. };
  83315. paramNameFor = (name, schema6) => {
  83316. const schemaSuffix = schema6 && schema6 !== "public" ? `In${schema6.capitalise()}` : "";
  83317. return `${name}${schemaSuffix}`;
  83318. };
  83319. schemaToTypeScript2 = (schema6, casing2) => {
  83320. Object.values(schema6.tables).forEach((table6) => {
  83321. Object.values(table6.foreignKeys).forEach((fk5) => {
  83322. const relation = `${fk5.tableFrom}-${fk5.tableTo}`;
  83323. relations2.add(relation);
  83324. });
  83325. });
  83326. const schemas = Object.fromEntries(
  83327. Object.entries(schema6.schemas).map((it) => {
  83328. return [it[0], withCasing2(it[1].replace("::", ""), casing2)];
  83329. })
  83330. );
  83331. const imports = Object.values(schema6.tables).reduce(
  83332. (res, it) => {
  83333. const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
  83334. const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
  83335. if (Object.values(it.foreignKeys).some((it2) => isCyclic2(it2) && !isSelf2(it2))) {
  83336. res.gel.push("type AnyGelColumn");
  83337. }
  83338. const pkImports = Object.values(it.compositePrimaryKeys).map((it2) => "primaryKey");
  83339. const uniqueImports = Object.values(it.uniqueConstraints).map((it2) => "unique");
  83340. const checkImports = Object.values(it.checkConstraints).map(
  83341. (it2) => "check"
  83342. );
  83343. const policiesImports = Object.values(it.policies).map(
  83344. (it2) => "gelPolicy"
  83345. );
  83346. if (it.schema && it.schema !== "public" && it.schema !== "") {
  83347. res.gel.push("gelSchema");
  83348. }
  83349. res.gel.push(...idxImports);
  83350. res.gel.push(...fkImpots);
  83351. res.gel.push(...pkImports);
  83352. res.gel.push(...uniqueImports);
  83353. res.gel.push(...policiesImports);
  83354. res.gel.push(...checkImports);
  83355. const columnImports = Object.values(it.columns).map((col) => {
  83356. var _a2;
  83357. let patched = ((_a2 = col.type) == null ? void 0 : _a2.replace("[]", "")) ?? "";
  83358. patched = patched.startsWith("time without time zone") ? "localTime" : patched;
  83359. patched = patched === "double precision" ? "doublePrecision" : patched;
  83360. patched = patched.startsWith("edgedbt.bigint_t") ? "bigintT" : patched;
  83361. patched = patched.startsWith("jsonb") ? "json" : patched;
  83362. patched = patched.startsWith("edgedbt.timestamptz_t") ? "timestamptz" : patched;
  83363. patched = patched.startsWith("edgedbt.timestamp_t") ? "timestamp" : patched;
  83364. patched = patched.startsWith("edgedbt.relative_duration_t") ? "relDuration" : patched;
  83365. patched = patched.startsWith("bytea") ? "bytes" : patched;
  83366. patched = patched.startsWith("numeric") ? "decimal" : patched;
  83367. patched = patched.startsWith("edgedbt.duration_t") ? "duration" : patched;
  83368. patched = patched.startsWith("edgedbt.date_t") ? "localDate" : patched;
  83369. patched = patched.startsWith("edgedbt.date_duration_t") ? "dateDuration" : patched;
  83370. return patched;
  83371. }).filter((type) => {
  83372. return gelImportsList.has(type);
  83373. });
  83374. res.gel.push(...columnImports);
  83375. return res;
  83376. },
  83377. { gel: [] }
  83378. );
  83379. if (Object.keys(schema6.roles).length > 0) {
  83380. imports.gel.push("gelRole");
  83381. }
  83382. const schemaStatements = Object.entries(schemas).filter((it) => it[0] !== "public").map((it) => {
  83383. return `export const ${it[1].replace("::", "").camelCase()} = gelSchema("${it[0]}");
  83384. `;
  83385. }).join("");
  83386. const rolesNameToTsKey = {};
  83387. const rolesStatements = Object.entries(schema6.roles).map((it) => {
  83388. const fields = it[1];
  83389. rolesNameToTsKey[fields.name] = it[0];
  83390. return `export const ${withCasing2(it[0], casing2)} = gelRole("${fields.name}", ${!fields.createDb && !fields.createRole && fields.inherit ? "" : `${`, { ${fields.createDb ? `createDb: true,` : ""}${fields.createRole ? ` createRole: true,` : ""}${!fields.inherit ? ` inherit: false ` : ""}`.trimChar(",")}}`} );
  83391. `;
  83392. }).join("");
  83393. const tableStatements = Object.values(schema6.tables).map((table6) => {
  83394. const tableSchema = schemas[table6.schema];
  83395. const paramName = paramNameFor(table6.name, tableSchema);
  83396. const func = tableSchema ? `${tableSchema}.table` : "gelTable";
  83397. let statement = `export const ${withCasing2(paramName, casing2)} = ${func}("${table6.name}", {
  83398. `;
  83399. statement += createTableColumns2(
  83400. table6.name,
  83401. Object.values(table6.columns),
  83402. Object.values(table6.foreignKeys),
  83403. // enumTypes,
  83404. /* @__PURE__ */ new Set(),
  83405. schemas,
  83406. casing2,
  83407. schema6.internal
  83408. );
  83409. statement += "}";
  83410. if (Object.keys(table6.indexes).length > 0 || Object.values(table6.foreignKeys).length > 0 || Object.values(table6.policies).length > 0 || Object.keys(table6.compositePrimaryKeys).length > 0 || Object.keys(table6.uniqueConstraints).length > 0 || Object.keys(table6.checkConstraints).length > 0) {
  83411. statement += ", ";
  83412. statement += "(table) => [";
  83413. statement += createTableIndexes2(table6.name, Object.values(table6.indexes), casing2);
  83414. statement += createTableFKs2(Object.values(table6.foreignKeys), schemas, casing2);
  83415. statement += createTablePKs2(
  83416. Object.values(table6.compositePrimaryKeys),
  83417. casing2
  83418. );
  83419. statement += createTableUniques2(
  83420. Object.values(table6.uniqueConstraints),
  83421. casing2
  83422. );
  83423. statement += createTablePolicies(
  83424. Object.values(table6.policies),
  83425. casing2,
  83426. rolesNameToTsKey
  83427. );
  83428. statement += createTableChecks2(
  83429. Object.values(table6.checkConstraints),
  83430. casing2
  83431. );
  83432. statement += "\n]";
  83433. }
  83434. statement += ");";
  83435. return statement;
  83436. });
  83437. const uniqueGelImports = ["gelTable", ...new Set(imports.gel)];
  83438. const importsTs = `import { ${uniqueGelImports.join(
  83439. ", "
  83440. )} } from "drizzle-orm/gel-core"
  83441. import { sql } from "drizzle-orm"
  83442. `;
  83443. let decalrations = schemaStatements;
  83444. decalrations += rolesStatements;
  83445. decalrations += "\n";
  83446. decalrations += tableStatements.join("\n\n");
  83447. decalrations += "\n";
  83448. const file = importsTs + decalrations;
  83449. const schemaEntry = `
  83450. {
  83451. ${Object.values(schema6.tables).map((it) => withCasing2(it.name, casing2)).join(",\n")}
  83452. }
  83453. `;
  83454. return { file, imports: importsTs, decalrations, schemaEntry };
  83455. };
  83456. isCyclic2 = (fk5) => {
  83457. const key = `${fk5.tableFrom}-${fk5.tableTo}`;
  83458. const reverse = `${fk5.tableTo}-${fk5.tableFrom}`;
  83459. return relations2.has(key) && relations2.has(reverse);
  83460. };
  83461. isSelf2 = (fk5) => {
  83462. return fk5.tableFrom === fk5.tableTo;
  83463. };
  83464. buildArrayDefault = (defaultValue, typeName) => {
  83465. if (typeof defaultValue === "string" && !(defaultValue.startsWith("_nullif_array_nulls(ARRAY[") || defaultValue.startsWith("ARRAY["))) {
  83466. return `sql\`${defaultValue}\``;
  83467. }
  83468. const regex = /ARRAY\[(.*)\]/;
  83469. const match2 = defaultValue.match(regex);
  83470. if (!match2) {
  83471. return `sql\`${defaultValue}\``;
  83472. }
  83473. defaultValue = match2[1];
  83474. return `sql\`[${defaultValue}]\``;
  83475. };
  83476. mapDefault = (tableName, type, name, enumTypes, typeSchema, defaultValue, internals) => {
  83477. var _a2, _b, _c, _d;
  83478. const isExpression = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
  83479. const isArray = ((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[name]) == null ? void 0 : _d.isArray) ?? false;
  83480. const lowered = type.toLowerCase().replace("[]", "");
  83481. if (name === "id") {
  83482. return `.default(sql\`uuid_generate_v4()\`)`;
  83483. }
  83484. if (isArray) {
  83485. return typeof defaultValue !== "undefined" ? `.default(${buildArrayDefault(defaultValue, lowered)})` : "";
  83486. }
  83487. if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
  83488. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
  83489. }
  83490. if (lowered.startsWith("integer")) {
  83491. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue.replaceAll("(", "").replaceAll(")", ""), isExpression)})` : "";
  83492. }
  83493. if (lowered.startsWith("smallint")) {
  83494. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue.replaceAll("(", "").replaceAll(")", ""), isExpression)})` : "";
  83495. }
  83496. if (lowered.startsWith("bigint")) {
  83497. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue.replaceAll("(", "").replaceAll(")", ""), isExpression)})` : "";
  83498. }
  83499. if (lowered.startsWith("edgedbt.bigint_t")) {
  83500. return typeof defaultValue !== "undefined" ? `.default(BigInt(${mapColumnDefault2(defaultValue.replaceAll("(", "").replaceAll(")", ""), isExpression)}))` : "";
  83501. }
  83502. if (lowered.startsWith("boolean")) {
  83503. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
  83504. }
  83505. if (lowered.startsWith("double precision")) {
  83506. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
  83507. }
  83508. if (lowered.startsWith("edgedbt.date_duration_t")) {
  83509. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, true)})` : "";
  83510. }
  83511. if (lowered.startsWith("real")) {
  83512. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : "";
  83513. }
  83514. if (lowered.startsWith("uuid")) {
  83515. const res = defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
  83516. return res;
  83517. }
  83518. if (lowered.startsWith("numeric")) {
  83519. defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
  83520. return defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
  83521. }
  83522. if (lowered.startsWith("edgedbt.timestamptz_t")) {
  83523. return defaultValue === "now()" ? ".defaultNow()" : /^'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?([+-]\d{2}(:\d{2})?)?'$/.test(defaultValue) ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
  83524. }
  83525. if (lowered.startsWith("time without time zone")) {
  83526. return defaultValue === "now()" ? ".defaultNow()" : /^'\d{2}:\d{2}(:\d{2})?(\.\d+)?'$/.test(defaultValue) ? `.default(${mapColumnDefault2(defaultValue, isExpression)})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
  83527. }
  83528. if (lowered.startsWith("edgedbt.duration_t")) {
  83529. return defaultValue ? `.default(${mapColumnDefault2(defaultValue, true)})` : "";
  83530. }
  83531. if (lowered === "edgedbt.date_t") {
  83532. return defaultValue === "now()" ? ".defaultNow()" : /^'\d{4}-\d{2}-\d{2}'$/.test(defaultValue) ? `.default(${defaultValue})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
  83533. }
  83534. if (lowered.startsWith("edgedbt.relative_duration_t")) {
  83535. return defaultValue ? `.default(${mapColumnDefault2(defaultValue, true)})` : "";
  83536. }
  83537. if (lowered.startsWith("text")) {
  83538. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
  83539. }
  83540. if (lowered.startsWith("json")) {
  83541. const def = typeof defaultValue !== "undefined" ? defaultValue : null;
  83542. return defaultValue ? `.default(sql\`${def}\`)` : "";
  83543. }
  83544. if (lowered.startsWith("bytea")) {
  83545. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault2(defaultValue, true)})` : "";
  83546. }
  83547. return "";
  83548. };
  83549. column7 = (tableName, type, name, enumTypes, typeSchema, casing2, defaultValue, internals) => {
  83550. var _a2, _b;
  83551. const isExpression = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
  83552. const lowered = type.toLowerCase().replace("[]", "");
  83553. if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
  83554. let out = `${withCasing2(name, casing2)}: ${withCasing2(paramNameFor(type.replace("[]", ""), typeSchema), casing2)}(${dbColumnName2({ name, casing: casing2 })})`;
  83555. return out;
  83556. }
  83557. if (lowered.startsWith("integer")) {
  83558. let out = `${withCasing2(name, casing2)}: integer(${dbColumnName2({ name, casing: casing2 })})`;
  83559. return out;
  83560. }
  83561. if (lowered.startsWith("smallint")) {
  83562. let out = `${withCasing2(name, casing2)}: smallint(${dbColumnName2({ name, casing: casing2 })})`;
  83563. return out;
  83564. }
  83565. if (lowered.startsWith("bigint")) {
  83566. let out = `${withCasing2(name, casing2)}: bigint(${dbColumnName2({ name, casing: casing2 })})`;
  83567. return out;
  83568. }
  83569. if (lowered.startsWith("edgedbt.bigint_t")) {
  83570. let out = `${withCasing2(name, casing2)}: bigintT(${dbColumnName2({ name, casing: casing2 })})`;
  83571. return out;
  83572. }
  83573. if (lowered.startsWith("boolean")) {
  83574. let out = `${withCasing2(name, casing2)}: boolean(${dbColumnName2({ name, casing: casing2 })})`;
  83575. return out;
  83576. }
  83577. if (lowered.startsWith("double precision")) {
  83578. let out = `${withCasing2(name, casing2)}: doublePrecision(${dbColumnName2({ name, casing: casing2 })})`;
  83579. return out;
  83580. }
  83581. if (lowered.startsWith("edgedbt.date_duration_t")) {
  83582. let out = `${withCasing2(name, casing2)}: dateDuration(${dbColumnName2({ name, casing: casing2 })})`;
  83583. return out;
  83584. }
  83585. if (lowered.startsWith("real")) {
  83586. let out = `${withCasing2(name, casing2)}: real(${dbColumnName2({ name, casing: casing2 })})`;
  83587. return out;
  83588. }
  83589. if (lowered.startsWith("uuid")) {
  83590. let out = `${withCasing2(name, casing2)}: uuid(${dbColumnName2({ name, casing: casing2 })})`;
  83591. return out;
  83592. }
  83593. if (lowered.startsWith("numeric")) {
  83594. let out = `${withCasing2(name, casing2)}: decimal(${dbColumnName2({ name, casing: casing2 })})`;
  83595. return out;
  83596. }
  83597. if (lowered.startsWith("edgedbt.timestamptz_t")) {
  83598. let out = `${withCasing2(name, casing2)}: timestamptz(${dbColumnName2({ name, casing: casing2 })})`;
  83599. return out;
  83600. }
  83601. if (lowered.startsWith("edgedbt.timestamp_t")) {
  83602. let out = `${withCasing2(name, casing2)}: timestamp(${dbColumnName2({ name, casing: casing2 })})`;
  83603. return out;
  83604. }
  83605. if (lowered.startsWith("edgedbt.date_t")) {
  83606. let out = `${withCasing2(name, casing2)}: localDate(${dbColumnName2({ name, casing: casing2 })})`;
  83607. return out;
  83608. }
  83609. if (lowered.startsWith("edgedbt.duration_t")) {
  83610. let out = `${withCasing2(name, casing2)}: duration(${dbColumnName2({ name, casing: casing2 })})`;
  83611. return out;
  83612. }
  83613. if (lowered.startsWith("edgedbt.relative_duration_t")) {
  83614. let out = `${withCasing2(name, casing2)}: relDuration(${dbColumnName2({ name, casing: casing2 })})`;
  83615. return out;
  83616. }
  83617. if (lowered.startsWith("text")) {
  83618. let out = `${withCasing2(name, casing2)}: text(${dbColumnName2({ name, casing: casing2 })})`;
  83619. return out;
  83620. }
  83621. if (lowered.startsWith("jsonb")) {
  83622. let out = `${withCasing2(name, casing2)}: json(${dbColumnName2({ name, casing: casing2 })})`;
  83623. return out;
  83624. }
  83625. if (lowered.startsWith("time without time zone")) {
  83626. let out = `${withCasing2(name, casing2)}: localTime(${dbColumnName2({ name, casing: casing2 })})`;
  83627. return out;
  83628. }
  83629. if (lowered.startsWith("bytea")) {
  83630. let out = `${withCasing2(name, casing2)}: bytes(${dbColumnName2({ name, casing: casing2 })})`;
  83631. return out;
  83632. }
  83633. let unknown = `// TODO: failed to parse database type '${type}'
  83634. `;
  83635. unknown += ` ${withCasing2(name, casing2)}: unknown("${name}")`;
  83636. return unknown;
  83637. };
  83638. dimensionsInArray = (size) => {
  83639. let res = "";
  83640. if (typeof size === "undefined") return res;
  83641. for (let i4 = 0; i4 < size; i4++) {
  83642. res += ".array()";
  83643. }
  83644. return res;
  83645. };
  83646. createTableColumns2 = (tableName, columns, fks, enumTypes, schemas, casing2, internals) => {
  83647. let statement = "";
  83648. const oneColumnsFKs = Object.values(fks).filter((it) => {
  83649. return !isSelf2(it);
  83650. }).filter((it) => it.columnsFrom.length === 1);
  83651. const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
  83652. const arr = res[it.columnsFrom[0]] || [];
  83653. arr.push(it);
  83654. res[it.columnsFrom[0]] = arr;
  83655. return res;
  83656. }, {});
  83657. columns.forEach((it) => {
  83658. var _a2, _b, _c, _d;
  83659. const columnStatement = column7(
  83660. tableName,
  83661. it.type,
  83662. it.name,
  83663. enumTypes,
  83664. it.typeSchema ?? "public",
  83665. casing2,
  83666. it.default,
  83667. internals
  83668. );
  83669. statement += " ";
  83670. statement += columnStatement;
  83671. if ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[it.name]) == null ? void 0 : _b.isArray) {
  83672. statement += dimensionsInArray((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[it.name]) == null ? void 0 : _d.dimensions);
  83673. }
  83674. statement += mapDefault(tableName, it.type, it.name, enumTypes, it.typeSchema ?? "public", it.default, internals);
  83675. statement += it.primaryKey ? ".primaryKey()" : "";
  83676. statement += it.notNull && !it.identity ? ".notNull()" : "";
  83677. statement += it.identity ? generateIdentityParams(it.identity) : "";
  83678. statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as}\`)` : "";
  83679. statement += ",\n";
  83680. });
  83681. return statement;
  83682. };
  83683. createTableIndexes2 = (tableName, idxs, casing2) => {
  83684. let statement = "";
  83685. idxs.forEach((it) => {
  83686. let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
  83687. idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
  83688. idxKey = withCasing2(idxKey, casing2);
  83689. const indexGeneratedName = indexName5(
  83690. tableName,
  83691. it.columns.map((it2) => it2.expression)
  83692. );
  83693. const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
  83694. statement += `
  83695. `;
  83696. statement += it.isUnique ? "uniqueIndex(" : "index(";
  83697. statement += `${escapedIndexName})`;
  83698. statement += `${it.concurrently ? `.concurrently()` : ""}`;
  83699. statement += `.using("${it.method}", ${it.columns.map((it2) => {
  83700. if (it2.isExpression) {
  83701. return `sql\`${it2.expression}\``;
  83702. } else {
  83703. return `table.${withCasing2(it2.expression, casing2)}${it2.asc ? ".asc()" : ".desc()"}${it2.nulls === "first" ? ".nullsFirst()" : ".nullsLast()"}${it2.opclass ? `.op("${it2.opclass}")` : ""}`;
  83704. }
  83705. }).join(", ")})`;
  83706. statement += it.where ? `.where(sql\`${it.where}\`)` : "";
  83707. function reverseLogic(mappedWith) {
  83708. let reversedString = "{";
  83709. for (const key in mappedWith) {
  83710. if (mappedWith.hasOwnProperty(key)) {
  83711. reversedString += `${key}: "${mappedWith[key]}",`;
  83712. }
  83713. }
  83714. reversedString = reversedString.length > 1 ? reversedString.slice(0, reversedString.length - 1) : reversedString;
  83715. return `${reversedString}}`;
  83716. }
  83717. statement += it.with && Object.keys(it.with).length > 0 ? `.with(${reverseLogic(it.with)})` : "";
  83718. statement += `,`;
  83719. });
  83720. return statement;
  83721. };
  83722. createTablePKs2 = (pks, casing2) => {
  83723. let statement = "";
  83724. pks.forEach((it) => {
  83725. statement += `
  83726. `;
  83727. statement += "primaryKey({ columns: [";
  83728. statement += `${it.columns.map((c3) => {
  83729. return `table.${withCasing2(c3, casing2)}`;
  83730. }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
  83731. statement += ")";
  83732. statement += `,`;
  83733. });
  83734. return statement;
  83735. };
  83736. createTablePolicies = (policies, casing2, rolesNameToTsKey = {}) => {
  83737. let statement = "";
  83738. policies.forEach((it) => {
  83739. var _a2, _b, _c;
  83740. const idxKey = withCasing2(it.name, casing2);
  83741. const mappedItTo = (_a2 = it.to) == null ? void 0 : _a2.map((v6) => {
  83742. return rolesNameToTsKey[v6] ? withCasing2(rolesNameToTsKey[v6], casing2) : `"${v6}"`;
  83743. });
  83744. statement += `
  83745. `;
  83746. statement += "gelPolicy(";
  83747. statement += `"${it.name}", { `;
  83748. statement += `as: "${(_b = it.as) == null ? void 0 : _b.toLowerCase()}", for: "${(_c = it.for) == null ? void 0 : _c.toLowerCase()}", to: [${mappedItTo == null ? void 0 : mappedItTo.join(", ")}]${it.using ? `, using: sql\`${it.using}\`` : ""}${it.withCheck ? `, withCheck: sql\`${it.withCheck}\` ` : ""}`;
  83749. statement += ` }),`;
  83750. });
  83751. return statement;
  83752. };
  83753. createTableUniques2 = (unqs, casing2) => {
  83754. let statement = "";
  83755. unqs.forEach((it) => {
  83756. statement += `
  83757. `;
  83758. statement += "unique(";
  83759. statement += `"${it.name}")`;
  83760. statement += `.on(${it.columns.map((it2) => `table.${withCasing2(it2, casing2)}`).join(", ")})`;
  83761. statement += it.nullsNotDistinct ? `.nullsNotDistinct()` : "";
  83762. statement += `,`;
  83763. });
  83764. return statement;
  83765. };
  83766. createTableChecks2 = (checkConstraints, casing2) => {
  83767. let statement = "";
  83768. checkConstraints.forEach((it) => {
  83769. statement += `
  83770. `;
  83771. statement += "check(";
  83772. statement += `"${it.name}", `;
  83773. statement += `sql\`${it.value}\`)`;
  83774. statement += `,`;
  83775. });
  83776. return statement;
  83777. };
  83778. createTableFKs2 = (fks, schemas, casing2) => {
  83779. let statement = "";
  83780. fks.forEach((it) => {
  83781. const tableSchema = schemas[it.schemaTo || ""];
  83782. const paramName = paramNameFor(it.tableTo, tableSchema);
  83783. const isSelf5 = it.tableTo === it.tableFrom;
  83784. const tableTo = isSelf5 ? "table" : `${withCasing2(paramName, casing2)}`;
  83785. statement += `
  83786. `;
  83787. statement += `foreignKey({
  83788. `;
  83789. statement += ` columns: [${it.columnsFrom.map((i4) => `table.${withCasing2(i4, casing2)}`).join(", ")}],
  83790. `;
  83791. statement += ` foreignColumns: [${it.columnsTo.map((i4) => `${tableTo}.${withCasing2(i4, casing2)}`).join(", ")}],
  83792. `;
  83793. statement += ` name: "${it.name}"
  83794. `;
  83795. statement += ` })`;
  83796. statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
  83797. statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
  83798. statement += `,`;
  83799. });
  83800. return statement;
  83801. };
  83802. }
  83803. });
  83804. // src/introspect-mysql.ts
  83805. var import_casing4, mysqlImportsList, objToStatement22, timeConfig, binaryConfig, importsPatch, relations3, escapeColumnKey3, prepareCasing, dbColumnName3, schemaToTypeScript3, isCyclic3, isSelf3, mapColumnDefault3, mapColumnDefaultForJson, column8, createTableColumns3, createTableIndexes3, createTableUniques3, createTableChecks3, createTablePKs3, createTableFKs3;
  83806. var init_introspect_mysql = __esm({
  83807. "src/introspect-mysql.ts"() {
  83808. "use strict";
  83809. import_casing4 = require("drizzle-orm/casing");
  83810. init_utils();
  83811. init_global();
  83812. init_utils2();
  83813. mysqlImportsList = /* @__PURE__ */ new Set([
  83814. "mysqlTable",
  83815. "mysqlEnum",
  83816. "bigint",
  83817. "binary",
  83818. "boolean",
  83819. "char",
  83820. "date",
  83821. "datetime",
  83822. "decimal",
  83823. "double",
  83824. "float",
  83825. "int",
  83826. "json",
  83827. "mediumint",
  83828. "real",
  83829. "serial",
  83830. "smallint",
  83831. "text",
  83832. "tinytext",
  83833. "mediumtext",
  83834. "longtext",
  83835. "time",
  83836. "timestamp",
  83837. "tinyint",
  83838. "varbinary",
  83839. "varchar",
  83840. "year",
  83841. "enum"
  83842. ]);
  83843. objToStatement22 = (json) => {
  83844. json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
  83845. const keys = Object.keys(json);
  83846. if (keys.length === 0) return;
  83847. let statement = "{ ";
  83848. statement += keys.map((it) => `${it}: "${json[it]}"`).join(", ");
  83849. statement += " }";
  83850. return statement;
  83851. };
  83852. timeConfig = (json) => {
  83853. json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
  83854. const keys = Object.keys(json);
  83855. if (keys.length === 0) return;
  83856. let statement = "{ ";
  83857. statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
  83858. statement += " }";
  83859. return statement;
  83860. };
  83861. binaryConfig = (json) => {
  83862. json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
  83863. const keys = Object.keys(json);
  83864. if (keys.length === 0) return;
  83865. let statement = "{ ";
  83866. statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
  83867. statement += " }";
  83868. return statement;
  83869. };
  83870. importsPatch = {
  83871. "double precision": "doublePrecision",
  83872. "timestamp without time zone": "timestamp"
  83873. };
  83874. relations3 = /* @__PURE__ */ new Set();
  83875. escapeColumnKey3 = (value) => {
  83876. if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
  83877. return `"${value}"`;
  83878. }
  83879. return value;
  83880. };
  83881. prepareCasing = (casing2) => (value) => {
  83882. if (casing2 === "preserve") {
  83883. return escapeColumnKey3(value);
  83884. }
  83885. if (casing2 === "camel") {
  83886. return escapeColumnKey3(value.camelCase());
  83887. }
  83888. assertUnreachable(casing2);
  83889. };
  83890. dbColumnName3 = ({ name, casing: casing2, withMode = false }) => {
  83891. if (casing2 === "preserve") {
  83892. return "";
  83893. }
  83894. if (casing2 === "camel") {
  83895. return (0, import_casing4.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
  83896. }
  83897. assertUnreachable(casing2);
  83898. };
  83899. schemaToTypeScript3 = (schema6, casing2) => {
  83900. const withCasing5 = prepareCasing(casing2);
  83901. Object.values(schema6.tables).forEach((table6) => {
  83902. Object.values(table6.foreignKeys).forEach((fk5) => {
  83903. const relation = `${fk5.tableFrom}-${fk5.tableTo}`;
  83904. relations3.add(relation);
  83905. });
  83906. });
  83907. const imports = Object.values(schema6.tables).reduce(
  83908. (res, it) => {
  83909. const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
  83910. const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
  83911. const pkImports = Object.values(it.compositePrimaryKeys).map(
  83912. (it2) => "primaryKey"
  83913. );
  83914. const uniqueImports = Object.values(it.uniqueConstraints).map(
  83915. (it2) => "unique"
  83916. );
  83917. const checkImports = Object.values(it.checkConstraint).map(
  83918. (it2) => "check"
  83919. );
  83920. res.mysql.push(...idxImports);
  83921. res.mysql.push(...fkImpots);
  83922. res.mysql.push(...pkImports);
  83923. res.mysql.push(...uniqueImports);
  83924. res.mysql.push(...checkImports);
  83925. const columnImports = Object.values(it.columns).map((col) => {
  83926. let patched = importsPatch[col.type] ?? col.type;
  83927. patched = patched.startsWith("varchar(") ? "varchar" : patched;
  83928. patched = patched.startsWith("char(") ? "char" : patched;
  83929. patched = patched.startsWith("binary(") ? "binary" : patched;
  83930. patched = patched.startsWith("decimal(") ? "decimal" : patched;
  83931. patched = patched.startsWith("smallint(") ? "smallint" : patched;
  83932. patched = patched.startsWith("enum(") ? "mysqlEnum" : patched;
  83933. patched = patched.startsWith("datetime(") ? "datetime" : patched;
  83934. patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
  83935. patched = patched.startsWith("int(") ? "int" : patched;
  83936. patched = patched.startsWith("double(") ? "double" : patched;
  83937. patched = patched.startsWith("float(") ? "float" : patched;
  83938. patched = patched.startsWith("int unsigned") ? "int" : patched;
  83939. patched = patched.startsWith("tinyint unsigned") ? "tinyint" : patched;
  83940. patched = patched.startsWith("smallint unsigned") ? "smallint" : patched;
  83941. patched = patched.startsWith("mediumint unsigned") ? "mediumint" : patched;
  83942. patched = patched.startsWith("bigint unsigned") ? "bigint" : patched;
  83943. return patched;
  83944. }).filter((type) => {
  83945. return mysqlImportsList.has(type);
  83946. });
  83947. res.mysql.push(...columnImports);
  83948. return res;
  83949. },
  83950. { mysql: [] }
  83951. );
  83952. Object.values(schema6.views).forEach((it) => {
  83953. imports.mysql.push("mysqlView");
  83954. const columnImports = Object.values(it.columns).map((col) => {
  83955. let patched = importsPatch[col.type] ?? col.type;
  83956. patched = patched.startsWith("varchar(") ? "varchar" : patched;
  83957. patched = patched.startsWith("char(") ? "char" : patched;
  83958. patched = patched.startsWith("binary(") ? "binary" : patched;
  83959. patched = patched.startsWith("decimal(") ? "decimal" : patched;
  83960. patched = patched.startsWith("smallint(") ? "smallint" : patched;
  83961. patched = patched.startsWith("enum(") ? "mysqlEnum" : patched;
  83962. patched = patched.startsWith("datetime(") ? "datetime" : patched;
  83963. patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
  83964. patched = patched.startsWith("int(") ? "int" : patched;
  83965. patched = patched.startsWith("double(") ? "double" : patched;
  83966. patched = patched.startsWith("float(") ? "float" : patched;
  83967. patched = patched.startsWith("int unsigned") ? "int" : patched;
  83968. patched = patched.startsWith("tinyint unsigned") ? "tinyint" : patched;
  83969. patched = patched.startsWith("smallint unsigned") ? "smallint" : patched;
  83970. patched = patched.startsWith("mediumint unsigned") ? "mediumint" : patched;
  83971. patched = patched.startsWith("bigint unsigned") ? "bigint" : patched;
  83972. return patched;
  83973. }).filter((type) => {
  83974. return mysqlImportsList.has(type);
  83975. });
  83976. imports.mysql.push(...columnImports);
  83977. });
  83978. const tableStatements = Object.values(schema6.tables).map((table6) => {
  83979. const func = "mysqlTable";
  83980. let statement = "";
  83981. if (imports.mysql.includes(withCasing5(table6.name))) {
  83982. statement = `// Table name is in conflict with ${withCasing5(
  83983. table6.name
  83984. )} import.
  83985. // Please change to any other name, that is not in imports list
  83986. `;
  83987. }
  83988. statement += `export const ${withCasing5(table6.name)} = ${func}("${table6.name}", {
  83989. `;
  83990. statement += createTableColumns3(
  83991. Object.values(table6.columns),
  83992. Object.values(table6.foreignKeys),
  83993. withCasing5,
  83994. casing2,
  83995. table6.name,
  83996. schema6
  83997. );
  83998. statement += "}";
  83999. const filteredFKs = Object.values(table6.foreignKeys).filter((it) => {
  84000. return it.columnsFrom.length > 1 || isSelf3(it);
  84001. });
  84002. if (Object.keys(table6.indexes).length > 0 || filteredFKs.length > 0 || Object.keys(table6.compositePrimaryKeys).length > 0 || Object.keys(table6.uniqueConstraints).length > 0 || Object.keys(table6.checkConstraint).length > 0) {
  84003. statement += ",\n";
  84004. statement += "(table) => [";
  84005. statement += createTableIndexes3(
  84006. table6.name,
  84007. Object.values(table6.indexes),
  84008. withCasing5
  84009. );
  84010. statement += createTableFKs3(Object.values(filteredFKs), withCasing5);
  84011. statement += createTablePKs3(
  84012. Object.values(table6.compositePrimaryKeys),
  84013. withCasing5
  84014. );
  84015. statement += createTableUniques3(
  84016. Object.values(table6.uniqueConstraints),
  84017. withCasing5
  84018. );
  84019. statement += createTableChecks3(
  84020. Object.values(table6.checkConstraint),
  84021. withCasing5
  84022. );
  84023. statement += "\n]";
  84024. }
  84025. statement += ");";
  84026. return statement;
  84027. });
  84028. const viewsStatements = Object.values(schema6.views).map((view5) => {
  84029. const { columns, name, algorithm, definition, sqlSecurity, withCheckOption } = view5;
  84030. const func = "mysqlView";
  84031. let statement = "";
  84032. if (imports.mysql.includes(withCasing5(name))) {
  84033. statement = `// Table name is in conflict with ${withCasing5(
  84034. view5.name
  84035. )} import.
  84036. // Please change to any other name, that is not in imports list
  84037. `;
  84038. }
  84039. statement += `export const ${withCasing5(name)} = ${func}("${name}", {
  84040. `;
  84041. statement += createTableColumns3(
  84042. Object.values(columns),
  84043. [],
  84044. withCasing5,
  84045. casing2,
  84046. name,
  84047. schema6
  84048. );
  84049. statement += "})";
  84050. statement += algorithm ? `.algorithm("${algorithm}")` : "";
  84051. statement += sqlSecurity ? `.sqlSecurity("${sqlSecurity}")` : "";
  84052. statement += withCheckOption ? `.withCheckOption("${withCheckOption}")` : "";
  84053. statement += `.as(sql\`${definition == null ? void 0 : definition.replaceAll("`", "\\`")}\`);`;
  84054. return statement;
  84055. });
  84056. const uniqueMySqlImports = [
  84057. "mysqlTable",
  84058. "mysqlSchema",
  84059. "AnyMySqlColumn",
  84060. ...new Set(imports.mysql)
  84061. ];
  84062. const importsTs = `import { ${uniqueMySqlImports.join(
  84063. ", "
  84064. )} } from "drizzle-orm/mysql-core"
  84065. import { sql } from "drizzle-orm"
  84066. `;
  84067. let decalrations = "";
  84068. decalrations += tableStatements.join("\n\n");
  84069. decalrations += "\n";
  84070. decalrations += viewsStatements.join("\n\n");
  84071. const file = importsTs + decalrations;
  84072. const schemaEntry = `
  84073. {
  84074. ${Object.values(schema6.tables).map((it) => withCasing5(it.name)).join(",")}
  84075. }
  84076. `;
  84077. return {
  84078. file,
  84079. // backward compatible, print to file
  84080. imports: importsTs,
  84081. decalrations,
  84082. schemaEntry
  84083. };
  84084. };
  84085. isCyclic3 = (fk5) => {
  84086. const key = `${fk5.tableFrom}-${fk5.tableTo}`;
  84087. const reverse = `${fk5.tableTo}-${fk5.tableFrom}`;
  84088. return relations3.has(key) && relations3.has(reverse);
  84089. };
  84090. isSelf3 = (fk5) => {
  84091. return fk5.tableFrom === fk5.tableTo;
  84092. };
  84093. mapColumnDefault3 = (defaultValue, isExpression) => {
  84094. if (isExpression) {
  84095. return `sql\`${defaultValue}\``;
  84096. }
  84097. return defaultValue;
  84098. };
  84099. mapColumnDefaultForJson = (defaultValue) => {
  84100. if (typeof defaultValue === "string" && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
  84101. return defaultValue.substring(2, defaultValue.length - 2);
  84102. }
  84103. return defaultValue;
  84104. };
  84105. column8 = (type, name, casing2, rawCasing, defaultValue, autoincrement, onUpdate, isExpression) => {
  84106. let lowered = type;
  84107. if (!type.startsWith("enum(")) {
  84108. lowered = type.toLowerCase();
  84109. }
  84110. if (lowered === "serial") {
  84111. return `${casing2(name)}: serial(${dbColumnName3({ name, casing: rawCasing })})`;
  84112. }
  84113. if (lowered.startsWith("int")) {
  84114. const isUnsigned = lowered.startsWith("int unsigned");
  84115. const columnName = dbColumnName3({ name, casing: rawCasing, withMode: isUnsigned });
  84116. let out = `${casing2(name)}: int(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
  84117. out += autoincrement ? `.autoincrement()` : "";
  84118. out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84119. return out;
  84120. }
  84121. if (lowered.startsWith("tinyint")) {
  84122. const isUnsigned = lowered.startsWith("tinyint unsigned");
  84123. const columnName = dbColumnName3({ name, casing: rawCasing, withMode: isUnsigned });
  84124. let out = `${casing2(name)}: tinyint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
  84125. out += autoincrement ? `.autoincrement()` : "";
  84126. out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84127. return out;
  84128. }
  84129. if (lowered.startsWith("smallint")) {
  84130. const isUnsigned = lowered.startsWith("smallint unsigned");
  84131. const columnName = dbColumnName3({ name, casing: rawCasing, withMode: isUnsigned });
  84132. let out = `${casing2(name)}: smallint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
  84133. out += autoincrement ? `.autoincrement()` : "";
  84134. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84135. return out;
  84136. }
  84137. if (lowered.startsWith("mediumint")) {
  84138. const isUnsigned = lowered.startsWith("mediumint unsigned");
  84139. const columnName = dbColumnName3({ name, casing: rawCasing, withMode: isUnsigned });
  84140. let out = `${casing2(name)}: mediumint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
  84141. out += autoincrement ? `.autoincrement()` : "";
  84142. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84143. return out;
  84144. }
  84145. if (lowered.startsWith("bigint")) {
  84146. const isUnsigned = lowered.startsWith("bigint unsigned");
  84147. let out = `${casing2(name)}: bigint(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ mode: "number"${isUnsigned ? ", unsigned: true" : ""} })`;
  84148. out += autoincrement ? `.autoincrement()` : "";
  84149. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84150. return out;
  84151. }
  84152. if (lowered === "boolean") {
  84153. let out = `${casing2(name)}: boolean(${dbColumnName3({ name, casing: rawCasing })})`;
  84154. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84155. return out;
  84156. }
  84157. if (lowered.startsWith("double")) {
  84158. let params;
  84159. if (lowered.length > (lowered.includes("unsigned") ? 15 : 6)) {
  84160. const [precision, scale] = lowered.slice(7, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
  84161. params = { precision, scale };
  84162. }
  84163. if (lowered.includes("unsigned")) {
  84164. params = { ...params ?? {}, unsigned: true };
  84165. }
  84166. const timeConfigParams = params ? timeConfig(params) : void 0;
  84167. let out = params ? `${casing2(name)}: double(${dbColumnName3({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfig(params)})` : `${casing2(name)}: double(${dbColumnName3({ name, casing: rawCasing })})`;
  84168. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84169. return out;
  84170. }
  84171. if (lowered.startsWith("float")) {
  84172. let params;
  84173. if (lowered.length > (lowered.includes("unsigned") ? 14 : 5)) {
  84174. const [precision, scale] = lowered.slice(6, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
  84175. params = { precision, scale };
  84176. }
  84177. if (lowered.includes("unsigned")) {
  84178. params = { ...params ?? {}, unsigned: true };
  84179. }
  84180. let out = `${casing2(name)}: float(${dbColumnName3({ name, casing: rawCasing })}${params ? timeConfig(params) : ""})`;
  84181. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84182. return out;
  84183. }
  84184. if (lowered === "real") {
  84185. let out = `${casing2(name)}: real(${dbColumnName3({ name, casing: rawCasing })})`;
  84186. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84187. return out;
  84188. }
  84189. if (lowered.startsWith("timestamp")) {
  84190. const keyLength = "timestamp".length + 1;
  84191. let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
  84192. fsp = fsp ? fsp : null;
  84193. const params = timeConfig({ fsp, mode: "'string'" });
  84194. let out = params ? `${casing2(name)}: timestamp(${dbColumnName3({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: timestamp(${dbColumnName3({ name, casing: rawCasing })})`;
  84195. defaultValue = defaultValue === "now()" || defaultValue === "(CURRENT_TIMESTAMP)" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84196. out += defaultValue;
  84197. let onUpdateNow = onUpdate ? ".onUpdateNow()" : "";
  84198. out += onUpdateNow;
  84199. return out;
  84200. }
  84201. if (lowered.startsWith("time")) {
  84202. const keyLength = "time".length + 1;
  84203. let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
  84204. fsp = fsp ? fsp : null;
  84205. const params = timeConfig({ fsp });
  84206. let out = params ? `${casing2(name)}: time(${dbColumnName3({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: time(${dbColumnName3({ name, casing: rawCasing })})`;
  84207. defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84208. out += defaultValue;
  84209. return out;
  84210. }
  84211. if (lowered === "date") {
  84212. let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
  84213. ${casing2(
  84214. name
  84215. )}: date(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ mode: 'string' })`;
  84216. defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84217. out += defaultValue;
  84218. return out;
  84219. }
  84220. if (lowered === "text") {
  84221. let out = `${casing2(name)}: text(${dbColumnName3({ name, casing: rawCasing })})`;
  84222. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84223. return out;
  84224. }
  84225. if (lowered === "tinytext") {
  84226. let out = `${casing2(name)}: tinytext(${dbColumnName3({ name, casing: rawCasing })})`;
  84227. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84228. return out;
  84229. }
  84230. if (lowered === "mediumtext") {
  84231. let out = `${casing2(name)}: mediumtext(${dbColumnName3({ name, casing: rawCasing })})`;
  84232. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84233. return out;
  84234. }
  84235. if (lowered === "longtext") {
  84236. let out = `${casing2(name)}: longtext(${dbColumnName3({ name, casing: rawCasing })})`;
  84237. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84238. return out;
  84239. }
  84240. if (lowered === "year") {
  84241. let out = `${casing2(name)}: year(${dbColumnName3({ name, casing: rawCasing })})`;
  84242. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84243. return out;
  84244. }
  84245. if (lowered === "json") {
  84246. let out = `${casing2(name)}: json(${dbColumnName3({ name, casing: rawCasing })})`;
  84247. out += defaultValue ? `.default(${mapColumnDefaultForJson(defaultValue)})` : "";
  84248. return out;
  84249. }
  84250. if (lowered.startsWith("varchar")) {
  84251. let out = `${casing2(
  84252. name
  84253. )}: varchar(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
  84254. "varchar".length + 1,
  84255. lowered.length - 1
  84256. )} })`;
  84257. const mappedDefaultValue = mapColumnDefault3(defaultValue, isExpression);
  84258. out += defaultValue ? `.default(${isExpression ? mappedDefaultValue : unescapeSingleQuotes(mappedDefaultValue, true)})` : "";
  84259. return out;
  84260. }
  84261. if (lowered.startsWith("char")) {
  84262. let out = `${casing2(
  84263. name
  84264. )}: char(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
  84265. "char".length + 1,
  84266. lowered.length - 1
  84267. )} })`;
  84268. out += defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84269. return out;
  84270. }
  84271. if (lowered.startsWith("datetime")) {
  84272. let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
  84273. `;
  84274. const fsp = lowered.startsWith("datetime(") ? lowered.substring("datetime".length + 1, lowered.length - 1) : void 0;
  84275. out = fsp ? `${casing2(
  84276. name
  84277. )}: datetime(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ mode: 'string', fsp: ${lowered.substring(
  84278. "datetime".length + 1,
  84279. lowered.length - 1
  84280. )} })` : `${casing2(name)}: datetime(${dbColumnName3({ name, casing: rawCasing, withMode: true })}{ mode: 'string'})`;
  84281. defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84282. out += defaultValue;
  84283. return out;
  84284. }
  84285. if (lowered.startsWith("decimal")) {
  84286. let params;
  84287. if (lowered.length > (lowered.includes("unsigned") ? 16 : 7)) {
  84288. const [precision, scale] = lowered.slice(8, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
  84289. params = { precision, scale };
  84290. }
  84291. if (lowered.includes("unsigned")) {
  84292. params = { ...params ?? {}, unsigned: true };
  84293. }
  84294. const timeConfigParams = params ? timeConfig(params) : void 0;
  84295. let out = params ? `${casing2(name)}: decimal(${dbColumnName3({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfigParams})` : `${casing2(name)}: decimal(${dbColumnName3({ name, casing: rawCasing })})`;
  84296. defaultValue = typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84297. out += defaultValue;
  84298. return out;
  84299. }
  84300. if (lowered.startsWith("binary")) {
  84301. const keyLength = "binary".length + 1;
  84302. let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
  84303. length = length ? length : null;
  84304. const params = binaryConfig({ length });
  84305. let out = params ? `${casing2(name)}: binary(${dbColumnName3({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: binary(${dbColumnName3({ name, casing: rawCasing })})`;
  84306. defaultValue = defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84307. out += defaultValue;
  84308. return out;
  84309. }
  84310. if (lowered.startsWith("enum")) {
  84311. const values = lowered.substring("enum".length + 1, lowered.length - 1).split(",").map((v6) => unescapeSingleQuotes(v6, true)).join(",");
  84312. let out = `${casing2(name)}: mysqlEnum(${dbColumnName3({ name, casing: rawCasing, withMode: true })}[${values}])`;
  84313. const mappedDefaultValue = mapColumnDefault3(defaultValue, isExpression);
  84314. out += defaultValue ? `.default(${isExpression ? mappedDefaultValue : unescapeSingleQuotes(mappedDefaultValue, true)})` : "";
  84315. return out;
  84316. }
  84317. if (lowered.startsWith("varbinary")) {
  84318. const keyLength = "varbinary".length + 1;
  84319. let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
  84320. length = length ? length : null;
  84321. const params = binaryConfig({ length });
  84322. let out = params ? `${casing2(name)}: varbinary(${dbColumnName3({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: varbinary(${dbColumnName3({ name, casing: rawCasing })})`;
  84323. defaultValue = defaultValue ? `.default(${mapColumnDefault3(defaultValue, isExpression)})` : "";
  84324. out += defaultValue;
  84325. return out;
  84326. }
  84327. console.log("uknown", type);
  84328. return `// Warning: Can't parse ${type} from database
  84329. // ${type}Type: ${type}("${name}")`;
  84330. };
  84331. createTableColumns3 = (columns, fks, casing2, rawCasing, tableName, schema6) => {
  84332. let statement = "";
  84333. const oneColumnsFKs = Object.values(fks).filter((it) => {
  84334. return !isSelf3(it);
  84335. }).filter((it) => it.columnsFrom.length === 1);
  84336. const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
  84337. const arr = res[it.columnsFrom[0]] || [];
  84338. arr.push(it);
  84339. res[it.columnsFrom[0]] = arr;
  84340. return res;
  84341. }, {});
  84342. columns.forEach((it) => {
  84343. var _a2, _b, _c;
  84344. statement += " ";
  84345. statement += column8(
  84346. it.type,
  84347. it.name,
  84348. casing2,
  84349. rawCasing,
  84350. it.default,
  84351. it.autoincrement,
  84352. it.onUpdate,
  84353. ((_c = (_b = (_a2 = schema6.internal) == null ? void 0 : _a2.tables[tableName]) == null ? void 0 : _b.columns[it.name]) == null ? void 0 : _c.isDefaultAnExpression) ?? false
  84354. );
  84355. statement += it.primaryKey ? ".primaryKey()" : "";
  84356. statement += it.notNull ? ".notNull()" : "";
  84357. statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as.replace(
  84358. /`/g,
  84359. "\\`"
  84360. )}\`, { mode: "${it.generated.type}" })` : "";
  84361. const fks2 = fkByColumnName[it.name];
  84362. if (fks2) {
  84363. const fksStatement = fks2.map((it2) => {
  84364. const onDelete = it2.onDelete && it2.onDelete !== "no action" ? it2.onDelete : null;
  84365. const onUpdate = it2.onUpdate && it2.onUpdate !== "no action" ? it2.onUpdate : null;
  84366. const params = { onDelete, onUpdate };
  84367. const typeSuffix = isCyclic3(it2) ? ": AnyMySqlColumn" : "";
  84368. const paramsStr = objToStatement22(params);
  84369. if (paramsStr) {
  84370. return `.references(()${typeSuffix} => ${casing2(
  84371. it2.tableTo
  84372. )}.${casing2(it2.columnsTo[0])}, ${paramsStr} )`;
  84373. }
  84374. return `.references(()${typeSuffix} => ${casing2(it2.tableTo)}.${casing2(
  84375. it2.columnsTo[0]
  84376. )})`;
  84377. }).join("");
  84378. statement += fksStatement;
  84379. }
  84380. statement += ",\n";
  84381. });
  84382. return statement;
  84383. };
  84384. createTableIndexes3 = (tableName, idxs, casing2) => {
  84385. let statement = "";
  84386. idxs.forEach((it) => {
  84387. let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
  84388. idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
  84389. idxKey = casing2(idxKey);
  84390. statement += `
  84391. `;
  84392. statement += it.isUnique ? "uniqueIndex(" : "index(";
  84393. statement += `"${it.name}")`;
  84394. statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
  84395. });
  84396. return statement;
  84397. };
  84398. createTableUniques3 = (unqs, casing2) => {
  84399. let statement = "";
  84400. unqs.forEach((it) => {
  84401. const idxKey = casing2(it.name);
  84402. statement += `
  84403. `;
  84404. statement += "unique(";
  84405. statement += `"${it.name}")`;
  84406. statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
  84407. });
  84408. return statement;
  84409. };
  84410. createTableChecks3 = (checks, casing2) => {
  84411. let statement = "";
  84412. checks.forEach((it) => {
  84413. statement += `
  84414. `;
  84415. statement += "check(";
  84416. statement += `"${it.name}", `;
  84417. statement += `sql\`${it.value.replace(/`/g, "\\`")}\`)`;
  84418. statement += `,`;
  84419. });
  84420. return statement;
  84421. };
  84422. createTablePKs3 = (pks, casing2) => {
  84423. let statement = "";
  84424. pks.forEach((it) => {
  84425. let idxKey = casing2(it.name);
  84426. statement += `
  84427. `;
  84428. statement += "primaryKey({ columns: [";
  84429. statement += `${it.columns.map((c3) => {
  84430. return `table.${casing2(c3)}`;
  84431. }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
  84432. statement += "),";
  84433. });
  84434. return statement;
  84435. };
  84436. createTableFKs3 = (fks, casing2) => {
  84437. let statement = "";
  84438. fks.forEach((it) => {
  84439. const isSelf5 = it.tableTo === it.tableFrom;
  84440. const tableTo = isSelf5 ? "table" : `${casing2(it.tableTo)}`;
  84441. statement += `
  84442. `;
  84443. statement += `foreignKey({
  84444. `;
  84445. statement += ` columns: [${it.columnsFrom.map((i4) => `table.${casing2(i4)}`).join(", ")}],
  84446. `;
  84447. statement += ` foreignColumns: [${it.columnsTo.map((i4) => `${tableTo}.${casing2(i4)}`).join(", ")}],
  84448. `;
  84449. statement += ` name: "${it.name}"
  84450. `;
  84451. statement += ` })`;
  84452. statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
  84453. statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
  84454. statement += `,`;
  84455. });
  84456. return statement;
  84457. };
  84458. }
  84459. });
  84460. // src/introspect-pg.ts
  84461. function generateIdentityParams2(identity) {
  84462. let paramsObj = `{ name: "${identity.name}"`;
  84463. if (identity == null ? void 0 : identity.startWith) {
  84464. paramsObj += `, startWith: ${identity.startWith}`;
  84465. }
  84466. if (identity == null ? void 0 : identity.increment) {
  84467. paramsObj += `, increment: ${identity.increment}`;
  84468. }
  84469. if (identity == null ? void 0 : identity.minValue) {
  84470. paramsObj += `, minValue: ${identity.minValue}`;
  84471. }
  84472. if (identity == null ? void 0 : identity.maxValue) {
  84473. paramsObj += `, maxValue: ${identity.maxValue}`;
  84474. }
  84475. if (identity == null ? void 0 : identity.cache) {
  84476. paramsObj += `, cache: ${identity.cache}`;
  84477. }
  84478. if (identity == null ? void 0 : identity.cycle) {
  84479. paramsObj += `, cycle: true`;
  84480. }
  84481. paramsObj += " }";
  84482. if ((identity == null ? void 0 : identity.type) === "always") {
  84483. return `.generatedAlwaysAsIdentity(${paramsObj})`;
  84484. }
  84485. return `.generatedByDefaultAsIdentity(${paramsObj})`;
  84486. }
  84487. var import_drizzle_orm10, import_relations2, import_casing5, pgImportsList, timeConfig2, possibleIntervals, intervalStrToObj, intervalConfig, mapColumnDefault4, importsPatch2, relations4, escapeColumnKey4, withCasing3, dbColumnName4, paramNameFor2, schemaToTypeScript4, isCyclic4, isSelf4, buildArrayDefault2, mapDefault2, column9, dimensionsInArray2, createTableColumns4, createTableIndexes4, createTablePKs4, createTablePolicies2, createTableUniques4, createTableChecks4, createTableFKs4;
  84488. var init_introspect_pg = __esm({
  84489. "src/introspect-pg.ts"() {
  84490. "use strict";
  84491. import_drizzle_orm10 = require("drizzle-orm");
  84492. import_relations2 = require("drizzle-orm/relations");
  84493. init_utils();
  84494. import_casing5 = require("drizzle-orm/casing");
  84495. init_global();
  84496. init_pgSerializer();
  84497. init_utils2();
  84498. pgImportsList = /* @__PURE__ */ new Set([
  84499. "pgTable",
  84500. "pgEnum",
  84501. "smallint",
  84502. "integer",
  84503. "bigint",
  84504. "boolean",
  84505. "text",
  84506. "varchar",
  84507. "char",
  84508. "serial",
  84509. "smallserial",
  84510. "bigserial",
  84511. "decimal",
  84512. "numeric",
  84513. "real",
  84514. "json",
  84515. "jsonb",
  84516. "time",
  84517. "timestamp",
  84518. "date",
  84519. "interval",
  84520. "cidr",
  84521. "inet",
  84522. "macaddr",
  84523. "macaddr8",
  84524. "bigint",
  84525. "doublePrecision",
  84526. "uuid",
  84527. "vector",
  84528. "point",
  84529. "line",
  84530. "geometry"
  84531. ]);
  84532. timeConfig2 = (json) => {
  84533. json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
  84534. const keys = Object.keys(json);
  84535. if (keys.length === 0) return;
  84536. let statement = "{ ";
  84537. statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
  84538. statement += " }";
  84539. return statement;
  84540. };
  84541. possibleIntervals = [
  84542. "year",
  84543. "month",
  84544. "day",
  84545. "hour",
  84546. "minute",
  84547. "second",
  84548. "year to month",
  84549. "day to hour",
  84550. "day to minute",
  84551. "day to second",
  84552. "hour to minute",
  84553. "hour to second",
  84554. "minute to second"
  84555. ];
  84556. intervalStrToObj = (str) => {
  84557. if (str.startsWith("interval(")) {
  84558. return {
  84559. precision: Number(str.substring("interval(".length, str.length - 1))
  84560. };
  84561. }
  84562. const splitted = str.split(" ");
  84563. if (splitted.length === 1) {
  84564. return {};
  84565. }
  84566. const rest = splitted.slice(1, splitted.length).join(" ");
  84567. if (possibleIntervals.includes(rest)) {
  84568. return { fields: `"${rest}"` };
  84569. }
  84570. for (const s4 of possibleIntervals) {
  84571. if (rest.startsWith(`${s4}(`)) {
  84572. return {
  84573. fields: `"${s4}"`,
  84574. precision: Number(rest.substring(s4.length + 1, rest.length - 1))
  84575. };
  84576. }
  84577. }
  84578. return {};
  84579. };
  84580. intervalConfig = (str) => {
  84581. const json = intervalStrToObj(str);
  84582. const keys = Object.keys(json);
  84583. if (keys.length === 0) return;
  84584. let statement = "{ ";
  84585. statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
  84586. statement += " }";
  84587. return statement;
  84588. };
  84589. mapColumnDefault4 = (defaultValue, isExpression) => {
  84590. if (isExpression) {
  84591. return `sql\`${defaultValue}\``;
  84592. }
  84593. return defaultValue;
  84594. };
  84595. importsPatch2 = {
  84596. "double precision": "doublePrecision",
  84597. "timestamp without time zone": "timestamp",
  84598. "timestamp with time zone": "timestamp",
  84599. "time without time zone": "time",
  84600. "time with time zone": "time"
  84601. };
  84602. relations4 = /* @__PURE__ */ new Set();
  84603. escapeColumnKey4 = (value) => {
  84604. if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
  84605. return `"${value}"`;
  84606. }
  84607. return value;
  84608. };
  84609. withCasing3 = (value, casing2) => {
  84610. if (casing2 === "preserve") {
  84611. return escapeColumnKey4(value);
  84612. }
  84613. if (casing2 === "camel") {
  84614. return escapeColumnKey4(value.camelCase());
  84615. }
  84616. assertUnreachable(casing2);
  84617. };
  84618. dbColumnName4 = ({ name, casing: casing2, withMode = false }) => {
  84619. if (casing2 === "preserve") {
  84620. return "";
  84621. }
  84622. if (casing2 === "camel") {
  84623. return (0, import_casing5.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
  84624. }
  84625. assertUnreachable(casing2);
  84626. };
  84627. paramNameFor2 = (name, schema6) => {
  84628. const schemaSuffix = schema6 && schema6 !== "public" ? `In${schema6.capitalise()}` : "";
  84629. return `${name}${schemaSuffix}`;
  84630. };
  84631. schemaToTypeScript4 = (schema6, casing2) => {
  84632. Object.values(schema6.tables).forEach((table6) => {
  84633. Object.values(table6.foreignKeys).forEach((fk5) => {
  84634. const relation = `${fk5.tableFrom}-${fk5.tableTo}`;
  84635. relations4.add(relation);
  84636. });
  84637. });
  84638. const schemas = Object.fromEntries(
  84639. Object.entries(schema6.schemas).map((it) => {
  84640. return [it[0], withCasing3(it[1], casing2)];
  84641. })
  84642. );
  84643. const enumTypes = Object.values(schema6.enums).reduce((acc, cur) => {
  84644. acc.add(`${cur.schema}.${cur.name}`);
  84645. return acc;
  84646. }, /* @__PURE__ */ new Set());
  84647. const imports = Object.values(schema6.tables).reduce(
  84648. (res, it) => {
  84649. const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
  84650. const fkImpots = Object.values(it.foreignKeys).map((it2) => "foreignKey");
  84651. if (Object.values(it.foreignKeys).some((it2) => isCyclic4(it2) && !isSelf4(it2))) {
  84652. res.pg.push("type AnyPgColumn");
  84653. }
  84654. const pkImports = Object.values(it.compositePrimaryKeys).map((it2) => "primaryKey");
  84655. const uniqueImports = Object.values(it.uniqueConstraints).map((it2) => "unique");
  84656. const checkImports = Object.values(it.checkConstraints).map(
  84657. (it2) => "check"
  84658. );
  84659. const policiesImports = Object.values(it.policies).map(
  84660. (it2) => "pgPolicy"
  84661. );
  84662. if (it.schema && it.schema !== "public" && it.schema !== "") {
  84663. res.pg.push("pgSchema");
  84664. }
  84665. res.pg.push(...idxImports);
  84666. res.pg.push(...fkImpots);
  84667. res.pg.push(...pkImports);
  84668. res.pg.push(...uniqueImports);
  84669. res.pg.push(...policiesImports);
  84670. res.pg.push(...checkImports);
  84671. const columnImports = Object.values(it.columns).map((col) => {
  84672. let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
  84673. patched = patched === "double precision" ? "doublePrecision" : patched;
  84674. patched = patched.startsWith("varchar(") ? "varchar" : patched;
  84675. patched = patched.startsWith("char(") ? "char" : patched;
  84676. patched = patched.startsWith("numeric(") ? "numeric" : patched;
  84677. patched = patched.startsWith("time(") ? "time" : patched;
  84678. patched = patched.startsWith("timestamp(") ? "timestamp" : patched;
  84679. patched = patched.startsWith("vector(") ? "vector" : patched;
  84680. patched = patched.startsWith("geometry(") ? "geometry" : patched;
  84681. return patched;
  84682. }).filter((type) => {
  84683. return pgImportsList.has(type);
  84684. });
  84685. res.pg.push(...columnImports);
  84686. return res;
  84687. },
  84688. { pg: [] }
  84689. );
  84690. Object.values(schema6.views).forEach((it) => {
  84691. if (it.schema && it.schema !== "public" && it.schema !== "") {
  84692. imports.pg.push("pgSchema");
  84693. } else if (it.schema === "public") {
  84694. it.materialized ? imports.pg.push("pgMaterializedView") : imports.pg.push("pgView");
  84695. }
  84696. Object.values(it.columns).forEach(() => {
  84697. const columnImports = Object.values(it.columns).map((col) => {
  84698. let patched = (importsPatch2[col.type] || col.type).replace("[]", "");
  84699. patched = patched === "double precision" ? "doublePrecision" : patched;
  84700. patched = patched.startsWith("varchar(") ? "varchar" : patched;
  84701. patched = patched.startsWith("char(") ? "char" : patched;
  84702. patched = patched.startsWith("numeric(") ? "numeric" : patched;
  84703. patched = patched.startsWith("time(") ? "time" : patched;
  84704. patched = patched.startsWith("timestamp(") ? "timestamp" : patched;
  84705. patched = patched.startsWith("vector(") ? "vector" : patched;
  84706. patched = patched.startsWith("geometry(") ? "geometry" : patched;
  84707. return patched;
  84708. }).filter((type) => {
  84709. return pgImportsList.has(type);
  84710. });
  84711. imports.pg.push(...columnImports);
  84712. });
  84713. });
  84714. Object.values(schema6.sequences).forEach((it) => {
  84715. if (it.schema && it.schema !== "public" && it.schema !== "") {
  84716. imports.pg.push("pgSchema");
  84717. } else if (it.schema === "public") {
  84718. imports.pg.push("pgSequence");
  84719. }
  84720. });
  84721. Object.values(schema6.enums).forEach((it) => {
  84722. if (it.schema && it.schema !== "public" && it.schema !== "") {
  84723. imports.pg.push("pgSchema");
  84724. } else if (it.schema === "public") {
  84725. imports.pg.push("pgEnum");
  84726. }
  84727. });
  84728. if (Object.keys(schema6.roles).length > 0) {
  84729. imports.pg.push("pgRole");
  84730. }
  84731. const enumStatements = Object.values(schema6.enums).map((it) => {
  84732. const enumSchema4 = schemas[it.schema];
  84733. const paramName = paramNameFor2(it.name, enumSchema4);
  84734. const func = enumSchema4 ? `${enumSchema4}.enum` : "pgEnum";
  84735. const values = Object.values(it.values).map((it2) => `'${unescapeSingleQuotes(it2, false)}'`).join(", ");
  84736. return `export const ${withCasing3(paramName, casing2)} = ${func}("${it.name}", [${values}])
  84737. `;
  84738. }).join("").concat("\n");
  84739. const sequencesStatements = Object.values(schema6.sequences).map((it) => {
  84740. const seqSchema = schemas[it.schema];
  84741. const paramName = paramNameFor2(it.name, seqSchema);
  84742. const func = seqSchema ? `${seqSchema}.sequence` : "pgSequence";
  84743. let params = "";
  84744. if (it.startWith) {
  84745. params += `, startWith: "${it.startWith}"`;
  84746. }
  84747. if (it.increment) {
  84748. params += `, increment: "${it.increment}"`;
  84749. }
  84750. if (it.minValue) {
  84751. params += `, minValue: "${it.minValue}"`;
  84752. }
  84753. if (it.maxValue) {
  84754. params += `, maxValue: "${it.maxValue}"`;
  84755. }
  84756. if (it.cache) {
  84757. params += `, cache: "${it.cache}"`;
  84758. }
  84759. if (it.cycle) {
  84760. params += `, cycle: true`;
  84761. } else {
  84762. params += `, cycle: false`;
  84763. }
  84764. return `export const ${withCasing3(paramName, casing2)} = ${func}("${it.name}"${params ? `, { ${params.trimChar(",")} }` : ""})
  84765. `;
  84766. }).join("").concat("");
  84767. const schemaStatements = Object.entries(schemas).map((it) => {
  84768. return `export const ${it[1]} = pgSchema("${it[0]}");
  84769. `;
  84770. }).join("");
  84771. const rolesNameToTsKey = {};
  84772. const rolesStatements = Object.entries(schema6.roles).map((it) => {
  84773. const fields = it[1];
  84774. rolesNameToTsKey[fields.name] = it[0];
  84775. return `export const ${withCasing3(it[0], casing2)} = pgRole("${fields.name}", ${!fields.createDb && !fields.createRole && fields.inherit ? "" : `${`, { ${fields.createDb ? `createDb: true,` : ""}${fields.createRole ? ` createRole: true,` : ""}${!fields.inherit ? ` inherit: false ` : ""}`.trimChar(",")}}`} );
  84776. `;
  84777. }).join("");
  84778. const tableStatements = Object.values(schema6.tables).map((table6) => {
  84779. const tableSchema = schemas[table6.schema];
  84780. const paramName = paramNameFor2(table6.name, tableSchema);
  84781. const func = tableSchema ? `${tableSchema}.table` : "pgTable";
  84782. let statement = `export const ${withCasing3(paramName, casing2)} = ${func}("${table6.name}", {
  84783. `;
  84784. statement += createTableColumns4(
  84785. table6.name,
  84786. Object.values(table6.columns),
  84787. Object.values(table6.foreignKeys),
  84788. enumTypes,
  84789. schemas,
  84790. casing2,
  84791. schema6.internal
  84792. );
  84793. statement += "}";
  84794. if (Object.keys(table6.indexes).length > 0 || Object.values(table6.foreignKeys).length > 0 || Object.values(table6.policies).length > 0 || Object.keys(table6.compositePrimaryKeys).length > 0 || Object.keys(table6.uniqueConstraints).length > 0 || Object.keys(table6.checkConstraints).length > 0) {
  84795. statement += ", ";
  84796. statement += "(table) => [";
  84797. statement += createTableIndexes4(table6.name, Object.values(table6.indexes), casing2);
  84798. statement += createTableFKs4(Object.values(table6.foreignKeys), schemas, casing2);
  84799. statement += createTablePKs4(
  84800. Object.values(table6.compositePrimaryKeys),
  84801. casing2
  84802. );
  84803. statement += createTableUniques4(
  84804. Object.values(table6.uniqueConstraints),
  84805. casing2
  84806. );
  84807. statement += createTablePolicies2(
  84808. Object.values(table6.policies),
  84809. casing2,
  84810. rolesNameToTsKey
  84811. );
  84812. statement += createTableChecks4(
  84813. Object.values(table6.checkConstraints),
  84814. casing2
  84815. );
  84816. statement += "\n]";
  84817. }
  84818. statement += ");";
  84819. return statement;
  84820. });
  84821. const viewsStatements = Object.values(schema6.views).map((it) => {
  84822. const viewSchema = schemas[it.schema];
  84823. const paramName = paramNameFor2(it.name, viewSchema);
  84824. const func = viewSchema ? it.materialized ? `${viewSchema}.materializedView` : `${viewSchema}.view` : it.materialized ? "pgMaterializedView" : "pgView";
  84825. const withOption = it.with ?? "";
  84826. const as = `sql\`${it.definition}\``;
  84827. const tablespace = it.tablespace ?? "";
  84828. const columns = createTableColumns4(
  84829. "",
  84830. Object.values(it.columns),
  84831. [],
  84832. enumTypes,
  84833. schemas,
  84834. casing2,
  84835. schema6.internal
  84836. );
  84837. let statement = `export const ${withCasing3(paramName, casing2)} = ${func}("${it.name}", {${columns}})`;
  84838. statement += tablespace ? `.tablespace("${tablespace}")` : "";
  84839. statement += withOption ? `.with(${JSON.stringify(withOption)})` : "";
  84840. statement += `.as(${as});`;
  84841. return statement;
  84842. }).join("\n\n");
  84843. const uniquePgImports = ["pgTable", ...new Set(imports.pg)];
  84844. const importsTs = `import { ${uniquePgImports.join(
  84845. ", "
  84846. )} } from "drizzle-orm/pg-core"
  84847. import { sql } from "drizzle-orm"
  84848. `;
  84849. let decalrations = schemaStatements;
  84850. decalrations += rolesStatements;
  84851. decalrations += enumStatements;
  84852. decalrations += sequencesStatements;
  84853. decalrations += "\n";
  84854. decalrations += tableStatements.join("\n\n");
  84855. decalrations += "\n";
  84856. decalrations += viewsStatements;
  84857. const file = importsTs + decalrations;
  84858. const schemaEntry = `
  84859. {
  84860. ${Object.values(schema6.tables).map((it) => withCasing3(it.name, casing2)).join(",\n")}
  84861. }
  84862. `;
  84863. return { file, imports: importsTs, decalrations, schemaEntry };
  84864. };
  84865. isCyclic4 = (fk5) => {
  84866. const key = `${fk5.tableFrom}-${fk5.tableTo}`;
  84867. const reverse = `${fk5.tableTo}-${fk5.tableFrom}`;
  84868. return relations4.has(key) && relations4.has(reverse);
  84869. };
  84870. isSelf4 = (fk5) => {
  84871. return fk5.tableFrom === fk5.tableTo;
  84872. };
  84873. buildArrayDefault2 = (defaultValue, typeName) => {
  84874. if (typeof defaultValue === "string" && !(defaultValue.startsWith("{") || defaultValue.startsWith("'{"))) {
  84875. return `sql\`${defaultValue}\``;
  84876. }
  84877. defaultValue = defaultValue.substring(2, defaultValue.length - 2);
  84878. return `[${defaultValue.split(/\s*,\s*/g).map((value) => {
  84879. if (typeName === "json" || typeName === "jsonb") {
  84880. return value.substring(1, value.length - 1).replaceAll("\\", "");
  84881. }
  84882. return value;
  84883. }).join(", ")}]`;
  84884. };
  84885. mapDefault2 = (tableName, type, name, enumTypes, typeSchema, defaultValue, internals) => {
  84886. var _a2, _b, _c, _d;
  84887. const isExpression = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
  84888. const isArray = ((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[name]) == null ? void 0 : _d.isArray) ?? false;
  84889. const lowered = type.toLowerCase().replace("[]", "");
  84890. if (isArray) {
  84891. return typeof defaultValue !== "undefined" ? `.default(${buildArrayDefault2(defaultValue, lowered)})` : "";
  84892. }
  84893. if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
  84894. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
  84895. }
  84896. if (lowered.startsWith("integer")) {
  84897. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84898. }
  84899. if (lowered.startsWith("smallint")) {
  84900. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84901. }
  84902. if (lowered.startsWith("bigint")) {
  84903. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84904. }
  84905. if (lowered.startsWith("boolean")) {
  84906. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84907. }
  84908. if (lowered.startsWith("double precision")) {
  84909. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84910. }
  84911. if (lowered.startsWith("real")) {
  84912. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84913. }
  84914. if (lowered.startsWith("uuid")) {
  84915. return defaultValue === "gen_random_uuid()" ? ".defaultRandom()" : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
  84916. }
  84917. if (lowered.startsWith("numeric")) {
  84918. defaultValue = defaultValue ? defaultValue.startsWith(`'`) && defaultValue.endsWith(`'`) ? defaultValue.substring(1, defaultValue.length - 1) : defaultValue : void 0;
  84919. return defaultValue ? `.default('${mapColumnDefault4(defaultValue, isExpression)}')` : "";
  84920. }
  84921. if (lowered.startsWith("timestamp")) {
  84922. return defaultValue === "now()" ? ".defaultNow()" : /^'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(\.\d+)?([+-]\d{2}(:\d{2})?)?'$/.test(defaultValue) ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
  84923. }
  84924. if (lowered.startsWith("time")) {
  84925. return defaultValue === "now()" ? ".defaultNow()" : /^'\d{2}:\d{2}(:\d{2})?(\.\d+)?'$/.test(defaultValue) ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
  84926. }
  84927. if (lowered.startsWith("interval")) {
  84928. return defaultValue ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84929. }
  84930. if (lowered === "date") {
  84931. return defaultValue === "now()" ? ".defaultNow()" : /^'\d{4}-\d{2}-\d{2}'$/.test(defaultValue) ? `.default(${defaultValue})` : defaultValue ? `.default(sql\`${defaultValue}\`)` : "";
  84932. }
  84933. if (lowered.startsWith("text")) {
  84934. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
  84935. }
  84936. if (lowered.startsWith("jsonb")) {
  84937. const def = typeof defaultValue !== "undefined" ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
  84938. return defaultValue ? `.default(${def})` : "";
  84939. }
  84940. if (lowered.startsWith("json")) {
  84941. const def = defaultValue ? defaultValue.replace(/::(.*?)(?<![^\w"])(?=$)/, "").slice(1, -1) : null;
  84942. return typeof defaultValue !== "undefined" ? `.default(${def})` : "";
  84943. }
  84944. if (lowered.startsWith("inet")) {
  84945. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84946. }
  84947. if (lowered.startsWith("cidr")) {
  84948. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84949. }
  84950. if (lowered.startsWith("macaddr8")) {
  84951. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84952. }
  84953. if (lowered.startsWith("macaddr")) {
  84954. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84955. }
  84956. if (lowered.startsWith("varchar")) {
  84957. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
  84958. }
  84959. if (lowered.startsWith("point")) {
  84960. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84961. }
  84962. if (lowered.startsWith("line")) {
  84963. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84964. }
  84965. if (lowered.startsWith("geometry")) {
  84966. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84967. }
  84968. if (lowered.startsWith("vector")) {
  84969. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(defaultValue, isExpression)})` : "";
  84970. }
  84971. if (lowered.startsWith("char")) {
  84972. return typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault4(unescapeSingleQuotes(defaultValue, true), isExpression)})` : "";
  84973. }
  84974. return "";
  84975. };
  84976. column9 = (tableName, type, name, enumTypes, typeSchema, casing2, defaultValue, internals) => {
  84977. var _a2, _b;
  84978. const isExpression = ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[name]) == null ? void 0 : _b.isDefaultAnExpression) ?? false;
  84979. const lowered = type.toLowerCase().replace("[]", "");
  84980. if (enumTypes.has(`${typeSchema}.${type.replace("[]", "")}`)) {
  84981. let out = `${withCasing3(name, casing2)}: ${withCasing3(paramNameFor2(type.replace("[]", ""), typeSchema), casing2)}(${dbColumnName4({ name, casing: casing2 })})`;
  84982. return out;
  84983. }
  84984. if (lowered.startsWith("serial")) {
  84985. return `${withCasing3(name, casing2)}: serial(${dbColumnName4({ name, casing: casing2 })})`;
  84986. }
  84987. if (lowered.startsWith("smallserial")) {
  84988. return `${withCasing3(name, casing2)}: smallserial(${dbColumnName4({ name, casing: casing2 })})`;
  84989. }
  84990. if (lowered.startsWith("bigserial")) {
  84991. return `${withCasing3(name, casing2)}: bigserial(${dbColumnName4({ name, casing: casing2, withMode: true })}{ mode: "bigint" })`;
  84992. }
  84993. if (lowered.startsWith("integer")) {
  84994. let out = `${withCasing3(name, casing2)}: integer(${dbColumnName4({ name, casing: casing2 })})`;
  84995. return out;
  84996. }
  84997. if (lowered.startsWith("smallint")) {
  84998. let out = `${withCasing3(name, casing2)}: smallint(${dbColumnName4({ name, casing: casing2 })})`;
  84999. return out;
  85000. }
  85001. if (lowered.startsWith("bigint")) {
  85002. let out = `// You can use { mode: "bigint" } if numbers are exceeding js number limitations
  85003. `;
  85004. out += `${withCasing3(name, casing2)}: bigint(${dbColumnName4({ name, casing: casing2, withMode: true })}{ mode: "number" })`;
  85005. return out;
  85006. }
  85007. if (lowered.startsWith("boolean")) {
  85008. let out = `${withCasing3(name, casing2)}: boolean(${dbColumnName4({ name, casing: casing2 })})`;
  85009. return out;
  85010. }
  85011. if (lowered.startsWith("double precision")) {
  85012. let out = `${withCasing3(name, casing2)}: doublePrecision(${dbColumnName4({ name, casing: casing2 })})`;
  85013. return out;
  85014. }
  85015. if (lowered.startsWith("real")) {
  85016. let out = `${withCasing3(name, casing2)}: real(${dbColumnName4({ name, casing: casing2 })})`;
  85017. return out;
  85018. }
  85019. if (lowered.startsWith("uuid")) {
  85020. let out = `${withCasing3(name, casing2)}: uuid(${dbColumnName4({ name, casing: casing2 })})`;
  85021. return out;
  85022. }
  85023. if (lowered.startsWith("numeric")) {
  85024. let params;
  85025. if (lowered.length > 7) {
  85026. const [precision, scale] = lowered.slice(8, lowered.length - 1).split(",");
  85027. params = { precision, scale };
  85028. }
  85029. let out = params ? `${withCasing3(name, casing2)}: numeric(${dbColumnName4({ name, casing: casing2, withMode: true })}${timeConfig2(params)})` : `${withCasing3(name, casing2)}: numeric(${dbColumnName4({ name, casing: casing2 })})`;
  85030. return out;
  85031. }
  85032. if (lowered.startsWith("timestamp")) {
  85033. const withTimezone = lowered.includes("with time zone");
  85034. let precision = lowered.startsWith("timestamp(") ? Number(lowered.split(" ")[0].substring("timestamp(".length, lowered.split(" ")[0].length - 1)) : null;
  85035. precision = precision ? precision : null;
  85036. const params = timeConfig2({
  85037. precision,
  85038. withTimezone,
  85039. mode: "'string'"
  85040. });
  85041. let out = params ? `${withCasing3(name, casing2)}: timestamp(${dbColumnName4({ name, casing: casing2, withMode: true })}${params})` : `${withCasing3(name, casing2)}: timestamp(${dbColumnName4({ name, casing: casing2 })})`;
  85042. return out;
  85043. }
  85044. if (lowered.startsWith("time")) {
  85045. const withTimezone = lowered.includes("with time zone");
  85046. let precision = lowered.startsWith("time(") ? Number(lowered.split(" ")[0].substring("time(".length, lowered.split(" ")[0].length - 1)) : null;
  85047. precision = precision ? precision : null;
  85048. const params = timeConfig2({ precision, withTimezone });
  85049. let out = params ? `${withCasing3(name, casing2)}: time(${dbColumnName4({ name, casing: casing2, withMode: true })}${params})` : `${withCasing3(name, casing2)}: time(${dbColumnName4({ name, casing: casing2 })})`;
  85050. return out;
  85051. }
  85052. if (lowered.startsWith("interval")) {
  85053. const params = intervalConfig(lowered);
  85054. let out = params ? `${withCasing3(name, casing2)}: interval(${dbColumnName4({ name, casing: casing2, withMode: true })}${params})` : `${withCasing3(name, casing2)}: interval(${dbColumnName4({ name, casing: casing2 })})`;
  85055. return out;
  85056. }
  85057. if (lowered === "date") {
  85058. let out = `${withCasing3(name, casing2)}: date(${dbColumnName4({ name, casing: casing2 })})`;
  85059. return out;
  85060. }
  85061. if (lowered.startsWith("text")) {
  85062. let out = `${withCasing3(name, casing2)}: text(${dbColumnName4({ name, casing: casing2 })})`;
  85063. return out;
  85064. }
  85065. if (lowered.startsWith("jsonb")) {
  85066. let out = `${withCasing3(name, casing2)}: jsonb(${dbColumnName4({ name, casing: casing2 })})`;
  85067. return out;
  85068. }
  85069. if (lowered.startsWith("json")) {
  85070. let out = `${withCasing3(name, casing2)}: json(${dbColumnName4({ name, casing: casing2 })})`;
  85071. return out;
  85072. }
  85073. if (lowered.startsWith("inet")) {
  85074. let out = `${withCasing3(name, casing2)}: inet(${dbColumnName4({ name, casing: casing2 })})`;
  85075. return out;
  85076. }
  85077. if (lowered.startsWith("cidr")) {
  85078. let out = `${withCasing3(name, casing2)}: cidr(${dbColumnName4({ name, casing: casing2 })})`;
  85079. return out;
  85080. }
  85081. if (lowered.startsWith("macaddr8")) {
  85082. let out = `${withCasing3(name, casing2)}: macaddr8(${dbColumnName4({ name, casing: casing2 })})`;
  85083. return out;
  85084. }
  85085. if (lowered.startsWith("macaddr")) {
  85086. let out = `${withCasing3(name, casing2)}: macaddr(${dbColumnName4({ name, casing: casing2 })})`;
  85087. return out;
  85088. }
  85089. if (lowered.startsWith("varchar")) {
  85090. let out;
  85091. if (lowered.length !== 7) {
  85092. out = `${withCasing3(name, casing2)}: varchar(${dbColumnName4({ name, casing: casing2, withMode: true })}{ length: ${lowered.substring(8, lowered.length - 1)} })`;
  85093. } else {
  85094. out = `${withCasing3(name, casing2)}: varchar(${dbColumnName4({ name, casing: casing2 })})`;
  85095. }
  85096. return out;
  85097. }
  85098. if (lowered.startsWith("point")) {
  85099. let out = `${withCasing3(name, casing2)}: point(${dbColumnName4({ name, casing: casing2 })})`;
  85100. return out;
  85101. }
  85102. if (lowered.startsWith("line")) {
  85103. let out = `${withCasing3(name, casing2)}: point(${dbColumnName4({ name, casing: casing2 })})`;
  85104. return out;
  85105. }
  85106. if (lowered.startsWith("geometry")) {
  85107. let out = "";
  85108. let isGeoUnknown = false;
  85109. if (lowered.length !== 8) {
  85110. const geometryOptions = lowered.slice(9, -1).split(",");
  85111. if (geometryOptions.length === 1 && geometryOptions[0] !== "") {
  85112. out = `${withCasing3(name, casing2)}: geometry(${dbColumnName4({ name, casing: casing2, withMode: true })}{ type: "${geometryOptions[0]}" })`;
  85113. } else if (geometryOptions.length === 2) {
  85114. out = `${withCasing3(name, casing2)}: geometry(${dbColumnName4({ name, casing: casing2, withMode: true })}{ type: "${geometryOptions[0]}", srid: ${geometryOptions[1]} })`;
  85115. } else {
  85116. isGeoUnknown = true;
  85117. }
  85118. } else {
  85119. out = `${withCasing3(name, casing2)}: geometry(${dbColumnName4({ name, casing: casing2 })})`;
  85120. }
  85121. if (isGeoUnknown) {
  85122. let unknown2 = `// TODO: failed to parse geometry type because found more than 2 options inside geometry function '${type}'
  85123. // Introspect is currently supporting only type and srid options
  85124. `;
  85125. unknown2 += ` ${withCasing3(name, casing2)}: unknown("${name}")`;
  85126. return unknown2;
  85127. }
  85128. return out;
  85129. }
  85130. if (lowered.startsWith("vector")) {
  85131. let out;
  85132. if (lowered.length !== 6) {
  85133. out = `${withCasing3(name, casing2)}: vector(${dbColumnName4({ name, casing: casing2, withMode: true })}{ dimensions: ${lowered.substring(7, lowered.length - 1)} })`;
  85134. } else {
  85135. out = `${withCasing3(name, casing2)}: vector(${dbColumnName4({ name, casing: casing2 })})`;
  85136. }
  85137. return out;
  85138. }
  85139. if (lowered.startsWith("char")) {
  85140. let out;
  85141. if (lowered.length !== 4) {
  85142. out = `${withCasing3(name, casing2)}: char(${dbColumnName4({ name, casing: casing2, withMode: true })}{ length: ${lowered.substring(5, lowered.length - 1)} })`;
  85143. } else {
  85144. out = `${withCasing3(name, casing2)}: char(${dbColumnName4({ name, casing: casing2 })})`;
  85145. }
  85146. return out;
  85147. }
  85148. let unknown = `// TODO: failed to parse database type '${type}'
  85149. `;
  85150. unknown += ` ${withCasing3(name, casing2)}: unknown("${name}")`;
  85151. return unknown;
  85152. };
  85153. dimensionsInArray2 = (size) => {
  85154. let res = "";
  85155. if (typeof size === "undefined") return res;
  85156. for (let i4 = 0; i4 < size; i4++) {
  85157. res += ".array()";
  85158. }
  85159. return res;
  85160. };
  85161. createTableColumns4 = (tableName, columns, fks, enumTypes, schemas, casing2, internals) => {
  85162. let statement = "";
  85163. const oneColumnsFKs = Object.values(fks).filter((it) => {
  85164. return !isSelf4(it);
  85165. }).filter((it) => it.columnsFrom.length === 1);
  85166. const fkByColumnName = oneColumnsFKs.reduce((res, it) => {
  85167. const arr = res[it.columnsFrom[0]] || [];
  85168. arr.push(it);
  85169. res[it.columnsFrom[0]] = arr;
  85170. return res;
  85171. }, {});
  85172. columns.forEach((it) => {
  85173. var _a2, _b, _c, _d;
  85174. const columnStatement = column9(
  85175. tableName,
  85176. it.type,
  85177. it.name,
  85178. enumTypes,
  85179. it.typeSchema ?? "public",
  85180. casing2,
  85181. it.default,
  85182. internals
  85183. );
  85184. statement += " ";
  85185. statement += columnStatement;
  85186. if ((_b = (_a2 = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _a2.columns[it.name]) == null ? void 0 : _b.isArray) {
  85187. statement += dimensionsInArray2((_d = (_c = internals == null ? void 0 : internals.tables[tableName]) == null ? void 0 : _c.columns[it.name]) == null ? void 0 : _d.dimensions);
  85188. }
  85189. statement += mapDefault2(tableName, it.type, it.name, enumTypes, it.typeSchema ?? "public", it.default, internals);
  85190. statement += it.primaryKey ? ".primaryKey()" : "";
  85191. statement += it.notNull && !it.identity ? ".notNull()" : "";
  85192. statement += it.identity ? generateIdentityParams2(it.identity) : "";
  85193. statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as}\`)` : "";
  85194. statement += ",\n";
  85195. });
  85196. return statement;
  85197. };
  85198. createTableIndexes4 = (tableName, idxs, casing2) => {
  85199. let statement = "";
  85200. idxs.forEach((it) => {
  85201. let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
  85202. idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
  85203. idxKey = withCasing3(idxKey, casing2);
  85204. const indexGeneratedName = indexName2(
  85205. tableName,
  85206. it.columns.map((it2) => it2.expression)
  85207. );
  85208. const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
  85209. statement += `
  85210. `;
  85211. statement += it.isUnique ? "uniqueIndex(" : "index(";
  85212. statement += `${escapedIndexName})`;
  85213. statement += `${it.concurrently ? `.concurrently()` : ""}`;
  85214. statement += `.using("${it.method}", ${it.columns.map((it2) => {
  85215. if (it2.isExpression) {
  85216. return `sql\`${it2.expression}\``;
  85217. } else {
  85218. return `table.${withCasing3(it2.expression, casing2)}${it2.asc ? ".asc()" : ".desc()"}${it2.nulls === "first" ? ".nullsFirst()" : ".nullsLast()"}${it2.opclass ? `.op("${it2.opclass}")` : ""}`;
  85219. }
  85220. }).join(", ")})`;
  85221. statement += it.where ? `.where(sql\`${it.where}\`)` : "";
  85222. function reverseLogic(mappedWith) {
  85223. let reversedString = "{";
  85224. for (const key in mappedWith) {
  85225. if (mappedWith.hasOwnProperty(key)) {
  85226. reversedString += `${key}: "${mappedWith[key]}",`;
  85227. }
  85228. }
  85229. reversedString = reversedString.length > 1 ? reversedString.slice(0, reversedString.length - 1) : reversedString;
  85230. return `${reversedString}}`;
  85231. }
  85232. statement += it.with && Object.keys(it.with).length > 0 ? `.with(${reverseLogic(it.with)})` : "";
  85233. statement += `,`;
  85234. });
  85235. return statement;
  85236. };
  85237. createTablePKs4 = (pks, casing2) => {
  85238. let statement = "";
  85239. pks.forEach((it) => {
  85240. statement += `
  85241. `;
  85242. statement += "primaryKey({ columns: [";
  85243. statement += `${it.columns.map((c3) => {
  85244. return `table.${withCasing3(c3, casing2)}`;
  85245. }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
  85246. statement += ")";
  85247. statement += `,`;
  85248. });
  85249. return statement;
  85250. };
  85251. createTablePolicies2 = (policies, casing2, rolesNameToTsKey = {}) => {
  85252. let statement = "";
  85253. policies.forEach((it) => {
  85254. var _a2, _b, _c;
  85255. const idxKey = withCasing3(it.name, casing2);
  85256. const mappedItTo = (_a2 = it.to) == null ? void 0 : _a2.map((v6) => {
  85257. return rolesNameToTsKey[v6] ? withCasing3(rolesNameToTsKey[v6], casing2) : `"${v6}"`;
  85258. });
  85259. statement += `
  85260. `;
  85261. statement += "pgPolicy(";
  85262. statement += `"${it.name}", { `;
  85263. statement += `as: "${(_b = it.as) == null ? void 0 : _b.toLowerCase()}", for: "${(_c = it.for) == null ? void 0 : _c.toLowerCase()}", to: [${mappedItTo == null ? void 0 : mappedItTo.join(", ")}]${it.using ? `, using: sql\`${it.using}\`` : ""}${it.withCheck ? `, withCheck: sql\`${it.withCheck}\` ` : ""}`;
  85264. statement += ` }),`;
  85265. });
  85266. return statement;
  85267. };
  85268. createTableUniques4 = (unqs, casing2) => {
  85269. let statement = "";
  85270. unqs.forEach((it) => {
  85271. statement += `
  85272. `;
  85273. statement += "unique(";
  85274. statement += `"${it.name}")`;
  85275. statement += `.on(${it.columns.map((it2) => `table.${withCasing3(it2, casing2)}`).join(", ")})`;
  85276. statement += it.nullsNotDistinct ? `.nullsNotDistinct()` : "";
  85277. statement += `,`;
  85278. });
  85279. return statement;
  85280. };
  85281. createTableChecks4 = (checkConstraints, casing2) => {
  85282. let statement = "";
  85283. checkConstraints.forEach((it) => {
  85284. statement += `
  85285. `;
  85286. statement += "check(";
  85287. statement += `"${it.name}", `;
  85288. statement += `sql\`${it.value}\`)`;
  85289. statement += `,`;
  85290. });
  85291. return statement;
  85292. };
  85293. createTableFKs4 = (fks, schemas, casing2) => {
  85294. let statement = "";
  85295. fks.forEach((it) => {
  85296. const tableSchema = schemas[it.schemaTo || ""];
  85297. const paramName = paramNameFor2(it.tableTo, tableSchema);
  85298. const isSelf5 = it.tableTo === it.tableFrom;
  85299. const tableTo = isSelf5 ? "table" : `${withCasing3(paramName, casing2)}`;
  85300. statement += `
  85301. `;
  85302. statement += `foreignKey({
  85303. `;
  85304. statement += ` columns: [${it.columnsFrom.map((i4) => `table.${withCasing3(i4, casing2)}`).join(", ")}],
  85305. `;
  85306. statement += ` foreignColumns: [${it.columnsTo.map((i4) => `${tableTo}.${withCasing3(i4, casing2)}`).join(", ")}],
  85307. `;
  85308. statement += ` name: "${it.name}"
  85309. `;
  85310. statement += ` })`;
  85311. statement += it.onUpdate && it.onUpdate !== "no action" ? `.onUpdate("${it.onUpdate}")` : "";
  85312. statement += it.onDelete && it.onDelete !== "no action" ? `.onDelete("${it.onDelete}")` : "";
  85313. statement += `,`;
  85314. });
  85315. return statement;
  85316. };
  85317. }
  85318. });
  85319. // src/introspect-singlestore.ts
  85320. var import_casing6, singlestoreImportsList, timeConfig3, binaryConfig2, importsPatch3, escapeColumnKey5, prepareCasing2, dbColumnName5, schemaToTypeScript5, mapColumnDefault5, mapColumnDefaultForJson2, column10, createTableColumns5, createTableIndexes5, createTableUniques5, createTablePKs5;
  85321. var init_introspect_singlestore = __esm({
  85322. "src/introspect-singlestore.ts"() {
  85323. "use strict";
  85324. import_casing6 = require("drizzle-orm/casing");
  85325. init_utils();
  85326. init_global();
  85327. init_singlestoreSerializer();
  85328. singlestoreImportsList = /* @__PURE__ */ new Set([
  85329. "singlestoreTable",
  85330. "singlestoreEnum",
  85331. "bigint",
  85332. "binary",
  85333. "boolean",
  85334. "char",
  85335. "date",
  85336. "datetime",
  85337. "decimal",
  85338. "double",
  85339. "float",
  85340. "int",
  85341. "json",
  85342. // TODO: add new type BSON
  85343. // TODO: add new type Blob
  85344. // TODO: add new type UUID
  85345. // TODO: add new type GUID
  85346. // TODO: add new type Vector
  85347. // TODO: add new type GeoPoint
  85348. "mediumint",
  85349. "real",
  85350. "serial",
  85351. "smallint",
  85352. "text",
  85353. "tinytext",
  85354. "mediumtext",
  85355. "longtext",
  85356. "time",
  85357. "timestamp",
  85358. "tinyint",
  85359. "varbinary",
  85360. "varchar",
  85361. "vector",
  85362. "year",
  85363. "enum"
  85364. ]);
  85365. timeConfig3 = (json) => {
  85366. json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
  85367. const keys = Object.keys(json);
  85368. if (keys.length === 0) return;
  85369. let statement = "{ ";
  85370. statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
  85371. statement += " }";
  85372. return statement;
  85373. };
  85374. binaryConfig2 = (json) => {
  85375. json = Object.fromEntries(Object.entries(json).filter((it) => it[1]));
  85376. const keys = Object.keys(json);
  85377. if (keys.length === 0) return;
  85378. let statement = "{ ";
  85379. statement += keys.map((it) => `${it}: ${json[it]}`).join(", ");
  85380. statement += " }";
  85381. return statement;
  85382. };
  85383. importsPatch3 = {
  85384. "double precision": "doublePrecision",
  85385. "timestamp without time zone": "timestamp"
  85386. };
  85387. escapeColumnKey5 = (value) => {
  85388. if (/^(?![a-zA-Z_$][a-zA-Z0-9_$]*$).+$/.test(value)) {
  85389. return `"${value}"`;
  85390. }
  85391. return value;
  85392. };
  85393. prepareCasing2 = (casing2) => (value) => {
  85394. if (casing2 === "preserve") {
  85395. return escapeColumnKey5(value);
  85396. }
  85397. if (casing2 === "camel") {
  85398. return escapeColumnKey5(value.camelCase());
  85399. }
  85400. assertUnreachable(casing2);
  85401. };
  85402. dbColumnName5 = ({ name, casing: casing2, withMode = false }) => {
  85403. if (casing2 === "preserve") {
  85404. return "";
  85405. }
  85406. if (casing2 === "camel") {
  85407. return (0, import_casing6.toCamelCase)(name) === name ? "" : withMode ? `"${name}", ` : `"${name}"`;
  85408. }
  85409. assertUnreachable(casing2);
  85410. };
  85411. schemaToTypeScript5 = (schema6, casing2) => {
  85412. const withCasing5 = prepareCasing2(casing2);
  85413. const imports = Object.values(schema6.tables).reduce(
  85414. (res, it) => {
  85415. const idxImports = Object.values(it.indexes).map((idx) => idx.isUnique ? "uniqueIndex" : "index");
  85416. const pkImports = Object.values(it.compositePrimaryKeys).map(
  85417. (it2) => "primaryKey"
  85418. );
  85419. const uniqueImports = Object.values(it.uniqueConstraints).map(
  85420. (it2) => "unique"
  85421. );
  85422. res.singlestore.push(...idxImports);
  85423. res.singlestore.push(...pkImports);
  85424. res.singlestore.push(...uniqueImports);
  85425. const columnImports = Object.values(it.columns).map((col) => {
  85426. let patched = importsPatch3[col.type] ?? col.type;
  85427. patched = patched.startsWith("varchar(") ? "varchar" : patched;
  85428. patched = patched.startsWith("char(") ? "char" : patched;
  85429. patched = patched.startsWith("binary(") ? "binary" : patched;
  85430. patched = patched.startsWith("decimal(") ? "decimal" : patched;
  85431. patched = patched.startsWith("smallint(") ? "smallint" : patched;
  85432. patched = patched.startsWith("enum(") ? "singlestoreEnum" : patched;
  85433. patched = patched.startsWith("datetime(") ? "datetime" : patched;
  85434. patched = patched.startsWith("varbinary(") ? "varbinary" : patched;
  85435. patched = patched.startsWith("int(") ? "int" : patched;
  85436. patched = patched.startsWith("double(") ? "double" : patched;
  85437. patched = patched.startsWith("float(") ? "float" : patched;
  85438. patched = patched.startsWith("int unsigned") ? "int" : patched;
  85439. patched = patched.startsWith("tinyint(") ? "tinyint" : patched;
  85440. patched = patched.startsWith("mediumint(") ? "mediumint" : patched;
  85441. patched = patched.startsWith("bigint(") ? "bigint" : patched;
  85442. patched = patched.startsWith("tinyint unsigned") ? "tinyint" : patched;
  85443. patched = patched.startsWith("smallint unsigned") ? "smallint" : patched;
  85444. patched = patched.startsWith("mediumint unsigned") ? "mediumint" : patched;
  85445. patched = patched.startsWith("bigint unsigned") ? "bigint" : patched;
  85446. return patched;
  85447. }).filter((type) => {
  85448. return singlestoreImportsList.has(type);
  85449. });
  85450. res.singlestore.push(...columnImports);
  85451. return res;
  85452. },
  85453. { singlestore: [] }
  85454. );
  85455. const tableStatements = Object.values(schema6.tables).map((table6) => {
  85456. const func = "singlestoreTable";
  85457. let statement = "";
  85458. if (imports.singlestore.includes(withCasing5(table6.name))) {
  85459. statement = `// Table name is in conflict with ${withCasing5(
  85460. table6.name
  85461. )} import.
  85462. // Please change to any other name, that is not in imports list
  85463. `;
  85464. }
  85465. statement += `export const ${withCasing5(table6.name)} = ${func}("${table6.name}", {
  85466. `;
  85467. statement += createTableColumns5(
  85468. Object.values(table6.columns),
  85469. withCasing5,
  85470. casing2,
  85471. table6.name,
  85472. schema6
  85473. );
  85474. statement += "}";
  85475. if (Object.keys(table6.indexes).length > 0 || Object.keys(table6.compositePrimaryKeys).length > 0 || Object.keys(table6.uniqueConstraints).length > 0) {
  85476. statement += ",\n";
  85477. statement += "(table) => [";
  85478. statement += createTableIndexes5(
  85479. table6.name,
  85480. Object.values(table6.indexes),
  85481. withCasing5
  85482. );
  85483. statement += createTablePKs5(
  85484. Object.values(table6.compositePrimaryKeys),
  85485. withCasing5
  85486. );
  85487. statement += createTableUniques5(
  85488. Object.values(table6.uniqueConstraints),
  85489. withCasing5
  85490. );
  85491. statement += "\n]";
  85492. }
  85493. statement += ");";
  85494. return statement;
  85495. });
  85496. const uniqueSingleStoreImports = [
  85497. "singlestoreTable",
  85498. "singlestoreSchema",
  85499. "AnySingleStoreColumn",
  85500. ...new Set(imports.singlestore)
  85501. ];
  85502. const importsTs = `import { ${uniqueSingleStoreImports.join(
  85503. ", "
  85504. )} } from "drizzle-orm/singlestore-core"
  85505. import { sql } from "drizzle-orm"
  85506. `;
  85507. let decalrations = "";
  85508. decalrations += tableStatements.join("\n\n");
  85509. decalrations += "\n";
  85510. const file = importsTs + decalrations;
  85511. const schemaEntry = `
  85512. {
  85513. ${Object.values(schema6.tables).map((it) => withCasing5(it.name)).join(",")}
  85514. }
  85515. `;
  85516. return {
  85517. file,
  85518. // backward compatible, print to file
  85519. imports: importsTs,
  85520. decalrations,
  85521. schemaEntry
  85522. };
  85523. };
  85524. mapColumnDefault5 = (defaultValue, isExpression) => {
  85525. if (isExpression) {
  85526. return `sql\`${defaultValue}\``;
  85527. }
  85528. return defaultValue;
  85529. };
  85530. mapColumnDefaultForJson2 = (defaultValue) => {
  85531. if (typeof defaultValue === "string" && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
  85532. return defaultValue.substring(2, defaultValue.length - 2);
  85533. }
  85534. return defaultValue;
  85535. };
  85536. column10 = (type, name, casing2, rawCasing, defaultValue, autoincrement, onUpdate, isExpression) => {
  85537. let lowered = type;
  85538. if (!type.startsWith("enum(")) {
  85539. lowered = type.toLowerCase();
  85540. }
  85541. if (lowered === "serial") {
  85542. return `${casing2(name)}: serial(${dbColumnName5({ name, casing: rawCasing })})`;
  85543. }
  85544. if (lowered.startsWith("int")) {
  85545. const isUnsigned = lowered.includes("unsigned");
  85546. const columnName = dbColumnName5({ name, casing: rawCasing, withMode: isUnsigned });
  85547. let out = `${casing2(name)}: int(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
  85548. out += autoincrement ? `.autoincrement()` : "";
  85549. out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85550. return out;
  85551. }
  85552. if (lowered.startsWith("tinyint")) {
  85553. const isUnsigned = lowered.includes("unsigned");
  85554. const columnName = dbColumnName5({ name, casing: rawCasing, withMode: isUnsigned });
  85555. let out = `${casing2(name)}: tinyint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
  85556. out += autoincrement ? `.autoincrement()` : "";
  85557. out += typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85558. return out;
  85559. }
  85560. if (lowered.startsWith("smallint")) {
  85561. const isUnsigned = lowered.includes("unsigned");
  85562. const columnName = dbColumnName5({ name, casing: rawCasing, withMode: isUnsigned });
  85563. let out = `${casing2(name)}: smallint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
  85564. out += autoincrement ? `.autoincrement()` : "";
  85565. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85566. return out;
  85567. }
  85568. if (lowered.startsWith("mediumint")) {
  85569. const isUnsigned = lowered.includes("unsigned");
  85570. const columnName = dbColumnName5({ name, casing: rawCasing, withMode: isUnsigned });
  85571. let out = `${casing2(name)}: mediumint(${columnName}${isUnsigned ? "{ unsigned: true }" : ""})`;
  85572. out += autoincrement ? `.autoincrement()` : "";
  85573. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85574. return out;
  85575. }
  85576. if (lowered.startsWith("bigint")) {
  85577. const isUnsigned = lowered.includes("unsigned");
  85578. let out = `${casing2(name)}: bigint(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ mode: "number"${isUnsigned ? ", unsigned: true" : ""} })`;
  85579. out += autoincrement ? `.autoincrement()` : "";
  85580. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85581. return out;
  85582. }
  85583. if (lowered === "boolean") {
  85584. let out = `${casing2(name)}: boolean(${dbColumnName5({ name, casing: rawCasing })})`;
  85585. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85586. return out;
  85587. }
  85588. if (lowered.startsWith("double")) {
  85589. let params;
  85590. if (lowered.length > (lowered.includes("unsigned") ? 15 : 6)) {
  85591. const [precision, scale] = lowered.slice(7, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
  85592. params = { precision, scale };
  85593. }
  85594. if (lowered.includes("unsigned")) {
  85595. params = { ...params ?? {}, unsigned: true };
  85596. }
  85597. const timeConfigParams = params ? timeConfig3(params) : void 0;
  85598. let out = params ? `${casing2(name)}: double(${dbColumnName5({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfig3(params)})` : `${casing2(name)}: double(${dbColumnName5({ name, casing: rawCasing })})`;
  85599. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85600. return out;
  85601. }
  85602. if (lowered.startsWith("float")) {
  85603. let params;
  85604. if (lowered.length > (lowered.includes("unsigned") ? 14 : 5)) {
  85605. const [precision, scale] = lowered.slice(6, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
  85606. params = { precision, scale };
  85607. }
  85608. if (lowered.includes("unsigned")) {
  85609. params = { ...params ?? {}, unsigned: true };
  85610. }
  85611. let out = `${casing2(name)}: float(${dbColumnName5({ name, casing: rawCasing })}${params ? timeConfig3(params) : ""})`;
  85612. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85613. return out;
  85614. }
  85615. if (lowered === "real") {
  85616. let out = `${casing2(name)}: real(${dbColumnName5({ name, casing: rawCasing })})`;
  85617. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85618. return out;
  85619. }
  85620. if (lowered.startsWith("timestamp")) {
  85621. const keyLength = "timestamp".length + 1;
  85622. let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
  85623. fsp = fsp ? fsp : null;
  85624. const params = timeConfig3({ fsp, mode: "'string'" });
  85625. let out = params ? `${casing2(name)}: timestamp(${dbColumnName5({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: timestamp(${dbColumnName5({ name, casing: rawCasing })})`;
  85626. defaultValue = defaultValue === "now()" || defaultValue === "CURRENT_TIMESTAMP" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85627. out += defaultValue;
  85628. let onUpdateNow = onUpdate ? ".onUpdateNow()" : "";
  85629. out += onUpdateNow;
  85630. return out;
  85631. }
  85632. if (lowered.startsWith("time")) {
  85633. const keyLength = "time".length + 1;
  85634. let fsp = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
  85635. fsp = fsp ? fsp : null;
  85636. const params = timeConfig3({ fsp });
  85637. let out = params ? `${casing2(name)}: time(${dbColumnName5({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: time(${dbColumnName5({ name, casing: rawCasing })})`;
  85638. defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85639. out += defaultValue;
  85640. return out;
  85641. }
  85642. if (lowered === "date") {
  85643. let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
  85644. ${casing2(
  85645. name
  85646. )}: date(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ mode: 'string' })`;
  85647. defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85648. out += defaultValue;
  85649. return out;
  85650. }
  85651. if (lowered === "text") {
  85652. let out = `${casing2(name)}: text(${dbColumnName5({ name, casing: rawCasing })})`;
  85653. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85654. return out;
  85655. }
  85656. if (lowered === "tinytext") {
  85657. let out = `${casing2(name)}: tinytext(${dbColumnName5({ name, casing: rawCasing })})`;
  85658. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85659. return out;
  85660. }
  85661. if (lowered === "mediumtext") {
  85662. let out = `${casing2(name)}: mediumtext(${dbColumnName5({ name, casing: rawCasing })})`;
  85663. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85664. return out;
  85665. }
  85666. if (lowered === "longtext") {
  85667. let out = `${casing2(name)}: longtext(${dbColumnName5({ name, casing: rawCasing })})`;
  85668. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85669. return out;
  85670. }
  85671. if (lowered === "year") {
  85672. let out = `${casing2(name)}: year(${dbColumnName5({ name, casing: rawCasing })})`;
  85673. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85674. return out;
  85675. }
  85676. if (lowered === "json") {
  85677. let out = `${casing2(name)}: json(${dbColumnName5({ name, casing: rawCasing })})`;
  85678. out += defaultValue ? `.default(${mapColumnDefaultForJson2(defaultValue)})` : "";
  85679. return out;
  85680. }
  85681. if (lowered.startsWith("varchar")) {
  85682. let out = `${casing2(
  85683. name
  85684. )}: varchar(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
  85685. "varchar".length + 1,
  85686. lowered.length - 1
  85687. )} })`;
  85688. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85689. return out;
  85690. }
  85691. if (lowered.startsWith("char")) {
  85692. let out = `${casing2(
  85693. name
  85694. )}: char(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ length: ${lowered.substring(
  85695. "char".length + 1,
  85696. lowered.length - 1
  85697. )} })`;
  85698. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85699. return out;
  85700. }
  85701. if (lowered.startsWith("datetime")) {
  85702. let out = `// you can use { mode: 'date' }, if you want to have Date as type for this column
  85703. `;
  85704. const fsp = lowered.startsWith("datetime(") ? lowered.substring("datetime".length + 1, lowered.length - 1) : void 0;
  85705. out = fsp ? `${casing2(
  85706. name
  85707. )}: datetime(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ mode: 'string', fsp: ${lowered.substring(
  85708. "datetime".length + 1,
  85709. lowered.length - 1
  85710. )} })` : `${casing2(name)}: datetime(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ mode: 'string'})`;
  85711. defaultValue = defaultValue === "now()" ? ".defaultNow()" : defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85712. out += defaultValue;
  85713. return out;
  85714. }
  85715. if (lowered.startsWith("decimal")) {
  85716. let params;
  85717. if (lowered.length > (lowered.includes("unsigned") ? 16 : 7)) {
  85718. const [precision, scale] = lowered.slice(8, lowered.length - (1 + (lowered.includes("unsigned") ? 9 : 0))).split(",");
  85719. params = { precision, scale };
  85720. }
  85721. if (lowered.includes("unsigned")) {
  85722. params = { ...params ?? {}, unsigned: true };
  85723. }
  85724. const timeConfigParams = params ? timeConfig3(params) : void 0;
  85725. let out = params ? `${casing2(name)}: decimal(${dbColumnName5({ name, casing: rawCasing, withMode: timeConfigParams !== void 0 })}${timeConfigParams})` : `${casing2(name)}: decimal(${dbColumnName5({ name, casing: rawCasing })})`;
  85726. defaultValue = typeof defaultValue !== "undefined" ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85727. out += defaultValue;
  85728. return out;
  85729. }
  85730. if (lowered.startsWith("binary")) {
  85731. const keyLength = "binary".length + 1;
  85732. let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
  85733. length = length ? length : null;
  85734. const params = binaryConfig2({ length });
  85735. let out = params ? `${casing2(name)}: binary(${dbColumnName5({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: binary(${dbColumnName5({ name, casing: rawCasing })})`;
  85736. defaultValue = defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85737. out += defaultValue;
  85738. return out;
  85739. }
  85740. if (lowered.startsWith("enum")) {
  85741. const values = lowered.substring("enum".length + 1, lowered.length - 1);
  85742. let out = `${casing2(name)}: singlestoreEnum(${dbColumnName5({ name, casing: rawCasing, withMode: true })}[${values}])`;
  85743. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85744. return out;
  85745. }
  85746. if (lowered.startsWith("varbinary")) {
  85747. const keyLength = "varbinary".length + 1;
  85748. let length = lowered.length > keyLength ? Number(lowered.substring(keyLength, lowered.length - 1)) : null;
  85749. length = length ? length : null;
  85750. const params = binaryConfig2({ length });
  85751. let out = params ? `${casing2(name)}: varbinary(${dbColumnName5({ name, casing: rawCasing, withMode: params !== void 0 })}${params})` : `${casing2(name)}: varbinary(${dbColumnName5({ name, casing: rawCasing })})`;
  85752. defaultValue = defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85753. out += defaultValue;
  85754. return out;
  85755. }
  85756. if (lowered.startsWith("vector")) {
  85757. const [dimensions, elementType] = lowered.substring("vector".length + 1, lowered.length - 1).split(",");
  85758. let out = `${casing2(name)}: vector(${dbColumnName5({ name, casing: rawCasing, withMode: true })}{ dimensions: ${dimensions}, elementType: ${elementType} })`;
  85759. out += defaultValue ? `.default(${mapColumnDefault5(defaultValue, isExpression)})` : "";
  85760. return out;
  85761. }
  85762. console.log("uknown", type);
  85763. return `// Warning: Can't parse ${type} from database
  85764. // ${type}Type: ${type}("${name}")`;
  85765. };
  85766. createTableColumns5 = (columns, casing2, rawCasing, tableName, schema6) => {
  85767. let statement = "";
  85768. columns.forEach((it) => {
  85769. var _a2, _b, _c;
  85770. statement += " ";
  85771. statement += column10(
  85772. it.type,
  85773. it.name,
  85774. casing2,
  85775. rawCasing,
  85776. it.default,
  85777. it.autoincrement,
  85778. it.onUpdate,
  85779. ((_c = (_b = (_a2 = schema6.internal) == null ? void 0 : _a2.tables[tableName]) == null ? void 0 : _b.columns[it.name]) == null ? void 0 : _c.isDefaultAnExpression) ?? false
  85780. );
  85781. statement += it.primaryKey ? ".primaryKey()" : "";
  85782. statement += it.notNull ? ".notNull()" : "";
  85783. statement += it.generated ? `.generatedAlwaysAs(sql\`${it.generated.as.replace(
  85784. /`/g,
  85785. "\\`"
  85786. )}\`, { mode: "${it.generated.type}" })` : "";
  85787. statement += ",\n";
  85788. });
  85789. return statement;
  85790. };
  85791. createTableIndexes5 = (tableName, idxs, casing2) => {
  85792. let statement = "";
  85793. idxs.forEach((it) => {
  85794. let idxKey = it.name.startsWith(tableName) && it.name !== tableName ? it.name.slice(tableName.length + 1) : it.name;
  85795. idxKey = idxKey.endsWith("_index") ? idxKey.slice(0, -"_index".length) + "_idx" : idxKey;
  85796. idxKey = casing2(idxKey);
  85797. const indexGeneratedName = indexName3(tableName, it.columns);
  85798. const escapedIndexName = indexGeneratedName === it.name ? "" : `"${it.name}"`;
  85799. statement += `
  85800. `;
  85801. statement += it.isUnique ? "uniqueIndex(" : "index(";
  85802. statement += `${escapedIndexName})`;
  85803. statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
  85804. });
  85805. return statement;
  85806. };
  85807. createTableUniques5 = (unqs, casing2) => {
  85808. let statement = "";
  85809. unqs.forEach((it) => {
  85810. statement += `
  85811. `;
  85812. statement += "unique(";
  85813. statement += `"${it.name}")`;
  85814. statement += `.on(${it.columns.map((it2) => `table.${casing2(it2)}`).join(", ")}),`;
  85815. });
  85816. return statement;
  85817. };
  85818. createTablePKs5 = (pks, casing2) => {
  85819. let statement = "";
  85820. pks.forEach((it) => {
  85821. let idxKey = casing2(it.name);
  85822. statement += `
  85823. `;
  85824. statement += "primaryKey({ columns: [";
  85825. statement += `${it.columns.map((c3) => {
  85826. return `table.${casing2(c3)}`;
  85827. }).join(", ")}]${it.name ? `, name: "${it.name}"` : ""}}`;
  85828. statement += "),";
  85829. });
  85830. return statement;
  85831. };
  85832. }
  85833. });
  85834. // src/cli/commands/introspect.ts
  85835. var introspect_exports = {};
  85836. __export(introspect_exports, {
  85837. introspectGel: () => introspectGel,
  85838. introspectLibSQL: () => introspectLibSQL,
  85839. introspectMysql: () => introspectMysql,
  85840. introspectPostgres: () => introspectPostgres,
  85841. introspectSingleStore: () => introspectSingleStore,
  85842. introspectSqlite: () => introspectSqlite,
  85843. relationsToTypeScript: () => relationsToTypeScript
  85844. });
  85845. var import_fs11, import_hanji14, import_path7, import_pluralize, introspectPostgres, introspectGel, introspectMysql, introspectSingleStore, introspectSqlite, introspectLibSQL, withCasing4, relationsToTypeScript;
  85846. var init_introspect = __esm({
  85847. "src/cli/commands/introspect.ts"() {
  85848. "use strict";
  85849. init_source();
  85850. import_fs11 = require("fs");
  85851. import_hanji14 = __toESM(require_hanji());
  85852. init_mjs();
  85853. import_path7 = require("path");
  85854. import_pluralize = __toESM(require_pluralize());
  85855. init_singlestoreSchema();
  85856. init_global();
  85857. init_introspect_gel();
  85858. init_introspect_mysql();
  85859. init_introspect_pg();
  85860. init_introspect_singlestore();
  85861. init_introspect_sqlite();
  85862. init_gelSerializer();
  85863. init_mysqlSchema();
  85864. init_mysqlSerializer();
  85865. init_pgSchema();
  85866. init_pgSerializer();
  85867. init_singlestoreSerializer();
  85868. init_sqliteSchema();
  85869. init_sqliteSerializer();
  85870. init_snapshotsDiffer();
  85871. init_utils2();
  85872. init_views();
  85873. init_migrate();
  85874. introspectPostgres = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2, entities) => {
  85875. const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  85876. const db = await preparePostgresDB2(credentials2);
  85877. const matchers = tablesFilter.map((it) => {
  85878. return new Minimatch(it);
  85879. });
  85880. const filter2 = (tableName) => {
  85881. if (matchers.length === 0) return true;
  85882. let flags = [];
  85883. for (let matcher of matchers) {
  85884. if (matcher.negate) {
  85885. if (!matcher.match(tableName)) {
  85886. flags.push(false);
  85887. }
  85888. }
  85889. if (matcher.match(tableName)) {
  85890. flags.push(true);
  85891. }
  85892. }
  85893. if (flags.length > 0) {
  85894. return flags.every(Boolean);
  85895. }
  85896. return false;
  85897. };
  85898. const progress = new IntrospectProgress(true);
  85899. const res = await (0, import_hanji14.renderWithTask)(
  85900. progress,
  85901. fromDatabase2(
  85902. db,
  85903. filter2,
  85904. schemasFilter,
  85905. entities,
  85906. (stage, count, status) => {
  85907. progress.update(stage, count, status);
  85908. }
  85909. )
  85910. );
  85911. const schema6 = { id: originUUID, prevId: "", ...res };
  85912. const ts = schemaToTypeScript4(schema6, casing2);
  85913. const relationsTs = relationsToTypeScript(schema6, casing2);
  85914. const { internal, ...schemaWithoutInternals } = schema6;
  85915. const schemaFile = (0, import_path7.join)(out, "schema.ts");
  85916. (0, import_fs11.writeFileSync)(schemaFile, ts.file);
  85917. const relationsFile = (0, import_path7.join)(out, "relations.ts");
  85918. (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
  85919. console.log();
  85920. const { snapshots, journal } = prepareOutFolder(out, "postgresql");
  85921. if (snapshots.length === 0) {
  85922. const { sqlStatements, _meta } = await applyPgSnapshotsDiff(
  85923. squashPgScheme(dryPg),
  85924. squashPgScheme(schema6),
  85925. schemasResolver,
  85926. enumsResolver,
  85927. sequencesResolver,
  85928. policyResolver,
  85929. indPolicyResolver,
  85930. roleResolver,
  85931. tablesResolver,
  85932. columnsResolver,
  85933. viewsResolver,
  85934. dryPg,
  85935. schema6
  85936. );
  85937. writeResult({
  85938. cur: schema6,
  85939. sqlStatements,
  85940. journal,
  85941. _meta,
  85942. outFolder: out,
  85943. breakpoints,
  85944. type: "introspect",
  85945. prefixMode: prefix2
  85946. });
  85947. } else {
  85948. (0, import_hanji14.render)(
  85949. `[${source_default.blue(
  85950. "i"
  85951. )}] No SQL generated, you already have migrations in project`
  85952. );
  85953. }
  85954. (0, import_hanji14.render)(
  85955. `[${source_default.green(
  85956. "\u2713"
  85957. )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
  85958. );
  85959. (0, import_hanji14.render)(
  85960. `[${source_default.green(
  85961. "\u2713"
  85962. )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
  85963. relationsFile
  85964. )} \u{1F680}`
  85965. );
  85966. process.exit(0);
  85967. };
  85968. introspectGel = async (casing2, out, breakpoints, credentials2, tablesFilter, schemasFilter, prefix2, entities) => {
  85969. const { prepareGelDB: prepareGelDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  85970. const db = await prepareGelDB2(credentials2);
  85971. const matchers = tablesFilter.map((it) => {
  85972. return new Minimatch(it);
  85973. });
  85974. const filter2 = (tableName) => {
  85975. if (matchers.length === 0) return true;
  85976. let flags = [];
  85977. for (let matcher of matchers) {
  85978. if (matcher.negate) {
  85979. if (!matcher.match(tableName)) {
  85980. flags.push(false);
  85981. }
  85982. }
  85983. if (matcher.match(tableName)) {
  85984. flags.push(true);
  85985. }
  85986. }
  85987. if (flags.length > 0) {
  85988. return flags.every(Boolean);
  85989. }
  85990. return false;
  85991. };
  85992. const progress = new IntrospectProgress(true);
  85993. const res = await (0, import_hanji14.renderWithTask)(
  85994. progress,
  85995. fromDatabase5(
  85996. db,
  85997. filter2,
  85998. schemasFilter,
  85999. entities,
  86000. (stage, count, status) => {
  86001. progress.update(stage, count, status);
  86002. }
  86003. )
  86004. );
  86005. const schema6 = { id: originUUID, prevId: "", ...res };
  86006. const ts = schemaToTypeScript2(schema6, casing2);
  86007. const relationsTs = relationsToTypeScript(schema6, casing2);
  86008. const { internal, ...schemaWithoutInternals } = schema6;
  86009. const schemaFile = (0, import_path7.join)(out, "schema.ts");
  86010. (0, import_fs11.writeFileSync)(schemaFile, ts.file);
  86011. const relationsFile = (0, import_path7.join)(out, "relations.ts");
  86012. (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
  86013. console.log();
  86014. (0, import_hanji14.render)(
  86015. `[${source_default.green(
  86016. "\u2713"
  86017. )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
  86018. );
  86019. (0, import_hanji14.render)(
  86020. `[${source_default.green(
  86021. "\u2713"
  86022. )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
  86023. relationsFile
  86024. )} \u{1F680}`
  86025. );
  86026. process.exit(0);
  86027. };
  86028. introspectMysql = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
  86029. const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  86030. const { db, database } = await connectToMySQL2(credentials2);
  86031. const matchers = tablesFilter.map((it) => {
  86032. return new Minimatch(it);
  86033. });
  86034. const filter2 = (tableName) => {
  86035. if (matchers.length === 0) return true;
  86036. let flags = [];
  86037. for (let matcher of matchers) {
  86038. if (matcher.negate) {
  86039. if (!matcher.match(tableName)) {
  86040. flags.push(false);
  86041. }
  86042. }
  86043. if (matcher.match(tableName)) {
  86044. flags.push(true);
  86045. }
  86046. }
  86047. if (flags.length > 0) {
  86048. return flags.every(Boolean);
  86049. }
  86050. return false;
  86051. };
  86052. const progress = new IntrospectProgress();
  86053. const res = await (0, import_hanji14.renderWithTask)(
  86054. progress,
  86055. fromDatabase(db, database, filter2, (stage, count, status) => {
  86056. progress.update(stage, count, status);
  86057. })
  86058. );
  86059. const schema6 = { id: originUUID, prevId: "", ...res };
  86060. const ts = schemaToTypeScript3(schema6, casing2);
  86061. const relationsTs = relationsToTypeScript(schema6, casing2);
  86062. const { internal, ...schemaWithoutInternals } = schema6;
  86063. const schemaFile = (0, import_path7.join)(out, "schema.ts");
  86064. (0, import_fs11.writeFileSync)(schemaFile, ts.file);
  86065. const relationsFile = (0, import_path7.join)(out, "relations.ts");
  86066. (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
  86067. console.log();
  86068. const { snapshots, journal } = prepareOutFolder(out, "mysql");
  86069. if (snapshots.length === 0) {
  86070. const { sqlStatements, _meta } = await applyMysqlSnapshotsDiff(
  86071. squashMysqlScheme(dryMySql),
  86072. squashMysqlScheme(schema6),
  86073. tablesResolver,
  86074. columnsResolver,
  86075. mySqlViewsResolver,
  86076. dryMySql,
  86077. schema6
  86078. );
  86079. writeResult({
  86080. cur: schema6,
  86081. sqlStatements,
  86082. journal,
  86083. _meta,
  86084. outFolder: out,
  86085. breakpoints,
  86086. type: "introspect",
  86087. prefixMode: prefix2
  86088. });
  86089. } else {
  86090. (0, import_hanji14.render)(
  86091. `[${source_default.blue(
  86092. "i"
  86093. )}] No SQL generated, you already have migrations in project`
  86094. );
  86095. }
  86096. (0, import_hanji14.render)(
  86097. `[${source_default.green(
  86098. "\u2713"
  86099. )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
  86100. );
  86101. (0, import_hanji14.render)(
  86102. `[${source_default.green(
  86103. "\u2713"
  86104. )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
  86105. relationsFile
  86106. )} \u{1F680}`
  86107. );
  86108. process.exit(0);
  86109. };
  86110. introspectSingleStore = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
  86111. const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  86112. const { db, database } = await connectToSingleStore2(credentials2);
  86113. const matchers = tablesFilter.map((it) => {
  86114. return new Minimatch(it);
  86115. });
  86116. const filter2 = (tableName) => {
  86117. if (matchers.length === 0) return true;
  86118. let flags = [];
  86119. for (let matcher of matchers) {
  86120. if (matcher.negate) {
  86121. if (!matcher.match(tableName)) {
  86122. flags.push(false);
  86123. }
  86124. }
  86125. if (matcher.match(tableName)) {
  86126. flags.push(true);
  86127. }
  86128. }
  86129. if (flags.length > 0) {
  86130. return flags.every(Boolean);
  86131. }
  86132. return false;
  86133. };
  86134. const progress = new IntrospectProgress();
  86135. const res = await (0, import_hanji14.renderWithTask)(
  86136. progress,
  86137. fromDatabase4(db, database, filter2, (stage, count, status) => {
  86138. progress.update(stage, count, status);
  86139. })
  86140. );
  86141. const schema6 = { id: originUUID, prevId: "", ...res };
  86142. const ts = schemaToTypeScript5(schema6, casing2);
  86143. const { internal, ...schemaWithoutInternals } = schema6;
  86144. const schemaFile = (0, import_path7.join)(out, "schema.ts");
  86145. (0, import_fs11.writeFileSync)(schemaFile, ts.file);
  86146. console.log();
  86147. const { snapshots, journal } = prepareOutFolder(out, "postgresql");
  86148. if (snapshots.length === 0) {
  86149. const { sqlStatements, _meta } = await applySingleStoreSnapshotsDiff(
  86150. squashSingleStoreScheme(drySingleStore),
  86151. squashSingleStoreScheme(schema6),
  86152. tablesResolver,
  86153. columnsResolver,
  86154. /* singleStoreViewsResolver, */
  86155. drySingleStore,
  86156. schema6
  86157. );
  86158. writeResult({
  86159. cur: schema6,
  86160. sqlStatements,
  86161. journal,
  86162. _meta,
  86163. outFolder: out,
  86164. breakpoints,
  86165. type: "introspect",
  86166. prefixMode: prefix2
  86167. });
  86168. } else {
  86169. (0, import_hanji14.render)(
  86170. `[${source_default.blue(
  86171. "i"
  86172. )}] No SQL generated, you already have migrations in project`
  86173. );
  86174. }
  86175. (0, import_hanji14.render)(
  86176. `[${source_default.green(
  86177. "\u2713"
  86178. )}] You schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
  86179. );
  86180. process.exit(0);
  86181. };
  86182. introspectSqlite = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
  86183. const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  86184. const db = await connectToSQLite2(credentials2);
  86185. const matchers = tablesFilter.map((it) => {
  86186. return new Minimatch(it);
  86187. });
  86188. const filter2 = (tableName) => {
  86189. if (matchers.length === 0) return true;
  86190. let flags = [];
  86191. for (let matcher of matchers) {
  86192. if (matcher.negate) {
  86193. if (!matcher.match(tableName)) {
  86194. flags.push(false);
  86195. }
  86196. }
  86197. if (matcher.match(tableName)) {
  86198. flags.push(true);
  86199. }
  86200. }
  86201. if (flags.length > 0) {
  86202. return flags.every(Boolean);
  86203. }
  86204. return false;
  86205. };
  86206. const progress = new IntrospectProgress();
  86207. const res = await (0, import_hanji14.renderWithTask)(
  86208. progress,
  86209. fromDatabase3(db, filter2, (stage, count, status) => {
  86210. progress.update(stage, count, status);
  86211. })
  86212. );
  86213. const schema6 = { id: originUUID, prevId: "", ...res };
  86214. const ts = schemaToTypeScript(schema6, casing2);
  86215. const relationsTs = relationsToTypeScript(schema6, casing2);
  86216. const schemaFile = (0, import_path7.join)(out, "schema.ts");
  86217. (0, import_fs11.writeFileSync)(schemaFile, ts.file);
  86218. const relationsFile = (0, import_path7.join)(out, "relations.ts");
  86219. (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
  86220. console.log();
  86221. const { snapshots, journal } = prepareOutFolder(out, "sqlite");
  86222. if (snapshots.length === 0) {
  86223. const { sqlStatements, _meta } = await applySqliteSnapshotsDiff(
  86224. squashSqliteScheme(drySQLite),
  86225. squashSqliteScheme(schema6),
  86226. tablesResolver,
  86227. columnsResolver,
  86228. sqliteViewsResolver,
  86229. drySQLite,
  86230. schema6
  86231. );
  86232. writeResult({
  86233. cur: schema6,
  86234. sqlStatements,
  86235. journal,
  86236. _meta,
  86237. outFolder: out,
  86238. breakpoints,
  86239. type: "introspect",
  86240. prefixMode: prefix2
  86241. });
  86242. } else {
  86243. (0, import_hanji14.render)(
  86244. `[${source_default.blue(
  86245. "i"
  86246. )}] No SQL generated, you already have migrations in project`
  86247. );
  86248. }
  86249. (0, import_hanji14.render)(
  86250. `[${source_default.green(
  86251. "\u2713"
  86252. )}] You schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
  86253. );
  86254. (0, import_hanji14.render)(
  86255. `[${source_default.green(
  86256. "\u2713"
  86257. )}] You relations file is ready \u279C ${source_default.bold.underline.blue(
  86258. relationsFile
  86259. )} \u{1F680}`
  86260. );
  86261. process.exit(0);
  86262. };
  86263. introspectLibSQL = async (casing2, out, breakpoints, credentials2, tablesFilter, prefix2) => {
  86264. const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  86265. const db = await connectToLibSQL2(credentials2);
  86266. const matchers = tablesFilter.map((it) => {
  86267. return new Minimatch(it);
  86268. });
  86269. const filter2 = (tableName) => {
  86270. if (matchers.length === 0) return true;
  86271. let flags = [];
  86272. for (let matcher of matchers) {
  86273. if (matcher.negate) {
  86274. if (!matcher.match(tableName)) {
  86275. flags.push(false);
  86276. }
  86277. }
  86278. if (matcher.match(tableName)) {
  86279. flags.push(true);
  86280. }
  86281. }
  86282. if (flags.length > 0) {
  86283. return flags.every(Boolean);
  86284. }
  86285. return false;
  86286. };
  86287. const progress = new IntrospectProgress();
  86288. const res = await (0, import_hanji14.renderWithTask)(
  86289. progress,
  86290. fromDatabase3(db, filter2, (stage, count, status) => {
  86291. progress.update(stage, count, status);
  86292. })
  86293. );
  86294. const schema6 = { id: originUUID, prevId: "", ...res };
  86295. const ts = schemaToTypeScript(schema6, casing2);
  86296. const relationsTs = relationsToTypeScript(schema6, casing2);
  86297. const schemaFile = (0, import_path7.join)(out, "schema.ts");
  86298. (0, import_fs11.writeFileSync)(schemaFile, ts.file);
  86299. const relationsFile = (0, import_path7.join)(out, "relations.ts");
  86300. (0, import_fs11.writeFileSync)(relationsFile, relationsTs.file);
  86301. console.log();
  86302. const { snapshots, journal } = prepareOutFolder(out, "sqlite");
  86303. if (snapshots.length === 0) {
  86304. const { sqlStatements, _meta } = await applyLibSQLSnapshotsDiff(
  86305. squashSqliteScheme(drySQLite),
  86306. squashSqliteScheme(schema6),
  86307. tablesResolver,
  86308. columnsResolver,
  86309. sqliteViewsResolver,
  86310. drySQLite,
  86311. schema6
  86312. );
  86313. writeResult({
  86314. cur: schema6,
  86315. sqlStatements,
  86316. journal,
  86317. _meta,
  86318. outFolder: out,
  86319. breakpoints,
  86320. type: "introspect",
  86321. prefixMode: prefix2
  86322. });
  86323. } else {
  86324. (0, import_hanji14.render)(
  86325. `[${source_default.blue(
  86326. "i"
  86327. )}] No SQL generated, you already have migrations in project`
  86328. );
  86329. }
  86330. (0, import_hanji14.render)(
  86331. `[${source_default.green(
  86332. "\u2713"
  86333. )}] Your schema file is ready \u279C ${source_default.bold.underline.blue(schemaFile)} \u{1F680}`
  86334. );
  86335. (0, import_hanji14.render)(
  86336. `[${source_default.green(
  86337. "\u2713"
  86338. )}] Your relations file is ready \u279C ${source_default.bold.underline.blue(
  86339. relationsFile
  86340. )} \u{1F680}`
  86341. );
  86342. process.exit(0);
  86343. };
  86344. withCasing4 = (value, casing2) => {
  86345. if (casing2 === "preserve") {
  86346. return value;
  86347. }
  86348. if (casing2 === "camel") {
  86349. return value.camelCase();
  86350. }
  86351. assertUnreachable(casing2);
  86352. };
  86353. relationsToTypeScript = (schema6, casing2) => {
  86354. const imports = [];
  86355. const tableRelations = {};
  86356. Object.values(schema6.tables).forEach((table6) => {
  86357. Object.values(table6.foreignKeys).forEach((fk5) => {
  86358. const tableNameFrom = paramNameFor2(fk5.tableFrom, table6.schema);
  86359. const tableNameTo = paramNameFor2(fk5.tableTo, fk5.schemaTo);
  86360. const tableFrom = withCasing4(tableNameFrom.replace(/:+/g, ""), casing2);
  86361. const tableTo = withCasing4(tableNameTo.replace(/:+/g, ""), casing2);
  86362. const columnFrom = withCasing4(fk5.columnsFrom[0], casing2);
  86363. const columnTo = withCasing4(fk5.columnsTo[0], casing2);
  86364. imports.push(tableTo, tableFrom);
  86365. const keyFrom = tableFrom;
  86366. if (!tableRelations[keyFrom]) {
  86367. tableRelations[keyFrom] = [];
  86368. }
  86369. tableRelations[keyFrom].push({
  86370. name: (0, import_pluralize.singular)(tableTo),
  86371. type: "one",
  86372. tableFrom,
  86373. columnFrom,
  86374. tableTo,
  86375. columnTo
  86376. });
  86377. const keyTo = tableTo;
  86378. if (!tableRelations[keyTo]) {
  86379. tableRelations[keyTo] = [];
  86380. }
  86381. tableRelations[keyTo].push({
  86382. name: (0, import_pluralize.plural)(tableFrom),
  86383. type: "many",
  86384. tableFrom: tableTo,
  86385. columnFrom: columnTo,
  86386. tableTo: tableFrom,
  86387. columnTo: columnFrom
  86388. });
  86389. });
  86390. });
  86391. const uniqueImports = [...new Set(imports)];
  86392. const importsTs = `import { relations } from "drizzle-orm/relations";
  86393. import { ${uniqueImports.join(
  86394. ", "
  86395. )} } from "./schema";
  86396. `;
  86397. const relationStatements = Object.entries(tableRelations).map(
  86398. ([table6, relations5]) => {
  86399. const hasOne = relations5.some((it) => it.type === "one");
  86400. const hasMany = relations5.some((it) => it.type === "many");
  86401. const preparedRelations = relations5.map(
  86402. (relation, relationIndex, originArray) => {
  86403. let name = relation.name;
  86404. let relationName;
  86405. const hasMultipleRelations = originArray.some(
  86406. (it, originIndex) => relationIndex !== originIndex && it.tableTo === relation.tableTo
  86407. );
  86408. if (hasMultipleRelations) {
  86409. relationName = relation.type === "one" ? `${relation.tableFrom}_${relation.columnFrom}_${relation.tableTo}_${relation.columnTo}` : `${relation.tableTo}_${relation.columnTo}_${relation.tableFrom}_${relation.columnFrom}`;
  86410. }
  86411. const hasDuplicatedRelation = originArray.some(
  86412. (it, originIndex) => relationIndex !== originIndex && it.name === relation.name
  86413. );
  86414. if (hasDuplicatedRelation) {
  86415. name = `${relation.name}_${relation.type === "one" ? relation.columnFrom : relation.columnTo}`;
  86416. }
  86417. return {
  86418. ...relation,
  86419. name,
  86420. relationName
  86421. };
  86422. }
  86423. );
  86424. const fields = preparedRelations.map((relation) => {
  86425. if (relation.type === "one") {
  86426. return ` ${relation.name}: one(${relation.tableTo}, {
  86427. fields: [${relation.tableFrom}.${relation.columnFrom}],
  86428. references: [${relation.tableTo}.${relation.columnTo}]${relation.relationName ? `,
  86429. relationName: "${relation.relationName}"` : ""}
  86430. }),`;
  86431. } else {
  86432. return ` ${relation.name}: many(${relation.tableTo}${relation.relationName ? `, {
  86433. relationName: "${relation.relationName}"
  86434. }` : ""}),`;
  86435. }
  86436. });
  86437. return `export const ${table6}Relations = relations(${table6}, ({${hasOne ? "one" : ""}${hasOne && hasMany ? ", " : ""}${hasMany ? "many" : ""}}) => ({
  86438. ${fields.join("\n")}
  86439. }));`;
  86440. }
  86441. );
  86442. return {
  86443. file: importsTs + relationStatements.join("\n\n")
  86444. };
  86445. };
  86446. }
  86447. });
  86448. // ../node_modules/.pnpm/@hono+node-server@1.14.3_hono@4.7.10/node_modules/@hono/node-server/dist/index.mjs
  86449. function writeFromReadableStream(stream, writable) {
  86450. if (stream.locked) {
  86451. throw new TypeError("ReadableStream is locked.");
  86452. } else if (writable.destroyed) {
  86453. stream.cancel();
  86454. return;
  86455. }
  86456. const reader = stream.getReader();
  86457. writable.on("close", cancel);
  86458. writable.on("error", cancel);
  86459. reader.read().then(flow, cancel);
  86460. return reader.closed.finally(() => {
  86461. writable.off("close", cancel);
  86462. writable.off("error", cancel);
  86463. });
  86464. function cancel(error2) {
  86465. reader.cancel(error2).catch(() => {
  86466. });
  86467. if (error2) {
  86468. writable.destroy(error2);
  86469. }
  86470. }
  86471. function onDrain() {
  86472. reader.read().then(flow, cancel);
  86473. }
  86474. function flow({ done, value }) {
  86475. try {
  86476. if (done) {
  86477. writable.end();
  86478. } else if (!writable.write(value)) {
  86479. writable.once("drain", onDrain);
  86480. } else {
  86481. return reader.read().then(flow, cancel);
  86482. }
  86483. } catch (e4) {
  86484. cancel(e4);
  86485. }
  86486. }
  86487. }
  86488. var import_http, import_http2, import_stream2, import_crypto7, RequestError, toRequestError, GlobalRequest, Request3, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, Response22, buildOutgoingHttpHeaders, X_ALREADY_SENT, webFetch, regBuffer, regContentType, handleRequestError, handleFetchError, handleResponseError, responseViaCache, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
  86489. var init_dist2 = __esm({
  86490. "../node_modules/.pnpm/@hono+node-server@1.14.3_hono@4.7.10/node_modules/@hono/node-server/dist/index.mjs"() {
  86491. import_http = require("http");
  86492. import_http2 = require("http2");
  86493. import_stream2 = require("stream");
  86494. import_crypto7 = __toESM(require("crypto"), 1);
  86495. RequestError = class extends Error {
  86496. constructor(message, options) {
  86497. super(message, options);
  86498. this.name = "RequestError";
  86499. }
  86500. };
  86501. toRequestError = (e4) => {
  86502. if (e4 instanceof RequestError) {
  86503. return e4;
  86504. }
  86505. return new RequestError(e4.message, { cause: e4 });
  86506. };
  86507. GlobalRequest = global.Request;
  86508. Request3 = class extends GlobalRequest {
  86509. constructor(input, options) {
  86510. var _a2;
  86511. if (typeof input === "object" && getRequestCache in input) {
  86512. input = input[getRequestCache]();
  86513. }
  86514. if (typeof ((_a2 = options == null ? void 0 : options.body) == null ? void 0 : _a2.getReader) !== "undefined") {
  86515. ;
  86516. options.duplex ??= "half";
  86517. }
  86518. super(input, options);
  86519. }
  86520. };
  86521. newRequestFromIncoming = (method, url, incoming, abortController) => {
  86522. const headerRecord = [];
  86523. const rawHeaders = incoming.rawHeaders;
  86524. for (let i4 = 0; i4 < rawHeaders.length; i4 += 2) {
  86525. const { [i4]: key, [i4 + 1]: value } = rawHeaders;
  86526. if (key.charCodeAt(0) !== /*:*/
  86527. 58) {
  86528. headerRecord.push([key, value]);
  86529. }
  86530. }
  86531. const init2 = {
  86532. method,
  86533. headers: headerRecord,
  86534. signal: abortController.signal
  86535. };
  86536. if (method === "TRACE") {
  86537. init2.method = "GET";
  86538. const req = new Request3(url, init2);
  86539. Object.defineProperty(req, "method", {
  86540. get() {
  86541. return "TRACE";
  86542. }
  86543. });
  86544. return req;
  86545. }
  86546. if (!(method === "GET" || method === "HEAD")) {
  86547. if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
  86548. init2.body = new ReadableStream({
  86549. start(controller) {
  86550. controller.enqueue(incoming.rawBody);
  86551. controller.close();
  86552. }
  86553. });
  86554. } else {
  86555. init2.body = import_stream2.Readable.toWeb(incoming);
  86556. }
  86557. }
  86558. return new Request3(url, init2);
  86559. };
  86560. getRequestCache = Symbol("getRequestCache");
  86561. requestCache = Symbol("requestCache");
  86562. incomingKey = Symbol("incomingKey");
  86563. urlKey = Symbol("urlKey");
  86564. abortControllerKey = Symbol("abortControllerKey");
  86565. getAbortController = Symbol("getAbortController");
  86566. requestPrototype = {
  86567. get method() {
  86568. return this[incomingKey].method || "GET";
  86569. },
  86570. get url() {
  86571. return this[urlKey];
  86572. },
  86573. [getAbortController]() {
  86574. this[getRequestCache]();
  86575. return this[abortControllerKey];
  86576. },
  86577. [getRequestCache]() {
  86578. this[abortControllerKey] ||= new AbortController();
  86579. return this[requestCache] ||= newRequestFromIncoming(
  86580. this.method,
  86581. this[urlKey],
  86582. this[incomingKey],
  86583. this[abortControllerKey]
  86584. );
  86585. }
  86586. };
  86587. [
  86588. "body",
  86589. "bodyUsed",
  86590. "cache",
  86591. "credentials",
  86592. "destination",
  86593. "headers",
  86594. "integrity",
  86595. "mode",
  86596. "redirect",
  86597. "referrer",
  86598. "referrerPolicy",
  86599. "signal",
  86600. "keepalive"
  86601. ].forEach((k3) => {
  86602. Object.defineProperty(requestPrototype, k3, {
  86603. get() {
  86604. return this[getRequestCache]()[k3];
  86605. }
  86606. });
  86607. });
  86608. ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k3) => {
  86609. Object.defineProperty(requestPrototype, k3, {
  86610. value: function() {
  86611. return this[getRequestCache]()[k3]();
  86612. }
  86613. });
  86614. });
  86615. Object.setPrototypeOf(requestPrototype, Request3.prototype);
  86616. newRequest = (incoming, defaultHostname) => {
  86617. const req = Object.create(requestPrototype);
  86618. req[incomingKey] = incoming;
  86619. const incomingUrl = incoming.url || "";
  86620. if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
  86621. (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
  86622. if (incoming instanceof import_http2.Http2ServerRequest) {
  86623. throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
  86624. }
  86625. try {
  86626. const url2 = new URL(incomingUrl);
  86627. req[urlKey] = url2.href;
  86628. } catch (e4) {
  86629. throw new RequestError("Invalid absolute URL", { cause: e4 });
  86630. }
  86631. return req;
  86632. }
  86633. const host = (incoming instanceof import_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
  86634. if (!host) {
  86635. throw new RequestError("Missing host header");
  86636. }
  86637. let scheme;
  86638. if (incoming instanceof import_http2.Http2ServerRequest) {
  86639. scheme = incoming.scheme;
  86640. if (!(scheme === "http" || scheme === "https")) {
  86641. throw new RequestError("Unsupported scheme");
  86642. }
  86643. } else {
  86644. scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
  86645. }
  86646. const url = new URL(`${scheme}://${host}${incomingUrl}`);
  86647. if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
  86648. throw new RequestError("Invalid host header");
  86649. }
  86650. req[urlKey] = url.href;
  86651. return req;
  86652. };
  86653. responseCache = Symbol("responseCache");
  86654. getResponseCache = Symbol("getResponseCache");
  86655. cacheKey = Symbol("cache");
  86656. GlobalResponse = global.Response;
  86657. Response22 = class _Response {
  86658. #body;
  86659. #init;
  86660. [getResponseCache]() {
  86661. delete this[cacheKey];
  86662. return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
  86663. }
  86664. constructor(body, init2) {
  86665. let headers;
  86666. this.#body = body;
  86667. if (init2 instanceof _Response) {
  86668. const cachedGlobalResponse = init2[responseCache];
  86669. if (cachedGlobalResponse) {
  86670. this.#init = cachedGlobalResponse;
  86671. this[getResponseCache]();
  86672. return;
  86673. } else {
  86674. this.#init = init2.#init;
  86675. headers = new Headers(init2.#init.headers);
  86676. }
  86677. } else {
  86678. this.#init = init2;
  86679. }
  86680. if (typeof body === "string" || typeof (body == null ? void 0 : body.getReader) !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
  86681. headers ||= (init2 == null ? void 0 : init2.headers) || { "content-type": "text/plain; charset=UTF-8" };
  86682. this[cacheKey] = [(init2 == null ? void 0 : init2.status) || 200, body, headers];
  86683. }
  86684. }
  86685. get headers() {
  86686. const cache3 = this[cacheKey];
  86687. if (cache3) {
  86688. if (!(cache3[2] instanceof Headers)) {
  86689. cache3[2] = new Headers(cache3[2]);
  86690. }
  86691. return cache3[2];
  86692. }
  86693. return this[getResponseCache]().headers;
  86694. }
  86695. get status() {
  86696. var _a2;
  86697. return ((_a2 = this[cacheKey]) == null ? void 0 : _a2[0]) ?? this[getResponseCache]().status;
  86698. }
  86699. get ok() {
  86700. const status = this.status;
  86701. return status >= 200 && status < 300;
  86702. }
  86703. };
  86704. ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k3) => {
  86705. Object.defineProperty(Response22.prototype, k3, {
  86706. get() {
  86707. return this[getResponseCache]()[k3];
  86708. }
  86709. });
  86710. });
  86711. ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k3) => {
  86712. Object.defineProperty(Response22.prototype, k3, {
  86713. value: function() {
  86714. return this[getResponseCache]()[k3]();
  86715. }
  86716. });
  86717. });
  86718. Object.setPrototypeOf(Response22, GlobalResponse);
  86719. Object.setPrototypeOf(Response22.prototype, GlobalResponse.prototype);
  86720. buildOutgoingHttpHeaders = (headers) => {
  86721. const res = {};
  86722. if (!(headers instanceof Headers)) {
  86723. headers = new Headers(headers ?? void 0);
  86724. }
  86725. const cookies = [];
  86726. for (const [k3, v6] of headers) {
  86727. if (k3 === "set-cookie") {
  86728. cookies.push(v6);
  86729. } else {
  86730. res[k3] = v6;
  86731. }
  86732. }
  86733. if (cookies.length > 0) {
  86734. res["set-cookie"] = cookies;
  86735. }
  86736. res["content-type"] ??= "text/plain; charset=UTF-8";
  86737. return res;
  86738. };
  86739. X_ALREADY_SENT = "x-hono-already-sent";
  86740. webFetch = global.fetch;
  86741. if (typeof global.crypto === "undefined") {
  86742. global.crypto = import_crypto7.default;
  86743. }
  86744. global.fetch = (info2, init2) => {
  86745. init2 = {
  86746. // Disable compression handling so people can return the result of a fetch
  86747. // directly in the loader without messing with the Content-Encoding header.
  86748. compress: false,
  86749. ...init2
  86750. };
  86751. return webFetch(info2, init2);
  86752. };
  86753. regBuffer = /^no$/i;
  86754. regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i;
  86755. handleRequestError = () => new Response(null, {
  86756. status: 400
  86757. });
  86758. handleFetchError = (e4) => new Response(null, {
  86759. status: e4 instanceof Error && (e4.name === "TimeoutError" || e4.constructor.name === "TimeoutError") ? 504 : 500
  86760. });
  86761. handleResponseError = (e4, outgoing) => {
  86762. const err2 = e4 instanceof Error ? e4 : new Error("unknown error", { cause: e4 });
  86763. if (err2.code === "ERR_STREAM_PREMATURE_CLOSE") {
  86764. console.info("The user aborted a request.");
  86765. } else {
  86766. console.error(e4);
  86767. if (!outgoing.headersSent) {
  86768. outgoing.writeHead(500, { "Content-Type": "text/plain" });
  86769. }
  86770. outgoing.end(`Error: ${err2.message}`);
  86771. outgoing.destroy(err2);
  86772. }
  86773. };
  86774. responseViaCache = async (res, outgoing) => {
  86775. var _a2;
  86776. let [status, body, header] = res[cacheKey];
  86777. if (header instanceof Headers) {
  86778. header = buildOutgoingHttpHeaders(header);
  86779. }
  86780. if (typeof body === "string") {
  86781. header["Content-Length"] = Buffer.byteLength(body);
  86782. } else if (body instanceof Uint8Array) {
  86783. header["Content-Length"] = body.byteLength;
  86784. } else if (body instanceof Blob) {
  86785. header["Content-Length"] = body.size;
  86786. }
  86787. outgoing.writeHead(status, header);
  86788. if (typeof body === "string" || body instanceof Uint8Array) {
  86789. outgoing.end(body);
  86790. } else if (body instanceof Blob) {
  86791. outgoing.end(new Uint8Array(await body.arrayBuffer()));
  86792. } else {
  86793. return (_a2 = writeFromReadableStream(body, outgoing)) == null ? void 0 : _a2.catch(
  86794. (e4) => handleResponseError(e4, outgoing)
  86795. );
  86796. }
  86797. };
  86798. responseViaResponseObject = async (res, outgoing, options = {}) => {
  86799. if (res instanceof Promise) {
  86800. if (options.errorHandler) {
  86801. try {
  86802. res = await res;
  86803. } catch (err2) {
  86804. const errRes = await options.errorHandler(err2);
  86805. if (!errRes) {
  86806. return;
  86807. }
  86808. res = errRes;
  86809. }
  86810. } else {
  86811. res = await res.catch(handleFetchError);
  86812. }
  86813. }
  86814. if (cacheKey in res) {
  86815. return responseViaCache(res, outgoing);
  86816. }
  86817. const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
  86818. if (res.body) {
  86819. const {
  86820. "transfer-encoding": transferEncoding,
  86821. "content-encoding": contentEncoding,
  86822. "content-length": contentLength,
  86823. "x-accel-buffering": accelBuffering,
  86824. "content-type": contentType
  86825. } = resHeaderRecord;
  86826. if (transferEncoding || contentEncoding || contentLength || // nginx buffering variant
  86827. accelBuffering && regBuffer.test(accelBuffering) || !regContentType.test(contentType)) {
  86828. outgoing.writeHead(res.status, resHeaderRecord);
  86829. await writeFromReadableStream(res.body, outgoing);
  86830. } else {
  86831. const buffer = await res.arrayBuffer();
  86832. resHeaderRecord["content-length"] = buffer.byteLength;
  86833. outgoing.writeHead(res.status, resHeaderRecord);
  86834. outgoing.end(new Uint8Array(buffer));
  86835. }
  86836. } else if (resHeaderRecord[X_ALREADY_SENT]) {
  86837. } else {
  86838. outgoing.writeHead(res.status, resHeaderRecord);
  86839. outgoing.end();
  86840. }
  86841. };
  86842. getRequestListener = (fetchCallback, options = {}) => {
  86843. if (options.overrideGlobalObjects !== false && global.Request !== Request3) {
  86844. Object.defineProperty(global, "Request", {
  86845. value: Request3
  86846. });
  86847. Object.defineProperty(global, "Response", {
  86848. value: Response22
  86849. });
  86850. }
  86851. return async (incoming, outgoing) => {
  86852. let res, req;
  86853. try {
  86854. req = newRequest(incoming, options.hostname);
  86855. outgoing.on("close", () => {
  86856. const abortController = req[abortControllerKey];
  86857. if (!abortController) {
  86858. return;
  86859. }
  86860. if (incoming.errored) {
  86861. req[abortControllerKey].abort(incoming.errored.toString());
  86862. } else if (!outgoing.writableFinished) {
  86863. req[abortControllerKey].abort("Client connection prematurely closed.");
  86864. }
  86865. });
  86866. res = fetchCallback(req, { incoming, outgoing });
  86867. if (cacheKey in res) {
  86868. return responseViaCache(res, outgoing);
  86869. }
  86870. } catch (e4) {
  86871. if (!res) {
  86872. if (options.errorHandler) {
  86873. res = await options.errorHandler(req ? e4 : toRequestError(e4));
  86874. if (!res) {
  86875. return;
  86876. }
  86877. } else if (!req) {
  86878. res = handleRequestError();
  86879. } else {
  86880. res = handleFetchError(e4);
  86881. }
  86882. } else {
  86883. return handleResponseError(e4, outgoing);
  86884. }
  86885. }
  86886. try {
  86887. return await responseViaResponseObject(res, outgoing, options);
  86888. } catch (e4) {
  86889. return handleResponseError(e4, outgoing);
  86890. }
  86891. };
  86892. };
  86893. createAdaptorServer = (options) => {
  86894. const fetchCallback = options.fetch;
  86895. const requestListener = getRequestListener(fetchCallback, {
  86896. hostname: options.hostname,
  86897. overrideGlobalObjects: options.overrideGlobalObjects
  86898. });
  86899. const createServer2 = options.createServer || import_http.createServer;
  86900. const server = createServer2(options.serverOptions || {}, requestListener);
  86901. return server;
  86902. };
  86903. serve = (options, listeningListener) => {
  86904. const server = createAdaptorServer(options);
  86905. server.listen((options == null ? void 0 : options.port) ?? 3e3, options.hostname, () => {
  86906. const serverInfo = server.address();
  86907. listeningListener && listeningListener(serverInfo);
  86908. });
  86909. return server;
  86910. };
  86911. }
  86912. });
  86913. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/url.js
  86914. var splitPath, splitRoutingPath, extractGroupsFromPath, replaceGroupMarks, patternCache, getPattern, tryDecode, tryDecodeURI, getPath, getPathNoStrict, mergePath, checkOptionalParameter, _decodeURI, _getQueryParam, getQueryParam, getQueryParams, decodeURIComponent_;
  86915. var init_url = __esm({
  86916. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/url.js"() {
  86917. splitPath = (path4) => {
  86918. const paths = path4.split("/");
  86919. if (paths[0] === "") {
  86920. paths.shift();
  86921. }
  86922. return paths;
  86923. };
  86924. splitRoutingPath = (routePath) => {
  86925. const { groups, path: path4 } = extractGroupsFromPath(routePath);
  86926. const paths = splitPath(path4);
  86927. return replaceGroupMarks(paths, groups);
  86928. };
  86929. extractGroupsFromPath = (path4) => {
  86930. const groups = [];
  86931. path4 = path4.replace(/\{[^}]+\}/g, (match2, index6) => {
  86932. const mark = `@${index6}`;
  86933. groups.push([mark, match2]);
  86934. return mark;
  86935. });
  86936. return { groups, path: path4 };
  86937. };
  86938. replaceGroupMarks = (paths, groups) => {
  86939. for (let i4 = groups.length - 1; i4 >= 0; i4--) {
  86940. const [mark] = groups[i4];
  86941. for (let j3 = paths.length - 1; j3 >= 0; j3--) {
  86942. if (paths[j3].includes(mark)) {
  86943. paths[j3] = paths[j3].replace(mark, groups[i4][1]);
  86944. break;
  86945. }
  86946. }
  86947. }
  86948. return paths;
  86949. };
  86950. patternCache = {};
  86951. getPattern = (label, next) => {
  86952. if (label === "*") {
  86953. return "*";
  86954. }
  86955. const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
  86956. if (match2) {
  86957. const cacheKey2 = `${label}#${next}`;
  86958. if (!patternCache[cacheKey2]) {
  86959. if (match2[2]) {
  86960. patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
  86961. } else {
  86962. patternCache[cacheKey2] = [label, match2[1], true];
  86963. }
  86964. }
  86965. return patternCache[cacheKey2];
  86966. }
  86967. return null;
  86968. };
  86969. tryDecode = (str, decoder) => {
  86970. try {
  86971. return decoder(str);
  86972. } catch {
  86973. return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
  86974. try {
  86975. return decoder(match2);
  86976. } catch {
  86977. return match2;
  86978. }
  86979. });
  86980. }
  86981. };
  86982. tryDecodeURI = (str) => tryDecode(str, decodeURI);
  86983. getPath = (request) => {
  86984. const url = request.url;
  86985. const start = url.indexOf("/", 8);
  86986. let i4 = start;
  86987. for (; i4 < url.length; i4++) {
  86988. const charCode = url.charCodeAt(i4);
  86989. if (charCode === 37) {
  86990. const queryIndex = url.indexOf("?", i4);
  86991. const path4 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
  86992. return tryDecodeURI(path4.includes("%25") ? path4.replace(/%25/g, "%2525") : path4);
  86993. } else if (charCode === 63) {
  86994. break;
  86995. }
  86996. }
  86997. return url.slice(start, i4);
  86998. };
  86999. getPathNoStrict = (request) => {
  87000. const result = getPath(request);
  87001. return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
  87002. };
  87003. mergePath = (base, sub, ...rest) => {
  87004. if (rest.length) {
  87005. sub = mergePath(sub, ...rest);
  87006. }
  87007. return `${(base == null ? void 0 : base[0]) === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${(base == null ? void 0 : base.at(-1)) === "/" ? "" : "/"}${(sub == null ? void 0 : sub[0]) === "/" ? sub.slice(1) : sub}`}`;
  87008. };
  87009. checkOptionalParameter = (path4) => {
  87010. if (path4.charCodeAt(path4.length - 1) !== 63 || !path4.includes(":")) {
  87011. return null;
  87012. }
  87013. const segments = path4.split("/");
  87014. const results = [];
  87015. let basePath = "";
  87016. segments.forEach((segment) => {
  87017. if (segment !== "" && !/\:/.test(segment)) {
  87018. basePath += "/" + segment;
  87019. } else if (/\:/.test(segment)) {
  87020. if (/\?/.test(segment)) {
  87021. if (results.length === 0 && basePath === "") {
  87022. results.push("/");
  87023. } else {
  87024. results.push(basePath);
  87025. }
  87026. const optionalSegment = segment.replace("?", "");
  87027. basePath += "/" + optionalSegment;
  87028. results.push(basePath);
  87029. } else {
  87030. basePath += "/" + segment;
  87031. }
  87032. }
  87033. });
  87034. return results.filter((v6, i4, a3) => a3.indexOf(v6) === i4);
  87035. };
  87036. _decodeURI = (value) => {
  87037. if (!/[%+]/.test(value)) {
  87038. return value;
  87039. }
  87040. if (value.indexOf("+") !== -1) {
  87041. value = value.replace(/\+/g, " ");
  87042. }
  87043. return value.indexOf("%") !== -1 ? decodeURIComponent_(value) : value;
  87044. };
  87045. _getQueryParam = (url, key, multiple) => {
  87046. let encoded;
  87047. if (!multiple && key && !/[%+]/.test(key)) {
  87048. let keyIndex2 = url.indexOf(`?${key}`, 8);
  87049. if (keyIndex2 === -1) {
  87050. keyIndex2 = url.indexOf(`&${key}`, 8);
  87051. }
  87052. while (keyIndex2 !== -1) {
  87053. const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
  87054. if (trailingKeyCode === 61) {
  87055. const valueIndex = keyIndex2 + key.length + 2;
  87056. const endIndex = url.indexOf("&", valueIndex);
  87057. return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
  87058. } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
  87059. return "";
  87060. }
  87061. keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
  87062. }
  87063. encoded = /[%+]/.test(url);
  87064. if (!encoded) {
  87065. return void 0;
  87066. }
  87067. }
  87068. const results = {};
  87069. encoded ??= /[%+]/.test(url);
  87070. let keyIndex = url.indexOf("?", 8);
  87071. while (keyIndex !== -1) {
  87072. const nextKeyIndex = url.indexOf("&", keyIndex + 1);
  87073. let valueIndex = url.indexOf("=", keyIndex);
  87074. if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
  87075. valueIndex = -1;
  87076. }
  87077. let name = url.slice(
  87078. keyIndex + 1,
  87079. valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
  87080. );
  87081. if (encoded) {
  87082. name = _decodeURI(name);
  87083. }
  87084. keyIndex = nextKeyIndex;
  87085. if (name === "") {
  87086. continue;
  87087. }
  87088. let value;
  87089. if (valueIndex === -1) {
  87090. value = "";
  87091. } else {
  87092. value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
  87093. if (encoded) {
  87094. value = _decodeURI(value);
  87095. }
  87096. }
  87097. if (multiple) {
  87098. if (!(results[name] && Array.isArray(results[name]))) {
  87099. results[name] = [];
  87100. }
  87101. ;
  87102. results[name].push(value);
  87103. } else {
  87104. results[name] ??= value;
  87105. }
  87106. }
  87107. return key ? results[key] : results;
  87108. };
  87109. getQueryParam = _getQueryParam;
  87110. getQueryParams = (url, key) => {
  87111. return _getQueryParam(url, key, true);
  87112. };
  87113. decodeURIComponent_ = decodeURIComponent;
  87114. }
  87115. });
  87116. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/cookie.js
  87117. var validCookieNameRegEx, validCookieValueRegEx, parse3;
  87118. var init_cookie = __esm({
  87119. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/cookie.js"() {
  87120. init_url();
  87121. validCookieNameRegEx = /^[\w!#$%&'*.^`|~+-]+$/;
  87122. validCookieValueRegEx = /^[ !#-:<-[\]-~]*$/;
  87123. parse3 = (cookie, name) => {
  87124. if (name && cookie.indexOf(name) === -1) {
  87125. return {};
  87126. }
  87127. const pairs = cookie.trim().split(";");
  87128. const parsedCookie = {};
  87129. for (let pairStr of pairs) {
  87130. pairStr = pairStr.trim();
  87131. const valueStartPos = pairStr.indexOf("=");
  87132. if (valueStartPos === -1) {
  87133. continue;
  87134. }
  87135. const cookieName = pairStr.substring(0, valueStartPos).trim();
  87136. if (name && name !== cookieName || !validCookieNameRegEx.test(cookieName)) {
  87137. continue;
  87138. }
  87139. let cookieValue = pairStr.substring(valueStartPos + 1).trim();
  87140. if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {
  87141. cookieValue = cookieValue.slice(1, -1);
  87142. }
  87143. if (validCookieValueRegEx.test(cookieValue)) {
  87144. parsedCookie[cookieName] = decodeURIComponent_(cookieValue);
  87145. if (name) {
  87146. break;
  87147. }
  87148. }
  87149. }
  87150. return parsedCookie;
  87151. };
  87152. }
  87153. });
  87154. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/helper/cookie/index.js
  87155. var getCookie;
  87156. var init_cookie2 = __esm({
  87157. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/helper/cookie/index.js"() {
  87158. init_cookie();
  87159. getCookie = (c3, key, prefix2) => {
  87160. const cookie = c3.req.raw.headers.get("Cookie");
  87161. if (typeof key === "string") {
  87162. if (!cookie) {
  87163. return void 0;
  87164. }
  87165. let finalKey = key;
  87166. if (prefix2 === "secure") {
  87167. finalKey = "__Secure-" + key;
  87168. } else if (prefix2 === "host") {
  87169. finalKey = "__Host-" + key;
  87170. }
  87171. const obj2 = parse3(cookie, finalKey);
  87172. return obj2[finalKey];
  87173. }
  87174. if (!cookie) {
  87175. return {};
  87176. }
  87177. const obj = parse3(cookie);
  87178. return obj;
  87179. };
  87180. }
  87181. });
  87182. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/http-exception.js
  87183. var HTTPException;
  87184. var init_http_exception = __esm({
  87185. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/http-exception.js"() {
  87186. HTTPException = class extends Error {
  87187. res;
  87188. status;
  87189. constructor(status = 500, options) {
  87190. super(options == null ? void 0 : options.message, { cause: options == null ? void 0 : options.cause });
  87191. this.res = options == null ? void 0 : options.res;
  87192. this.status = status;
  87193. }
  87194. getResponse() {
  87195. if (this.res) {
  87196. const newResponse = new Response(this.res.body, {
  87197. status: this.status,
  87198. headers: this.res.headers
  87199. });
  87200. return newResponse;
  87201. }
  87202. return new Response(this.message, {
  87203. status: this.status
  87204. });
  87205. }
  87206. };
  87207. }
  87208. });
  87209. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/crypto.js
  87210. var init_crypto = __esm({
  87211. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/crypto.js"() {
  87212. }
  87213. });
  87214. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/buffer.js
  87215. var bufferToFormData;
  87216. var init_buffer = __esm({
  87217. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/buffer.js"() {
  87218. init_crypto();
  87219. bufferToFormData = (arrayBuffer, contentType) => {
  87220. const response = new Response(arrayBuffer, {
  87221. headers: {
  87222. "Content-Type": contentType
  87223. }
  87224. });
  87225. return response.formData();
  87226. };
  87227. }
  87228. });
  87229. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/validator.js
  87230. var jsonRegex, multipartRegex, urlencodedRegex, validator;
  87231. var init_validator = __esm({
  87232. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/validator.js"() {
  87233. init_cookie2();
  87234. init_http_exception();
  87235. init_buffer();
  87236. jsonRegex = /^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
  87237. multipartRegex = /^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/;
  87238. urlencodedRegex = /^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/;
  87239. validator = (target, validationFunc) => {
  87240. return async (c3, next) => {
  87241. let value = {};
  87242. const contentType = c3.req.header("Content-Type");
  87243. switch (target) {
  87244. case "json":
  87245. if (!contentType || !jsonRegex.test(contentType)) {
  87246. break;
  87247. }
  87248. try {
  87249. value = await c3.req.json();
  87250. } catch {
  87251. const message = "Malformed JSON in request body";
  87252. throw new HTTPException(400, { message });
  87253. }
  87254. break;
  87255. case "form": {
  87256. if (!contentType || !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType))) {
  87257. break;
  87258. }
  87259. let formData;
  87260. if (c3.req.bodyCache.formData) {
  87261. formData = await c3.req.bodyCache.formData;
  87262. } else {
  87263. try {
  87264. const arrayBuffer = await c3.req.arrayBuffer();
  87265. formData = await bufferToFormData(arrayBuffer, contentType);
  87266. c3.req.bodyCache.formData = formData;
  87267. } catch (e4) {
  87268. let message = "Malformed FormData request.";
  87269. message += e4 instanceof Error ? ` ${e4.message}` : ` ${String(e4)}`;
  87270. throw new HTTPException(400, { message });
  87271. }
  87272. }
  87273. const form = {};
  87274. formData.forEach((value2, key) => {
  87275. if (key.endsWith("[]")) {
  87276. ;
  87277. (form[key] ??= []).push(value2);
  87278. } else if (Array.isArray(form[key])) {
  87279. ;
  87280. form[key].push(value2);
  87281. } else if (key in form) {
  87282. form[key] = [form[key], value2];
  87283. } else {
  87284. form[key] = value2;
  87285. }
  87286. });
  87287. value = form;
  87288. break;
  87289. }
  87290. case "query":
  87291. value = Object.fromEntries(
  87292. Object.entries(c3.req.queries()).map(([k3, v6]) => {
  87293. return v6.length === 1 ? [k3, v6[0]] : [k3, v6];
  87294. })
  87295. );
  87296. break;
  87297. case "param":
  87298. value = c3.req.param();
  87299. break;
  87300. case "header":
  87301. value = c3.req.header();
  87302. break;
  87303. case "cookie":
  87304. value = getCookie(c3);
  87305. break;
  87306. }
  87307. const res = await validationFunc(value, c3);
  87308. if (res instanceof Response) {
  87309. return res;
  87310. }
  87311. c3.req.addValidatedData(target, res);
  87312. await next();
  87313. };
  87314. };
  87315. }
  87316. });
  87317. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/index.js
  87318. var init_validator2 = __esm({
  87319. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/validator/index.js"() {
  87320. init_validator();
  87321. }
  87322. });
  87323. // ../node_modules/.pnpm/@hono+zod-validator@0.2.2_hono@4.7.10_zod@3.25.42/node_modules/@hono/zod-validator/dist/esm/index.js
  87324. var zValidator;
  87325. var init_esm2 = __esm({
  87326. "../node_modules/.pnpm/@hono+zod-validator@0.2.2_hono@4.7.10_zod@3.25.42/node_modules/@hono/zod-validator/dist/esm/index.js"() {
  87327. init_validator2();
  87328. zValidator = (target, schema6, hook) => (
  87329. // @ts-expect-error not typed well
  87330. validator(target, async (value, c3) => {
  87331. const result = await schema6.safeParseAsync(value);
  87332. if (hook) {
  87333. const hookResult = await hook({ data: value, ...result }, c3);
  87334. if (hookResult) {
  87335. if (hookResult instanceof Response) {
  87336. return hookResult;
  87337. }
  87338. if ("response" in hookResult) {
  87339. return hookResult.response;
  87340. }
  87341. }
  87342. }
  87343. if (!result.success) {
  87344. return c3.json(result, 400);
  87345. }
  87346. return result.data;
  87347. })
  87348. );
  87349. }
  87350. });
  87351. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/compose.js
  87352. var compose;
  87353. var init_compose = __esm({
  87354. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/compose.js"() {
  87355. compose = (middleware, onError, onNotFound) => {
  87356. return (context, next) => {
  87357. let index6 = -1;
  87358. return dispatch(0);
  87359. async function dispatch(i4) {
  87360. if (i4 <= index6) {
  87361. throw new Error("next() called multiple times");
  87362. }
  87363. index6 = i4;
  87364. let res;
  87365. let isError = false;
  87366. let handler;
  87367. if (middleware[i4]) {
  87368. handler = middleware[i4][0][0];
  87369. context.req.routeIndex = i4;
  87370. } else {
  87371. handler = i4 === middleware.length && next || void 0;
  87372. }
  87373. if (handler) {
  87374. try {
  87375. res = await handler(context, () => dispatch(i4 + 1));
  87376. } catch (err2) {
  87377. if (err2 instanceof Error && onError) {
  87378. context.error = err2;
  87379. res = await onError(err2, context);
  87380. isError = true;
  87381. } else {
  87382. throw err2;
  87383. }
  87384. }
  87385. } else {
  87386. if (context.finalized === false && onNotFound) {
  87387. res = await onNotFound(context);
  87388. }
  87389. }
  87390. if (res && (context.finalized === false || isError)) {
  87391. context.res = res;
  87392. }
  87393. return context;
  87394. }
  87395. };
  87396. };
  87397. }
  87398. });
  87399. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/body.js
  87400. async function parseFormData(request, options) {
  87401. const formData = await request.formData();
  87402. if (formData) {
  87403. return convertFormDataToBodyData(formData, options);
  87404. }
  87405. return {};
  87406. }
  87407. function convertFormDataToBodyData(formData, options) {
  87408. const form = /* @__PURE__ */ Object.create(null);
  87409. formData.forEach((value, key) => {
  87410. const shouldParseAllValues = options.all || key.endsWith("[]");
  87411. if (!shouldParseAllValues) {
  87412. form[key] = value;
  87413. } else {
  87414. handleParsingAllValues(form, key, value);
  87415. }
  87416. });
  87417. if (options.dot) {
  87418. Object.entries(form).forEach(([key, value]) => {
  87419. const shouldParseDotValues = key.includes(".");
  87420. if (shouldParseDotValues) {
  87421. handleParsingNestedValues(form, key, value);
  87422. delete form[key];
  87423. }
  87424. });
  87425. }
  87426. return form;
  87427. }
  87428. var parseBody, handleParsingAllValues, handleParsingNestedValues;
  87429. var init_body2 = __esm({
  87430. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/body.js"() {
  87431. init_request2();
  87432. parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
  87433. const { all = false, dot = false } = options;
  87434. const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
  87435. const contentType = headers.get("Content-Type");
  87436. if ((contentType == null ? void 0 : contentType.startsWith("multipart/form-data")) || (contentType == null ? void 0 : contentType.startsWith("application/x-www-form-urlencoded"))) {
  87437. return parseFormData(request, { all, dot });
  87438. }
  87439. return {};
  87440. };
  87441. handleParsingAllValues = (form, key, value) => {
  87442. if (form[key] !== void 0) {
  87443. if (Array.isArray(form[key])) {
  87444. ;
  87445. form[key].push(value);
  87446. } else {
  87447. form[key] = [form[key], value];
  87448. }
  87449. } else {
  87450. form[key] = value;
  87451. }
  87452. };
  87453. handleParsingNestedValues = (form, key, value) => {
  87454. let nestedForm = form;
  87455. const keys = key.split(".");
  87456. keys.forEach((key2, index6) => {
  87457. if (index6 === keys.length - 1) {
  87458. nestedForm[key2] = value;
  87459. } else {
  87460. if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
  87461. nestedForm[key2] = /* @__PURE__ */ Object.create(null);
  87462. }
  87463. nestedForm = nestedForm[key2];
  87464. }
  87465. });
  87466. };
  87467. }
  87468. });
  87469. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/request.js
  87470. var tryDecodeURIComponent, HonoRequest;
  87471. var init_request2 = __esm({
  87472. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/request.js"() {
  87473. init_body2();
  87474. init_url();
  87475. tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
  87476. HonoRequest = class {
  87477. raw;
  87478. #validatedData;
  87479. #matchResult;
  87480. routeIndex = 0;
  87481. path;
  87482. bodyCache = {};
  87483. constructor(request, path4 = "/", matchResult = [[]]) {
  87484. this.raw = request;
  87485. this.path = path4;
  87486. this.#matchResult = matchResult;
  87487. this.#validatedData = {};
  87488. }
  87489. param(key) {
  87490. return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
  87491. }
  87492. #getDecodedParam(key) {
  87493. const paramKey = this.#matchResult[0][this.routeIndex][1][key];
  87494. const param = this.#getParamValue(paramKey);
  87495. return param ? /\%/.test(param) ? tryDecodeURIComponent(param) : param : void 0;
  87496. }
  87497. #getAllDecodedParams() {
  87498. const decoded = {};
  87499. const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
  87500. for (const key of keys) {
  87501. const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
  87502. if (value && typeof value === "string") {
  87503. decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
  87504. }
  87505. }
  87506. return decoded;
  87507. }
  87508. #getParamValue(paramKey) {
  87509. return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
  87510. }
  87511. query(key) {
  87512. return getQueryParam(this.url, key);
  87513. }
  87514. queries(key) {
  87515. return getQueryParams(this.url, key);
  87516. }
  87517. header(name) {
  87518. if (name) {
  87519. return this.raw.headers.get(name) ?? void 0;
  87520. }
  87521. const headerData = {};
  87522. this.raw.headers.forEach((value, key) => {
  87523. headerData[key] = value;
  87524. });
  87525. return headerData;
  87526. }
  87527. async parseBody(options) {
  87528. return this.bodyCache.parsedBody ??= await parseBody(this, options);
  87529. }
  87530. #cachedBody = (key) => {
  87531. const { bodyCache, raw: raw2 } = this;
  87532. const cachedBody = bodyCache[key];
  87533. if (cachedBody) {
  87534. return cachedBody;
  87535. }
  87536. const anyCachedKey = Object.keys(bodyCache)[0];
  87537. if (anyCachedKey) {
  87538. return bodyCache[anyCachedKey].then((body) => {
  87539. if (anyCachedKey === "json") {
  87540. body = JSON.stringify(body);
  87541. }
  87542. return new Response(body)[key]();
  87543. });
  87544. }
  87545. return bodyCache[key] = raw2[key]();
  87546. };
  87547. json() {
  87548. return this.#cachedBody("json");
  87549. }
  87550. text() {
  87551. return this.#cachedBody("text");
  87552. }
  87553. arrayBuffer() {
  87554. return this.#cachedBody("arrayBuffer");
  87555. }
  87556. blob() {
  87557. return this.#cachedBody("blob");
  87558. }
  87559. formData() {
  87560. return this.#cachedBody("formData");
  87561. }
  87562. addValidatedData(target, data) {
  87563. this.#validatedData[target] = data;
  87564. }
  87565. valid(target) {
  87566. return this.#validatedData[target];
  87567. }
  87568. get url() {
  87569. return this.raw.url;
  87570. }
  87571. get method() {
  87572. return this.raw.method;
  87573. }
  87574. get matchedRoutes() {
  87575. return this.#matchResult[0].map(([[, route]]) => route);
  87576. }
  87577. get routePath() {
  87578. return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
  87579. }
  87580. };
  87581. }
  87582. });
  87583. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/html.js
  87584. var HtmlEscapedCallbackPhase, raw, resolveCallback;
  87585. var init_html = __esm({
  87586. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/html.js"() {
  87587. HtmlEscapedCallbackPhase = {
  87588. Stringify: 1,
  87589. BeforeStream: 2,
  87590. Stream: 3
  87591. };
  87592. raw = (value, callbacks) => {
  87593. const escapedString = new String(value);
  87594. escapedString.isEscaped = true;
  87595. escapedString.callbacks = callbacks;
  87596. return escapedString;
  87597. };
  87598. resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
  87599. if (typeof str === "object" && !(str instanceof String)) {
  87600. if (!(str instanceof Promise)) {
  87601. str = str.toString();
  87602. }
  87603. if (str instanceof Promise) {
  87604. str = await str;
  87605. }
  87606. }
  87607. const callbacks = str.callbacks;
  87608. if (!(callbacks == null ? void 0 : callbacks.length)) {
  87609. return Promise.resolve(str);
  87610. }
  87611. if (buffer) {
  87612. buffer[0] += str;
  87613. } else {
  87614. buffer = [str];
  87615. }
  87616. const resStr = Promise.all(callbacks.map((c3) => c3({ phase, buffer, context }))).then(
  87617. (res) => Promise.all(
  87618. res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
  87619. ).then(() => buffer[0])
  87620. );
  87621. if (preserveCallbacks) {
  87622. return raw(await resStr, callbacks);
  87623. } else {
  87624. return resStr;
  87625. }
  87626. };
  87627. }
  87628. });
  87629. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/context.js
  87630. var TEXT_PLAIN, setHeaders, Context;
  87631. var init_context = __esm({
  87632. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/context.js"() {
  87633. init_request2();
  87634. init_html();
  87635. TEXT_PLAIN = "text/plain; charset=UTF-8";
  87636. setHeaders = (headers, map2 = {}) => {
  87637. for (const key of Object.keys(map2)) {
  87638. headers.set(key, map2[key]);
  87639. }
  87640. return headers;
  87641. };
  87642. Context = class {
  87643. #rawRequest;
  87644. #req;
  87645. env = {};
  87646. #var;
  87647. finalized = false;
  87648. error;
  87649. #status = 200;
  87650. #executionCtx;
  87651. #headers;
  87652. #preparedHeaders;
  87653. #res;
  87654. #isFresh = true;
  87655. #layout;
  87656. #renderer;
  87657. #notFoundHandler;
  87658. #matchResult;
  87659. #path;
  87660. constructor(req, options) {
  87661. this.#rawRequest = req;
  87662. if (options) {
  87663. this.#executionCtx = options.executionCtx;
  87664. this.env = options.env;
  87665. this.#notFoundHandler = options.notFoundHandler;
  87666. this.#path = options.path;
  87667. this.#matchResult = options.matchResult;
  87668. }
  87669. }
  87670. get req() {
  87671. this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
  87672. return this.#req;
  87673. }
  87674. get event() {
  87675. if (this.#executionCtx && "respondWith" in this.#executionCtx) {
  87676. return this.#executionCtx;
  87677. } else {
  87678. throw Error("This context has no FetchEvent");
  87679. }
  87680. }
  87681. get executionCtx() {
  87682. if (this.#executionCtx) {
  87683. return this.#executionCtx;
  87684. } else {
  87685. throw Error("This context has no ExecutionContext");
  87686. }
  87687. }
  87688. get res() {
  87689. this.#isFresh = false;
  87690. return this.#res ||= new Response("404 Not Found", { status: 404 });
  87691. }
  87692. set res(_res) {
  87693. this.#isFresh = false;
  87694. if (this.#res && _res) {
  87695. _res = new Response(_res.body, _res);
  87696. for (const [k3, v6] of this.#res.headers.entries()) {
  87697. if (k3 === "content-type") {
  87698. continue;
  87699. }
  87700. if (k3 === "set-cookie") {
  87701. const cookies = this.#res.headers.getSetCookie();
  87702. _res.headers.delete("set-cookie");
  87703. for (const cookie of cookies) {
  87704. _res.headers.append("set-cookie", cookie);
  87705. }
  87706. } else {
  87707. _res.headers.set(k3, v6);
  87708. }
  87709. }
  87710. }
  87711. this.#res = _res;
  87712. this.finalized = true;
  87713. }
  87714. render = (...args) => {
  87715. this.#renderer ??= (content) => this.html(content);
  87716. return this.#renderer(...args);
  87717. };
  87718. setLayout = (layout) => this.#layout = layout;
  87719. getLayout = () => this.#layout;
  87720. setRenderer = (renderer) => {
  87721. this.#renderer = renderer;
  87722. };
  87723. header = (name, value, options) => {
  87724. if (this.finalized) {
  87725. this.#res = new Response(this.#res.body, this.#res);
  87726. }
  87727. if (value === void 0) {
  87728. if (this.#headers) {
  87729. this.#headers.delete(name);
  87730. } else if (this.#preparedHeaders) {
  87731. delete this.#preparedHeaders[name.toLocaleLowerCase()];
  87732. }
  87733. if (this.finalized) {
  87734. this.res.headers.delete(name);
  87735. }
  87736. return;
  87737. }
  87738. if (options == null ? void 0 : options.append) {
  87739. if (!this.#headers) {
  87740. this.#isFresh = false;
  87741. this.#headers = new Headers(this.#preparedHeaders);
  87742. this.#preparedHeaders = {};
  87743. }
  87744. this.#headers.append(name, value);
  87745. } else {
  87746. if (this.#headers) {
  87747. this.#headers.set(name, value);
  87748. } else {
  87749. this.#preparedHeaders ??= {};
  87750. this.#preparedHeaders[name.toLowerCase()] = value;
  87751. }
  87752. }
  87753. if (this.finalized) {
  87754. if (options == null ? void 0 : options.append) {
  87755. this.res.headers.append(name, value);
  87756. } else {
  87757. this.res.headers.set(name, value);
  87758. }
  87759. }
  87760. };
  87761. status = (status) => {
  87762. this.#isFresh = false;
  87763. this.#status = status;
  87764. };
  87765. set = (key, value) => {
  87766. this.#var ??= /* @__PURE__ */ new Map();
  87767. this.#var.set(key, value);
  87768. };
  87769. get = (key) => {
  87770. return this.#var ? this.#var.get(key) : void 0;
  87771. };
  87772. get var() {
  87773. if (!this.#var) {
  87774. return {};
  87775. }
  87776. return Object.fromEntries(this.#var);
  87777. }
  87778. #newResponse(data, arg, headers) {
  87779. if (this.#isFresh && !headers && !arg && this.#status === 200) {
  87780. return new Response(data, {
  87781. headers: this.#preparedHeaders
  87782. });
  87783. }
  87784. if (arg && typeof arg !== "number") {
  87785. const header = new Headers(arg.headers);
  87786. if (this.#headers) {
  87787. this.#headers.forEach((v6, k3) => {
  87788. if (k3 === "set-cookie") {
  87789. header.append(k3, v6);
  87790. } else {
  87791. header.set(k3, v6);
  87792. }
  87793. });
  87794. }
  87795. const headers2 = setHeaders(header, this.#preparedHeaders);
  87796. return new Response(data, {
  87797. headers: headers2,
  87798. status: arg.status ?? this.#status
  87799. });
  87800. }
  87801. const status = typeof arg === "number" ? arg : this.#status;
  87802. this.#preparedHeaders ??= {};
  87803. this.#headers ??= new Headers();
  87804. setHeaders(this.#headers, this.#preparedHeaders);
  87805. if (this.#res) {
  87806. this.#res.headers.forEach((v6, k3) => {
  87807. var _a2, _b;
  87808. if (k3 === "set-cookie") {
  87809. (_a2 = this.#headers) == null ? void 0 : _a2.append(k3, v6);
  87810. } else {
  87811. (_b = this.#headers) == null ? void 0 : _b.set(k3, v6);
  87812. }
  87813. });
  87814. setHeaders(this.#headers, this.#preparedHeaders);
  87815. }
  87816. headers ??= {};
  87817. for (const [k3, v6] of Object.entries(headers)) {
  87818. if (typeof v6 === "string") {
  87819. this.#headers.set(k3, v6);
  87820. } else {
  87821. this.#headers.delete(k3);
  87822. for (const v22 of v6) {
  87823. this.#headers.append(k3, v22);
  87824. }
  87825. }
  87826. }
  87827. return new Response(data, {
  87828. status,
  87829. headers: this.#headers
  87830. });
  87831. }
  87832. newResponse = (...args) => this.#newResponse(...args);
  87833. body = (data, arg, headers) => {
  87834. return typeof arg === "number" ? this.#newResponse(data, arg, headers) : this.#newResponse(data, arg);
  87835. };
  87836. text = (text, arg, headers) => {
  87837. if (!this.#preparedHeaders) {
  87838. if (this.#isFresh && !headers && !arg) {
  87839. return new Response(text);
  87840. }
  87841. this.#preparedHeaders = {};
  87842. }
  87843. this.#preparedHeaders["content-type"] = TEXT_PLAIN;
  87844. if (typeof arg === "number") {
  87845. return this.#newResponse(text, arg, headers);
  87846. }
  87847. return this.#newResponse(text, arg);
  87848. };
  87849. json = (object, arg, headers) => {
  87850. const body = JSON.stringify(object);
  87851. this.#preparedHeaders ??= {};
  87852. this.#preparedHeaders["content-type"] = "application/json";
  87853. return typeof arg === "number" ? this.#newResponse(body, arg, headers) : this.#newResponse(body, arg);
  87854. };
  87855. html = (html, arg, headers) => {
  87856. this.#preparedHeaders ??= {};
  87857. this.#preparedHeaders["content-type"] = "text/html; charset=UTF-8";
  87858. if (typeof html === "object") {
  87859. return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html2) => {
  87860. return typeof arg === "number" ? this.#newResponse(html2, arg, headers) : this.#newResponse(html2, arg);
  87861. });
  87862. }
  87863. return typeof arg === "number" ? this.#newResponse(html, arg, headers) : this.#newResponse(html, arg);
  87864. };
  87865. redirect = (location, status) => {
  87866. this.#headers ??= new Headers();
  87867. this.#headers.set("Location", String(location));
  87868. return this.newResponse(null, status ?? 302);
  87869. };
  87870. notFound = () => {
  87871. this.#notFoundHandler ??= () => new Response();
  87872. return this.#notFoundHandler(this);
  87873. };
  87874. };
  87875. }
  87876. });
  87877. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router.js
  87878. var METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS, MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError;
  87879. var init_router = __esm({
  87880. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router.js"() {
  87881. METHOD_NAME_ALL = "ALL";
  87882. METHOD_NAME_ALL_LOWERCASE = "all";
  87883. METHODS = ["get", "post", "put", "delete", "options", "patch"];
  87884. MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
  87885. UnsupportedPathError = class extends Error {
  87886. };
  87887. }
  87888. });
  87889. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/constants.js
  87890. var COMPOSED_HANDLER;
  87891. var init_constants = __esm({
  87892. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/constants.js"() {
  87893. COMPOSED_HANDLER = "__COMPOSED_HANDLER";
  87894. }
  87895. });
  87896. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono-base.js
  87897. var notFoundHandler, errorHandler, Hono;
  87898. var init_hono_base = __esm({
  87899. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono-base.js"() {
  87900. init_compose();
  87901. init_context();
  87902. init_router();
  87903. init_constants();
  87904. init_url();
  87905. notFoundHandler = (c3) => {
  87906. return c3.text("404 Not Found", 404);
  87907. };
  87908. errorHandler = (err2, c3) => {
  87909. if ("getResponse" in err2) {
  87910. return err2.getResponse();
  87911. }
  87912. console.error(err2);
  87913. return c3.text("Internal Server Error", 500);
  87914. };
  87915. Hono = class {
  87916. get;
  87917. post;
  87918. put;
  87919. delete;
  87920. options;
  87921. patch;
  87922. all;
  87923. on;
  87924. use;
  87925. router;
  87926. getPath;
  87927. _basePath = "/";
  87928. #path = "/";
  87929. routes = [];
  87930. constructor(options = {}) {
  87931. const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
  87932. allMethods.forEach((method) => {
  87933. this[method] = (args1, ...args) => {
  87934. if (typeof args1 === "string") {
  87935. this.#path = args1;
  87936. } else {
  87937. this.#addRoute(method, this.#path, args1);
  87938. }
  87939. args.forEach((handler) => {
  87940. this.#addRoute(method, this.#path, handler);
  87941. });
  87942. return this;
  87943. };
  87944. });
  87945. this.on = (method, path4, ...handlers) => {
  87946. for (const p3 of [path4].flat()) {
  87947. this.#path = p3;
  87948. for (const m4 of [method].flat()) {
  87949. handlers.map((handler) => {
  87950. this.#addRoute(m4.toUpperCase(), this.#path, handler);
  87951. });
  87952. }
  87953. }
  87954. return this;
  87955. };
  87956. this.use = (arg1, ...handlers) => {
  87957. if (typeof arg1 === "string") {
  87958. this.#path = arg1;
  87959. } else {
  87960. this.#path = "*";
  87961. handlers.unshift(arg1);
  87962. }
  87963. handlers.forEach((handler) => {
  87964. this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
  87965. });
  87966. return this;
  87967. };
  87968. const { strict, ...optionsWithoutStrict } = options;
  87969. Object.assign(this, optionsWithoutStrict);
  87970. this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
  87971. }
  87972. #clone() {
  87973. const clone2 = new Hono({
  87974. router: this.router,
  87975. getPath: this.getPath
  87976. });
  87977. clone2.errorHandler = this.errorHandler;
  87978. clone2.#notFoundHandler = this.#notFoundHandler;
  87979. clone2.routes = this.routes;
  87980. return clone2;
  87981. }
  87982. #notFoundHandler = notFoundHandler;
  87983. errorHandler = errorHandler;
  87984. route(path4, app) {
  87985. const subApp = this.basePath(path4);
  87986. app.routes.map((r4) => {
  87987. let handler;
  87988. if (app.errorHandler === errorHandler) {
  87989. handler = r4.handler;
  87990. } else {
  87991. handler = async (c3, next) => (await compose([], app.errorHandler)(c3, () => r4.handler(c3, next))).res;
  87992. handler[COMPOSED_HANDLER] = r4.handler;
  87993. }
  87994. subApp.#addRoute(r4.method, r4.path, handler);
  87995. });
  87996. return this;
  87997. }
  87998. basePath(path4) {
  87999. const subApp = this.#clone();
  88000. subApp._basePath = mergePath(this._basePath, path4);
  88001. return subApp;
  88002. }
  88003. onError = (handler) => {
  88004. this.errorHandler = handler;
  88005. return this;
  88006. };
  88007. notFound = (handler) => {
  88008. this.#notFoundHandler = handler;
  88009. return this;
  88010. };
  88011. mount(path4, applicationHandler, options) {
  88012. let replaceRequest;
  88013. let optionHandler;
  88014. if (options) {
  88015. if (typeof options === "function") {
  88016. optionHandler = options;
  88017. } else {
  88018. optionHandler = options.optionHandler;
  88019. if (options.replaceRequest === false) {
  88020. replaceRequest = (request) => request;
  88021. } else {
  88022. replaceRequest = options.replaceRequest;
  88023. }
  88024. }
  88025. }
  88026. const getOptions = optionHandler ? (c3) => {
  88027. const options2 = optionHandler(c3);
  88028. return Array.isArray(options2) ? options2 : [options2];
  88029. } : (c3) => {
  88030. let executionContext = void 0;
  88031. try {
  88032. executionContext = c3.executionCtx;
  88033. } catch {
  88034. }
  88035. return [c3.env, executionContext];
  88036. };
  88037. replaceRequest ||= (() => {
  88038. const mergedPath = mergePath(this._basePath, path4);
  88039. const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
  88040. return (request) => {
  88041. const url = new URL(request.url);
  88042. url.pathname = url.pathname.slice(pathPrefixLength) || "/";
  88043. return new Request(url, request);
  88044. };
  88045. })();
  88046. const handler = async (c3, next) => {
  88047. const res = await applicationHandler(replaceRequest(c3.req.raw), ...getOptions(c3));
  88048. if (res) {
  88049. return res;
  88050. }
  88051. await next();
  88052. };
  88053. this.#addRoute(METHOD_NAME_ALL, mergePath(path4, "*"), handler);
  88054. return this;
  88055. }
  88056. #addRoute(method, path4, handler) {
  88057. method = method.toUpperCase();
  88058. path4 = mergePath(this._basePath, path4);
  88059. const r4 = { path: path4, method, handler };
  88060. this.router.add(method, path4, [handler, r4]);
  88061. this.routes.push(r4);
  88062. }
  88063. #handleError(err2, c3) {
  88064. if (err2 instanceof Error) {
  88065. return this.errorHandler(err2, c3);
  88066. }
  88067. throw err2;
  88068. }
  88069. #dispatch(request, executionCtx, env3, method) {
  88070. if (method === "HEAD") {
  88071. return (async () => new Response(null, await this.#dispatch(request, executionCtx, env3, "GET")))();
  88072. }
  88073. const path4 = this.getPath(request, { env: env3 });
  88074. const matchResult = this.router.match(method, path4);
  88075. const c3 = new Context(request, {
  88076. path: path4,
  88077. matchResult,
  88078. env: env3,
  88079. executionCtx,
  88080. notFoundHandler: this.#notFoundHandler
  88081. });
  88082. if (matchResult[0].length === 1) {
  88083. let res;
  88084. try {
  88085. res = matchResult[0][0][0][0](c3, async () => {
  88086. c3.res = await this.#notFoundHandler(c3);
  88087. });
  88088. } catch (err2) {
  88089. return this.#handleError(err2, c3);
  88090. }
  88091. return res instanceof Promise ? res.then(
  88092. (resolved) => resolved || (c3.finalized ? c3.res : this.#notFoundHandler(c3))
  88093. ).catch((err2) => this.#handleError(err2, c3)) : res ?? this.#notFoundHandler(c3);
  88094. }
  88095. const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
  88096. return (async () => {
  88097. try {
  88098. const context = await composed(c3);
  88099. if (!context.finalized) {
  88100. throw new Error(
  88101. "Context is not finalized. Did you forget to return a Response object or `await next()`?"
  88102. );
  88103. }
  88104. return context.res;
  88105. } catch (err2) {
  88106. return this.#handleError(err2, c3);
  88107. }
  88108. })();
  88109. }
  88110. fetch = (request, ...rest) => {
  88111. return this.#dispatch(request, rest[1], rest[0], request.method);
  88112. };
  88113. request = (input, requestInit, Env, executionCtx) => {
  88114. if (input instanceof Request) {
  88115. return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
  88116. }
  88117. input = input.toString();
  88118. return this.fetch(
  88119. new Request(
  88120. /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
  88121. requestInit
  88122. ),
  88123. Env,
  88124. executionCtx
  88125. );
  88126. };
  88127. fire = () => {
  88128. addEventListener("fetch", (event) => {
  88129. event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
  88130. });
  88131. };
  88132. };
  88133. }
  88134. });
  88135. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/node.js
  88136. function compareKey(a3, b3) {
  88137. if (a3.length === 1) {
  88138. return b3.length === 1 ? a3 < b3 ? -1 : 1 : -1;
  88139. }
  88140. if (b3.length === 1) {
  88141. return 1;
  88142. }
  88143. if (a3 === ONLY_WILDCARD_REG_EXP_STR || a3 === TAIL_WILDCARD_REG_EXP_STR) {
  88144. return 1;
  88145. } else if (b3 === ONLY_WILDCARD_REG_EXP_STR || b3 === TAIL_WILDCARD_REG_EXP_STR) {
  88146. return -1;
  88147. }
  88148. if (a3 === LABEL_REG_EXP_STR) {
  88149. return 1;
  88150. } else if (b3 === LABEL_REG_EXP_STR) {
  88151. return -1;
  88152. }
  88153. return a3.length === b3.length ? a3 < b3 ? -1 : 1 : b3.length - a3.length;
  88154. }
  88155. var LABEL_REG_EXP_STR, ONLY_WILDCARD_REG_EXP_STR, TAIL_WILDCARD_REG_EXP_STR, PATH_ERROR, regExpMetaChars, Node;
  88156. var init_node = __esm({
  88157. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/node.js"() {
  88158. LABEL_REG_EXP_STR = "[^/]+";
  88159. ONLY_WILDCARD_REG_EXP_STR = ".*";
  88160. TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
  88161. PATH_ERROR = Symbol();
  88162. regExpMetaChars = new Set(".\\+*[^]$()");
  88163. Node = class {
  88164. #index;
  88165. #varIndex;
  88166. #children = /* @__PURE__ */ Object.create(null);
  88167. insert(tokens, index6, paramMap, context, pathErrorCheckOnly) {
  88168. if (tokens.length === 0) {
  88169. if (this.#index !== void 0) {
  88170. throw PATH_ERROR;
  88171. }
  88172. if (pathErrorCheckOnly) {
  88173. return;
  88174. }
  88175. this.#index = index6;
  88176. return;
  88177. }
  88178. const [token, ...restTokens] = tokens;
  88179. const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
  88180. let node;
  88181. if (pattern) {
  88182. const name = pattern[1];
  88183. let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
  88184. if (name && pattern[2]) {
  88185. regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
  88186. if (/\((?!\?:)/.test(regexpStr)) {
  88187. throw PATH_ERROR;
  88188. }
  88189. }
  88190. node = this.#children[regexpStr];
  88191. if (!node) {
  88192. if (Object.keys(this.#children).some(
  88193. (k3) => k3 !== ONLY_WILDCARD_REG_EXP_STR && k3 !== TAIL_WILDCARD_REG_EXP_STR
  88194. )) {
  88195. throw PATH_ERROR;
  88196. }
  88197. if (pathErrorCheckOnly) {
  88198. return;
  88199. }
  88200. node = this.#children[regexpStr] = new Node();
  88201. if (name !== "") {
  88202. node.#varIndex = context.varIndex++;
  88203. }
  88204. }
  88205. if (!pathErrorCheckOnly && name !== "") {
  88206. paramMap.push([name, node.#varIndex]);
  88207. }
  88208. } else {
  88209. node = this.#children[token];
  88210. if (!node) {
  88211. if (Object.keys(this.#children).some(
  88212. (k3) => k3.length > 1 && k3 !== ONLY_WILDCARD_REG_EXP_STR && k3 !== TAIL_WILDCARD_REG_EXP_STR
  88213. )) {
  88214. throw PATH_ERROR;
  88215. }
  88216. if (pathErrorCheckOnly) {
  88217. return;
  88218. }
  88219. node = this.#children[token] = new Node();
  88220. }
  88221. }
  88222. node.insert(restTokens, index6, paramMap, context, pathErrorCheckOnly);
  88223. }
  88224. buildRegExpStr() {
  88225. const childKeys = Object.keys(this.#children).sort(compareKey);
  88226. const strList = childKeys.map((k3) => {
  88227. const c3 = this.#children[k3];
  88228. return (typeof c3.#varIndex === "number" ? `(${k3})@${c3.#varIndex}` : regExpMetaChars.has(k3) ? `\\${k3}` : k3) + c3.buildRegExpStr();
  88229. });
  88230. if (typeof this.#index === "number") {
  88231. strList.unshift(`#${this.#index}`);
  88232. }
  88233. if (strList.length === 0) {
  88234. return "";
  88235. }
  88236. if (strList.length === 1) {
  88237. return strList[0];
  88238. }
  88239. return "(?:" + strList.join("|") + ")";
  88240. }
  88241. };
  88242. }
  88243. });
  88244. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/trie.js
  88245. var Trie;
  88246. var init_trie = __esm({
  88247. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/trie.js"() {
  88248. init_node();
  88249. Trie = class {
  88250. #context = { varIndex: 0 };
  88251. #root = new Node();
  88252. insert(path4, index6, pathErrorCheckOnly) {
  88253. const paramAssoc = [];
  88254. const groups = [];
  88255. for (let i4 = 0; ; ) {
  88256. let replaced = false;
  88257. path4 = path4.replace(/\{[^}]+\}/g, (m4) => {
  88258. const mark = `@\\${i4}`;
  88259. groups[i4] = [mark, m4];
  88260. i4++;
  88261. replaced = true;
  88262. return mark;
  88263. });
  88264. if (!replaced) {
  88265. break;
  88266. }
  88267. }
  88268. const tokens = path4.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
  88269. for (let i4 = groups.length - 1; i4 >= 0; i4--) {
  88270. const [mark] = groups[i4];
  88271. for (let j3 = tokens.length - 1; j3 >= 0; j3--) {
  88272. if (tokens[j3].indexOf(mark) !== -1) {
  88273. tokens[j3] = tokens[j3].replace(mark, groups[i4][1]);
  88274. break;
  88275. }
  88276. }
  88277. }
  88278. this.#root.insert(tokens, index6, paramAssoc, this.#context, pathErrorCheckOnly);
  88279. return paramAssoc;
  88280. }
  88281. buildRegExp() {
  88282. let regexp = this.#root.buildRegExpStr();
  88283. if (regexp === "") {
  88284. return [/^$/, [], []];
  88285. }
  88286. let captureIndex = 0;
  88287. const indexReplacementMap = [];
  88288. const paramReplacementMap = [];
  88289. regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_3, handlerIndex, paramIndex) => {
  88290. if (handlerIndex !== void 0) {
  88291. indexReplacementMap[++captureIndex] = Number(handlerIndex);
  88292. return "$()";
  88293. }
  88294. if (paramIndex !== void 0) {
  88295. paramReplacementMap[Number(paramIndex)] = ++captureIndex;
  88296. return "";
  88297. }
  88298. return "";
  88299. });
  88300. return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
  88301. }
  88302. };
  88303. }
  88304. });
  88305. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/router.js
  88306. function buildWildcardRegExp(path4) {
  88307. return wildcardRegExpCache[path4] ??= new RegExp(
  88308. path4 === "*" ? "" : `^${path4.replace(
  88309. /\/\*$|([.\\+*[^\]$()])/g,
  88310. (_3, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
  88311. )}$`
  88312. );
  88313. }
  88314. function clearWildcardRegExpCache() {
  88315. wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
  88316. }
  88317. function buildMatcherFromPreprocessedRoutes(routes) {
  88318. var _a2;
  88319. const trie = new Trie();
  88320. const handlerData = [];
  88321. if (routes.length === 0) {
  88322. return nullMatcher;
  88323. }
  88324. const routesWithStaticPathFlag = routes.map(
  88325. (route) => [!/\*|\/:/.test(route[0]), ...route]
  88326. ).sort(
  88327. ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
  88328. );
  88329. const staticMap = /* @__PURE__ */ Object.create(null);
  88330. for (let i4 = 0, j3 = -1, len = routesWithStaticPathFlag.length; i4 < len; i4++) {
  88331. const [pathErrorCheckOnly, path4, handlers] = routesWithStaticPathFlag[i4];
  88332. if (pathErrorCheckOnly) {
  88333. staticMap[path4] = [handlers.map(([h4]) => [h4, /* @__PURE__ */ Object.create(null)]), emptyParam];
  88334. } else {
  88335. j3++;
  88336. }
  88337. let paramAssoc;
  88338. try {
  88339. paramAssoc = trie.insert(path4, j3, pathErrorCheckOnly);
  88340. } catch (e4) {
  88341. throw e4 === PATH_ERROR ? new UnsupportedPathError(path4) : e4;
  88342. }
  88343. if (pathErrorCheckOnly) {
  88344. continue;
  88345. }
  88346. handlerData[j3] = handlers.map(([h4, paramCount]) => {
  88347. const paramIndexMap = /* @__PURE__ */ Object.create(null);
  88348. paramCount -= 1;
  88349. for (; paramCount >= 0; paramCount--) {
  88350. const [key, value] = paramAssoc[paramCount];
  88351. paramIndexMap[key] = value;
  88352. }
  88353. return [h4, paramIndexMap];
  88354. });
  88355. }
  88356. const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
  88357. for (let i4 = 0, len = handlerData.length; i4 < len; i4++) {
  88358. for (let j3 = 0, len2 = handlerData[i4].length; j3 < len2; j3++) {
  88359. const map2 = (_a2 = handlerData[i4][j3]) == null ? void 0 : _a2[1];
  88360. if (!map2) {
  88361. continue;
  88362. }
  88363. const keys = Object.keys(map2);
  88364. for (let k3 = 0, len3 = keys.length; k3 < len3; k3++) {
  88365. map2[keys[k3]] = paramReplacementMap[map2[keys[k3]]];
  88366. }
  88367. }
  88368. }
  88369. const handlerMap = [];
  88370. for (const i4 in indexReplacementMap) {
  88371. handlerMap[i4] = handlerData[indexReplacementMap[i4]];
  88372. }
  88373. return [regexp, handlerMap, staticMap];
  88374. }
  88375. function findMiddleware(middleware, path4) {
  88376. if (!middleware) {
  88377. return void 0;
  88378. }
  88379. for (const k3 of Object.keys(middleware).sort((a3, b3) => b3.length - a3.length)) {
  88380. if (buildWildcardRegExp(k3).test(path4)) {
  88381. return [...middleware[k3]];
  88382. }
  88383. }
  88384. return void 0;
  88385. }
  88386. var emptyParam, nullMatcher, wildcardRegExpCache, RegExpRouter;
  88387. var init_router2 = __esm({
  88388. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/router.js"() {
  88389. init_router();
  88390. init_url();
  88391. init_node();
  88392. init_trie();
  88393. emptyParam = [];
  88394. nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
  88395. wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
  88396. RegExpRouter = class {
  88397. name = "RegExpRouter";
  88398. #middleware;
  88399. #routes;
  88400. constructor() {
  88401. this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
  88402. this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
  88403. }
  88404. add(method, path4, handler) {
  88405. const middleware = this.#middleware;
  88406. const routes = this.#routes;
  88407. if (!middleware || !routes) {
  88408. throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
  88409. }
  88410. if (!middleware[method]) {
  88411. ;
  88412. [middleware, routes].forEach((handlerMap) => {
  88413. handlerMap[method] = /* @__PURE__ */ Object.create(null);
  88414. Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p3) => {
  88415. handlerMap[method][p3] = [...handlerMap[METHOD_NAME_ALL][p3]];
  88416. });
  88417. });
  88418. }
  88419. if (path4 === "/*") {
  88420. path4 = "*";
  88421. }
  88422. const paramCount = (path4.match(/\/:/g) || []).length;
  88423. if (/\*$/.test(path4)) {
  88424. const re = buildWildcardRegExp(path4);
  88425. if (method === METHOD_NAME_ALL) {
  88426. Object.keys(middleware).forEach((m4) => {
  88427. middleware[m4][path4] ||= findMiddleware(middleware[m4], path4) || findMiddleware(middleware[METHOD_NAME_ALL], path4) || [];
  88428. });
  88429. } else {
  88430. middleware[method][path4] ||= findMiddleware(middleware[method], path4) || findMiddleware(middleware[METHOD_NAME_ALL], path4) || [];
  88431. }
  88432. Object.keys(middleware).forEach((m4) => {
  88433. if (method === METHOD_NAME_ALL || method === m4) {
  88434. Object.keys(middleware[m4]).forEach((p3) => {
  88435. re.test(p3) && middleware[m4][p3].push([handler, paramCount]);
  88436. });
  88437. }
  88438. });
  88439. Object.keys(routes).forEach((m4) => {
  88440. if (method === METHOD_NAME_ALL || method === m4) {
  88441. Object.keys(routes[m4]).forEach(
  88442. (p3) => re.test(p3) && routes[m4][p3].push([handler, paramCount])
  88443. );
  88444. }
  88445. });
  88446. return;
  88447. }
  88448. const paths = checkOptionalParameter(path4) || [path4];
  88449. for (let i4 = 0, len = paths.length; i4 < len; i4++) {
  88450. const path22 = paths[i4];
  88451. Object.keys(routes).forEach((m4) => {
  88452. if (method === METHOD_NAME_ALL || method === m4) {
  88453. routes[m4][path22] ||= [
  88454. ...findMiddleware(middleware[m4], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || []
  88455. ];
  88456. routes[m4][path22].push([handler, paramCount - len + i4 + 1]);
  88457. }
  88458. });
  88459. }
  88460. }
  88461. match(method, path4) {
  88462. clearWildcardRegExpCache();
  88463. const matchers = this.#buildAllMatchers();
  88464. this.match = (method2, path22) => {
  88465. const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
  88466. const staticMatch = matcher[2][path22];
  88467. if (staticMatch) {
  88468. return staticMatch;
  88469. }
  88470. const match2 = path22.match(matcher[0]);
  88471. if (!match2) {
  88472. return [[], emptyParam];
  88473. }
  88474. const index6 = match2.indexOf("", 1);
  88475. return [matcher[1][index6], match2];
  88476. };
  88477. return this.match(method, path4);
  88478. }
  88479. #buildAllMatchers() {
  88480. const matchers = /* @__PURE__ */ Object.create(null);
  88481. Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
  88482. matchers[method] ||= this.#buildMatcher(method);
  88483. });
  88484. this.#middleware = this.#routes = void 0;
  88485. return matchers;
  88486. }
  88487. #buildMatcher(method) {
  88488. const routes = [];
  88489. let hasOwnRoute = method === METHOD_NAME_ALL;
  88490. [this.#middleware, this.#routes].forEach((r4) => {
  88491. const ownRoute = r4[method] ? Object.keys(r4[method]).map((path4) => [path4, r4[method][path4]]) : [];
  88492. if (ownRoute.length !== 0) {
  88493. hasOwnRoute ||= true;
  88494. routes.push(...ownRoute);
  88495. } else if (method !== METHOD_NAME_ALL) {
  88496. routes.push(
  88497. ...Object.keys(r4[METHOD_NAME_ALL]).map((path4) => [path4, r4[METHOD_NAME_ALL][path4]])
  88498. );
  88499. }
  88500. });
  88501. if (!hasOwnRoute) {
  88502. return null;
  88503. } else {
  88504. return buildMatcherFromPreprocessedRoutes(routes);
  88505. }
  88506. }
  88507. };
  88508. }
  88509. });
  88510. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/index.js
  88511. var init_reg_exp_router = __esm({
  88512. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/reg-exp-router/index.js"() {
  88513. init_router2();
  88514. }
  88515. });
  88516. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/router.js
  88517. var SmartRouter;
  88518. var init_router3 = __esm({
  88519. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/router.js"() {
  88520. init_router();
  88521. SmartRouter = class {
  88522. name = "SmartRouter";
  88523. #routers = [];
  88524. #routes = [];
  88525. constructor(init2) {
  88526. this.#routers = init2.routers;
  88527. }
  88528. add(method, path4, handler) {
  88529. if (!this.#routes) {
  88530. throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
  88531. }
  88532. this.#routes.push([method, path4, handler]);
  88533. }
  88534. match(method, path4) {
  88535. if (!this.#routes) {
  88536. throw new Error("Fatal error");
  88537. }
  88538. const routers = this.#routers;
  88539. const routes = this.#routes;
  88540. const len = routers.length;
  88541. let i4 = 0;
  88542. let res;
  88543. for (; i4 < len; i4++) {
  88544. const router = routers[i4];
  88545. try {
  88546. for (let i22 = 0, len2 = routes.length; i22 < len2; i22++) {
  88547. router.add(...routes[i22]);
  88548. }
  88549. res = router.match(method, path4);
  88550. } catch (e4) {
  88551. if (e4 instanceof UnsupportedPathError) {
  88552. continue;
  88553. }
  88554. throw e4;
  88555. }
  88556. this.match = router.match.bind(router);
  88557. this.#routers = [router];
  88558. this.#routes = void 0;
  88559. break;
  88560. }
  88561. if (i4 === len) {
  88562. throw new Error("Fatal error");
  88563. }
  88564. this.name = `SmartRouter + ${this.activeRouter.name}`;
  88565. return res;
  88566. }
  88567. get activeRouter() {
  88568. if (this.#routes || this.#routers.length !== 1) {
  88569. throw new Error("No active router has been determined yet.");
  88570. }
  88571. return this.#routers[0];
  88572. }
  88573. };
  88574. }
  88575. });
  88576. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/index.js
  88577. var init_smart_router = __esm({
  88578. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/smart-router/index.js"() {
  88579. init_router3();
  88580. }
  88581. });
  88582. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/node.js
  88583. var emptyParams, Node2;
  88584. var init_node2 = __esm({
  88585. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/node.js"() {
  88586. init_router();
  88587. init_url();
  88588. emptyParams = /* @__PURE__ */ Object.create(null);
  88589. Node2 = class {
  88590. #methods;
  88591. #children;
  88592. #patterns;
  88593. #order = 0;
  88594. #params = emptyParams;
  88595. constructor(method, handler, children) {
  88596. this.#children = children || /* @__PURE__ */ Object.create(null);
  88597. this.#methods = [];
  88598. if (method && handler) {
  88599. const m4 = /* @__PURE__ */ Object.create(null);
  88600. m4[method] = { handler, possibleKeys: [], score: 0 };
  88601. this.#methods = [m4];
  88602. }
  88603. this.#patterns = [];
  88604. }
  88605. insert(method, path4, handler) {
  88606. this.#order = ++this.#order;
  88607. let curNode = this;
  88608. const parts = splitRoutingPath(path4);
  88609. const possibleKeys = [];
  88610. for (let i4 = 0, len = parts.length; i4 < len; i4++) {
  88611. const p3 = parts[i4];
  88612. const nextP = parts[i4 + 1];
  88613. const pattern = getPattern(p3, nextP);
  88614. const key = Array.isArray(pattern) ? pattern[0] : p3;
  88615. if (Object.keys(curNode.#children).includes(key)) {
  88616. curNode = curNode.#children[key];
  88617. const pattern2 = getPattern(p3, nextP);
  88618. if (pattern2) {
  88619. possibleKeys.push(pattern2[1]);
  88620. }
  88621. continue;
  88622. }
  88623. curNode.#children[key] = new Node2();
  88624. if (pattern) {
  88625. curNode.#patterns.push(pattern);
  88626. possibleKeys.push(pattern[1]);
  88627. }
  88628. curNode = curNode.#children[key];
  88629. }
  88630. const m4 = /* @__PURE__ */ Object.create(null);
  88631. const handlerSet = {
  88632. handler,
  88633. possibleKeys: possibleKeys.filter((v6, i4, a3) => a3.indexOf(v6) === i4),
  88634. score: this.#order
  88635. };
  88636. m4[method] = handlerSet;
  88637. curNode.#methods.push(m4);
  88638. return curNode;
  88639. }
  88640. #getHandlerSets(node, method, nodeParams, params) {
  88641. const handlerSets = [];
  88642. for (let i4 = 0, len = node.#methods.length; i4 < len; i4++) {
  88643. const m4 = node.#methods[i4];
  88644. const handlerSet = m4[method] || m4[METHOD_NAME_ALL];
  88645. const processedSet = {};
  88646. if (handlerSet !== void 0) {
  88647. handlerSet.params = /* @__PURE__ */ Object.create(null);
  88648. handlerSets.push(handlerSet);
  88649. if (nodeParams !== emptyParams || params && params !== emptyParams) {
  88650. for (let i22 = 0, len2 = handlerSet.possibleKeys.length; i22 < len2; i22++) {
  88651. const key = handlerSet.possibleKeys[i22];
  88652. const processed = processedSet[handlerSet.score];
  88653. handlerSet.params[key] = (params == null ? void 0 : params[key]) && !processed ? params[key] : nodeParams[key] ?? (params == null ? void 0 : params[key]);
  88654. processedSet[handlerSet.score] = true;
  88655. }
  88656. }
  88657. }
  88658. }
  88659. return handlerSets;
  88660. }
  88661. search(method, path4) {
  88662. var _a2;
  88663. const handlerSets = [];
  88664. this.#params = emptyParams;
  88665. const curNode = this;
  88666. let curNodes = [curNode];
  88667. const parts = splitPath(path4);
  88668. const curNodesQueue = [];
  88669. for (let i4 = 0, len = parts.length; i4 < len; i4++) {
  88670. const part = parts[i4];
  88671. const isLast = i4 === len - 1;
  88672. const tempNodes = [];
  88673. for (let j3 = 0, len2 = curNodes.length; j3 < len2; j3++) {
  88674. const node = curNodes[j3];
  88675. const nextNode = node.#children[part];
  88676. if (nextNode) {
  88677. nextNode.#params = node.#params;
  88678. if (isLast) {
  88679. if (nextNode.#children["*"]) {
  88680. handlerSets.push(
  88681. ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
  88682. );
  88683. }
  88684. handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
  88685. } else {
  88686. tempNodes.push(nextNode);
  88687. }
  88688. }
  88689. for (let k3 = 0, len3 = node.#patterns.length; k3 < len3; k3++) {
  88690. const pattern = node.#patterns[k3];
  88691. const params = node.#params === emptyParams ? {} : { ...node.#params };
  88692. if (pattern === "*") {
  88693. const astNode = node.#children["*"];
  88694. if (astNode) {
  88695. handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
  88696. astNode.#params = params;
  88697. tempNodes.push(astNode);
  88698. }
  88699. continue;
  88700. }
  88701. if (part === "") {
  88702. continue;
  88703. }
  88704. const [key, name, matcher] = pattern;
  88705. const child = node.#children[key];
  88706. const restPathString = parts.slice(i4).join("/");
  88707. if (matcher instanceof RegExp) {
  88708. const m4 = matcher.exec(restPathString);
  88709. if (m4) {
  88710. params[name] = m4[0];
  88711. handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
  88712. if (Object.keys(child.#children).length) {
  88713. child.#params = params;
  88714. const componentCount = ((_a2 = m4[0].match(/\//)) == null ? void 0 : _a2.length) ?? 0;
  88715. const targetCurNodes = curNodesQueue[componentCount] ||= [];
  88716. targetCurNodes.push(child);
  88717. }
  88718. continue;
  88719. }
  88720. }
  88721. if (matcher === true || matcher.test(part)) {
  88722. params[name] = part;
  88723. if (isLast) {
  88724. handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
  88725. if (child.#children["*"]) {
  88726. handlerSets.push(
  88727. ...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
  88728. );
  88729. }
  88730. } else {
  88731. child.#params = params;
  88732. tempNodes.push(child);
  88733. }
  88734. }
  88735. }
  88736. }
  88737. curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
  88738. }
  88739. if (handlerSets.length > 1) {
  88740. handlerSets.sort((a3, b3) => {
  88741. return a3.score - b3.score;
  88742. });
  88743. }
  88744. return [handlerSets.map(({ handler, params }) => [handler, params])];
  88745. }
  88746. };
  88747. }
  88748. });
  88749. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/router.js
  88750. var TrieRouter;
  88751. var init_router4 = __esm({
  88752. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/router.js"() {
  88753. init_url();
  88754. init_node2();
  88755. TrieRouter = class {
  88756. name = "TrieRouter";
  88757. #node;
  88758. constructor() {
  88759. this.#node = new Node2();
  88760. }
  88761. add(method, path4, handler) {
  88762. const results = checkOptionalParameter(path4);
  88763. if (results) {
  88764. for (let i4 = 0, len = results.length; i4 < len; i4++) {
  88765. this.#node.insert(method, results[i4], handler);
  88766. }
  88767. return;
  88768. }
  88769. this.#node.insert(method, path4, handler);
  88770. }
  88771. match(method, path4) {
  88772. return this.#node.search(method, path4);
  88773. }
  88774. };
  88775. }
  88776. });
  88777. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/index.js
  88778. var init_trie_router = __esm({
  88779. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/router/trie-router/index.js"() {
  88780. init_router4();
  88781. }
  88782. });
  88783. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono.js
  88784. var Hono2;
  88785. var init_hono = __esm({
  88786. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/hono.js"() {
  88787. init_hono_base();
  88788. init_reg_exp_router();
  88789. init_smart_router();
  88790. init_trie_router();
  88791. Hono2 = class extends Hono {
  88792. constructor(options = {}) {
  88793. super(options);
  88794. this.router = options.router ?? new SmartRouter({
  88795. routers: [new RegExpRouter(), new TrieRouter()]
  88796. });
  88797. }
  88798. };
  88799. }
  88800. });
  88801. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/index.js
  88802. var init_dist3 = __esm({
  88803. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/index.js"() {
  88804. init_hono();
  88805. }
  88806. });
  88807. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/compress.js
  88808. var COMPRESSIBLE_CONTENT_TYPE_REGEX;
  88809. var init_compress = __esm({
  88810. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/utils/compress.js"() {
  88811. COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
  88812. }
  88813. });
  88814. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/compress/index.js
  88815. var ENCODING_TYPES, cacheControlNoTransformRegExp, compress, shouldCompress, shouldTransform;
  88816. var init_compress2 = __esm({
  88817. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/compress/index.js"() {
  88818. init_compress();
  88819. ENCODING_TYPES = ["gzip", "deflate"];
  88820. cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i;
  88821. compress = (options) => {
  88822. const threshold = (options == null ? void 0 : options.threshold) ?? 1024;
  88823. return async function compress2(ctx, next) {
  88824. await next();
  88825. const contentLength = ctx.res.headers.get("Content-Length");
  88826. if (ctx.res.headers.has("Content-Encoding") || ctx.res.headers.has("Transfer-Encoding") || ctx.req.method === "HEAD" || contentLength && Number(contentLength) < threshold || !shouldCompress(ctx.res) || !shouldTransform(ctx.res)) {
  88827. return;
  88828. }
  88829. const accepted = ctx.req.header("Accept-Encoding");
  88830. const encoding = (options == null ? void 0 : options.encoding) ?? ENCODING_TYPES.find((encoding2) => accepted == null ? void 0 : accepted.includes(encoding2));
  88831. if (!encoding || !ctx.res.body) {
  88832. return;
  88833. }
  88834. const stream = new CompressionStream(encoding);
  88835. ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res);
  88836. ctx.res.headers.delete("Content-Length");
  88837. ctx.res.headers.set("Content-Encoding", encoding);
  88838. };
  88839. };
  88840. shouldCompress = (res) => {
  88841. const type = res.headers.get("Content-Type");
  88842. return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type);
  88843. };
  88844. shouldTransform = (res) => {
  88845. const cacheControl = res.headers.get("Cache-Control");
  88846. return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl);
  88847. };
  88848. }
  88849. });
  88850. // ../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/cors/index.js
  88851. var cors;
  88852. var init_cors = __esm({
  88853. "../node_modules/.pnpm/hono@4.7.10/node_modules/hono/dist/middleware/cors/index.js"() {
  88854. cors = (options) => {
  88855. const defaults2 = {
  88856. origin: "*",
  88857. allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
  88858. allowHeaders: [],
  88859. exposeHeaders: []
  88860. };
  88861. const opts = {
  88862. ...defaults2,
  88863. ...options
  88864. };
  88865. const findAllowOrigin = ((optsOrigin) => {
  88866. if (typeof optsOrigin === "string") {
  88867. if (optsOrigin === "*") {
  88868. return () => optsOrigin;
  88869. } else {
  88870. return (origin) => optsOrigin === origin ? origin : null;
  88871. }
  88872. } else if (typeof optsOrigin === "function") {
  88873. return optsOrigin;
  88874. } else {
  88875. return (origin) => optsOrigin.includes(origin) ? origin : null;
  88876. }
  88877. })(opts.origin);
  88878. return async function cors2(c3, next) {
  88879. var _a2, _b;
  88880. function set(key, value) {
  88881. c3.res.headers.set(key, value);
  88882. }
  88883. const allowOrigin = findAllowOrigin(c3.req.header("origin") || "", c3);
  88884. if (allowOrigin) {
  88885. set("Access-Control-Allow-Origin", allowOrigin);
  88886. }
  88887. if (opts.origin !== "*") {
  88888. const existingVary = c3.req.header("Vary");
  88889. if (existingVary) {
  88890. set("Vary", existingVary);
  88891. } else {
  88892. set("Vary", "Origin");
  88893. }
  88894. }
  88895. if (opts.credentials) {
  88896. set("Access-Control-Allow-Credentials", "true");
  88897. }
  88898. if ((_a2 = opts.exposeHeaders) == null ? void 0 : _a2.length) {
  88899. set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
  88900. }
  88901. if (c3.req.method === "OPTIONS") {
  88902. if (opts.maxAge != null) {
  88903. set("Access-Control-Max-Age", opts.maxAge.toString());
  88904. }
  88905. if ((_b = opts.allowMethods) == null ? void 0 : _b.length) {
  88906. set("Access-Control-Allow-Methods", opts.allowMethods.join(","));
  88907. }
  88908. let headers = opts.allowHeaders;
  88909. if (!(headers == null ? void 0 : headers.length)) {
  88910. const requestHeaders = c3.req.header("Access-Control-Request-Headers");
  88911. if (requestHeaders) {
  88912. headers = requestHeaders.split(/\s*,\s*/);
  88913. }
  88914. }
  88915. if (headers == null ? void 0 : headers.length) {
  88916. set("Access-Control-Allow-Headers", headers.join(","));
  88917. c3.res.headers.append("Vary", "Access-Control-Request-Headers");
  88918. }
  88919. c3.res.headers.delete("Content-Length");
  88920. c3.res.headers.delete("Content-Type");
  88921. return new Response(null, {
  88922. headers: c3.res.headers,
  88923. status: 204,
  88924. statusText: "No Content"
  88925. });
  88926. }
  88927. await next();
  88928. };
  88929. };
  88930. }
  88931. });
  88932. // src/serializer/studio.ts
  88933. var studio_exports = {};
  88934. __export(studio_exports, {
  88935. drizzleForLibSQL: () => drizzleForLibSQL,
  88936. drizzleForMySQL: () => drizzleForMySQL,
  88937. drizzleForPostgres: () => drizzleForPostgres,
  88938. drizzleForSQLite: () => drizzleForSQLite,
  88939. drizzleForSingleStore: () => drizzleForSingleStore,
  88940. extractRelations: () => extractRelations,
  88941. prepareMySqlSchema: () => prepareMySqlSchema,
  88942. preparePgSchema: () => preparePgSchema,
  88943. prepareSQLiteSchema: () => prepareSQLiteSchema,
  88944. prepareServer: () => prepareServer,
  88945. prepareSingleStoreSchema: () => prepareSingleStoreSchema
  88946. });
  88947. var import_crypto9, import_drizzle_orm11, import_mysql_core3, import_pg_core3, import_relations3, import_singlestore_core3, import_sqlite_core3, import_fs12, import_node_https2, preparePgSchema, prepareMySqlSchema, prepareSQLiteSchema, prepareSingleStoreSchema, getCustomDefaults, drizzleForPostgres, drizzleForMySQL, drizzleForSQLite, drizzleForLibSQL, drizzleForSingleStore, extractRelations, init, proxySchema, transactionProxySchema, defaultsSchema, schema5, jsonStringify, prepareServer;
  88948. var init_studio2 = __esm({
  88949. "src/serializer/studio.ts"() {
  88950. "use strict";
  88951. init_dist2();
  88952. init_esm2();
  88953. import_crypto9 = require("crypto");
  88954. import_drizzle_orm11 = require("drizzle-orm");
  88955. import_mysql_core3 = require("drizzle-orm/mysql-core");
  88956. import_pg_core3 = require("drizzle-orm/pg-core");
  88957. import_relations3 = require("drizzle-orm/relations");
  88958. import_singlestore_core3 = require("drizzle-orm/singlestore-core");
  88959. import_sqlite_core3 = require("drizzle-orm/sqlite-core");
  88960. import_fs12 = __toESM(require("fs"));
  88961. init_dist3();
  88962. init_compress2();
  88963. init_cors();
  88964. import_node_https2 = require("node:https");
  88965. init_global();
  88966. init_esm();
  88967. init_utils3();
  88968. init_serializer();
  88969. init_utils4();
  88970. preparePgSchema = async (path4) => {
  88971. const imports = prepareFilenames(path4);
  88972. const pgSchema2 = {};
  88973. const relations5 = {};
  88974. const files = imports.map((it, index6) => ({
  88975. // get the file name from the path
  88976. name: it.split("/").pop() || `schema${index6}.ts`,
  88977. content: import_fs12.default.readFileSync(it, "utf-8")
  88978. }));
  88979. await safeRegister(async () => {
  88980. for (let i4 = 0; i4 < imports.length; i4++) {
  88981. const it = imports[i4];
  88982. const i0 = require(`${it}`);
  88983. const i0values = Object.entries(i0);
  88984. i0values.forEach(([k3, t4]) => {
  88985. if ((0, import_drizzle_orm11.is)(t4, import_pg_core3.PgTable)) {
  88986. const schema6 = (0, import_pg_core3.getTableConfig)(t4).schema || "public";
  88987. pgSchema2[schema6] = pgSchema2[schema6] || {};
  88988. pgSchema2[schema6][k3] = t4;
  88989. }
  88990. if ((0, import_drizzle_orm11.is)(t4, import_relations3.Relations)) {
  88991. relations5[k3] = t4;
  88992. }
  88993. });
  88994. }
  88995. });
  88996. return { schema: pgSchema2, relations: relations5, files };
  88997. };
  88998. prepareMySqlSchema = async (path4) => {
  88999. const imports = prepareFilenames(path4);
  89000. const mysqlSchema3 = {
  89001. public: {}
  89002. };
  89003. const relations5 = {};
  89004. const files = imports.map((it, index6) => ({
  89005. // get the file name from the path
  89006. name: it.split("/").pop() || `schema${index6}.ts`,
  89007. content: import_fs12.default.readFileSync(it, "utf-8")
  89008. }));
  89009. await safeRegister(async () => {
  89010. for (let i4 = 0; i4 < imports.length; i4++) {
  89011. const it = imports[i4];
  89012. const i0 = require(`${it}`);
  89013. const i0values = Object.entries(i0);
  89014. i0values.forEach(([k3, t4]) => {
  89015. if ((0, import_drizzle_orm11.is)(t4, import_mysql_core3.MySqlTable)) {
  89016. const schema6 = (0, import_mysql_core3.getTableConfig)(t4).schema || "public";
  89017. mysqlSchema3[schema6][k3] = t4;
  89018. }
  89019. if ((0, import_drizzle_orm11.is)(t4, import_relations3.Relations)) {
  89020. relations5[k3] = t4;
  89021. }
  89022. });
  89023. }
  89024. });
  89025. return { schema: mysqlSchema3, relations: relations5, files };
  89026. };
  89027. prepareSQLiteSchema = async (path4) => {
  89028. const imports = prepareFilenames(path4);
  89029. const sqliteSchema2 = {
  89030. public: {}
  89031. };
  89032. const relations5 = {};
  89033. const files = imports.map((it, index6) => ({
  89034. // get the file name from the path
  89035. name: it.split("/").pop() || `schema${index6}.ts`,
  89036. content: import_fs12.default.readFileSync(it, "utf-8")
  89037. }));
  89038. await safeRegister(async () => {
  89039. for (let i4 = 0; i4 < imports.length; i4++) {
  89040. const it = imports[i4];
  89041. const i0 = require(`${it}`);
  89042. const i0values = Object.entries(i0);
  89043. i0values.forEach(([k3, t4]) => {
  89044. if ((0, import_drizzle_orm11.is)(t4, import_sqlite_core3.SQLiteTable)) {
  89045. const schema6 = "public";
  89046. sqliteSchema2[schema6][k3] = t4;
  89047. }
  89048. if ((0, import_drizzle_orm11.is)(t4, import_relations3.Relations)) {
  89049. relations5[k3] = t4;
  89050. }
  89051. });
  89052. }
  89053. });
  89054. return { schema: sqliteSchema2, relations: relations5, files };
  89055. };
  89056. prepareSingleStoreSchema = async (path4) => {
  89057. const imports = prepareFilenames(path4);
  89058. const singlestoreSchema2 = {
  89059. public: {}
  89060. };
  89061. const relations5 = {};
  89062. const files = imports.map((it, index6) => ({
  89063. // get the file name from the path
  89064. name: it.split("/").pop() || `schema${index6}.ts`,
  89065. content: import_fs12.default.readFileSync(it, "utf-8")
  89066. }));
  89067. await safeRegister(async () => {
  89068. for (let i4 = 0; i4 < imports.length; i4++) {
  89069. const it = imports[i4];
  89070. const i0 = require(`${it}`);
  89071. const i0values = Object.entries(i0);
  89072. i0values.forEach(([k3, t4]) => {
  89073. if ((0, import_drizzle_orm11.is)(t4, import_singlestore_core3.SingleStoreTable)) {
  89074. const schema6 = (0, import_singlestore_core3.getTableConfig)(t4).schema || "public";
  89075. singlestoreSchema2[schema6][k3] = t4;
  89076. }
  89077. if ((0, import_drizzle_orm11.is)(t4, import_relations3.Relations)) {
  89078. relations5[k3] = t4;
  89079. }
  89080. });
  89081. }
  89082. });
  89083. return { schema: singlestoreSchema2, relations: relations5, files };
  89084. };
  89085. getCustomDefaults = (schema6, casing2) => {
  89086. const customDefaults = [];
  89087. Object.entries(schema6).map(([schema7, tables]) => {
  89088. Object.entries(tables).map(([, table6]) => {
  89089. let tableConfig;
  89090. if ((0, import_drizzle_orm11.is)(table6, import_pg_core3.PgTable)) {
  89091. tableConfig = (0, import_pg_core3.getTableConfig)(table6);
  89092. } else if ((0, import_drizzle_orm11.is)(table6, import_mysql_core3.MySqlTable)) {
  89093. tableConfig = (0, import_mysql_core3.getTableConfig)(table6);
  89094. } else if ((0, import_drizzle_orm11.is)(table6, import_sqlite_core3.SQLiteTable)) {
  89095. tableConfig = (0, import_sqlite_core3.getTableConfig)(table6);
  89096. } else {
  89097. tableConfig = (0, import_singlestore_core3.getTableConfig)(table6);
  89098. }
  89099. tableConfig.columns.map((column11) => {
  89100. if (column11.defaultFn) {
  89101. customDefaults.push({
  89102. schema: schema7,
  89103. table: tableConfig.name,
  89104. column: getColumnCasing(column11, casing2),
  89105. func: column11.defaultFn
  89106. });
  89107. }
  89108. });
  89109. });
  89110. });
  89111. return customDefaults;
  89112. };
  89113. drizzleForPostgres = async (credentials2, pgSchema2, relations5, schemaFiles, casing2) => {
  89114. const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  89115. const db = await preparePostgresDB2(credentials2);
  89116. const customDefaults = getCustomDefaults(pgSchema2, casing2);
  89117. let dbUrl;
  89118. if ("driver" in credentials2) {
  89119. const { driver: driver2 } = credentials2;
  89120. if (driver2 === "aws-data-api") {
  89121. dbUrl = `aws-data-api://${credentials2.database}/${credentials2.secretArn}/${credentials2.resourceArn}`;
  89122. } else if (driver2 === "pglite") {
  89123. dbUrl = "client" in credentials2 ? credentials2.client.dataDir || "pglite://custom-client" : credentials2.url;
  89124. } else {
  89125. assertUnreachable(driver2);
  89126. }
  89127. } else if ("url" in credentials2) {
  89128. dbUrl = credentials2.url;
  89129. } else {
  89130. dbUrl = `postgresql://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
  89131. }
  89132. const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
  89133. return {
  89134. dbHash,
  89135. dialect: "postgresql",
  89136. driver: "driver" in credentials2 ? credentials2.driver : void 0,
  89137. packageName: db.packageName,
  89138. proxy: db.proxy,
  89139. transactionProxy: db.transactionProxy,
  89140. customDefaults,
  89141. schema: pgSchema2,
  89142. relations: relations5,
  89143. schemaFiles,
  89144. casing: casing2
  89145. };
  89146. };
  89147. drizzleForMySQL = async (credentials2, mysqlSchema3, relations5, schemaFiles, casing2) => {
  89148. const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  89149. const { proxy, transactionProxy, database, packageName } = await connectToMySQL2(credentials2);
  89150. const customDefaults = getCustomDefaults(mysqlSchema3, casing2);
  89151. let dbUrl;
  89152. if ("url" in credentials2) {
  89153. dbUrl = credentials2.url;
  89154. } else {
  89155. dbUrl = `mysql://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
  89156. }
  89157. const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
  89158. return {
  89159. dbHash,
  89160. dialect: "mysql",
  89161. packageName,
  89162. databaseName: database,
  89163. proxy,
  89164. transactionProxy,
  89165. customDefaults,
  89166. schema: mysqlSchema3,
  89167. relations: relations5,
  89168. schemaFiles,
  89169. casing: casing2
  89170. };
  89171. };
  89172. drizzleForSQLite = async (credentials2, sqliteSchema2, relations5, schemaFiles, casing2) => {
  89173. const customDefaults = getCustomDefaults(sqliteSchema2, casing2);
  89174. if ("driver" in credentials2 && credentials2.driver === "d1") {
  89175. const { connectToD1: connectToD12 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  89176. const sqliteDB2 = await connectToD12(credentials2.binding);
  89177. const dbUrl2 = "d1://binding";
  89178. const dbHash2 = (0, import_crypto9.createHash)("sha256").update(dbUrl2).digest("hex");
  89179. return {
  89180. dbHash: dbHash2,
  89181. dialect: "sqlite",
  89182. driver: "d1",
  89183. packageName: "d1",
  89184. proxy: sqliteDB2.proxy,
  89185. transactionProxy: sqliteDB2.transactionProxy,
  89186. customDefaults,
  89187. schema: sqliteSchema2,
  89188. relations: relations5,
  89189. schemaFiles,
  89190. casing: casing2
  89191. };
  89192. }
  89193. const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  89194. const sqliteDB = await connectToSQLite2(credentials2);
  89195. let dbUrl;
  89196. if ("driver" in credentials2) {
  89197. const { driver: driver2 } = credentials2;
  89198. if (driver2 === "d1-http") {
  89199. dbUrl = `d1-http://${credentials2.accountId}/${credentials2.databaseId}/${credentials2.token}`;
  89200. } else {
  89201. assertUnreachable(driver2);
  89202. }
  89203. } else {
  89204. dbUrl = credentials2.url;
  89205. }
  89206. const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
  89207. return {
  89208. dbHash,
  89209. dialect: "sqlite",
  89210. driver: "driver" in credentials2 ? credentials2.driver : void 0,
  89211. packageName: sqliteDB.packageName,
  89212. proxy: sqliteDB.proxy,
  89213. transactionProxy: sqliteDB.transactionProxy,
  89214. customDefaults,
  89215. schema: sqliteSchema2,
  89216. relations: relations5,
  89217. schemaFiles,
  89218. casing: casing2
  89219. };
  89220. };
  89221. drizzleForLibSQL = async (credentials2, sqliteSchema2, relations5, schemaFiles, casing2) => {
  89222. const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  89223. const sqliteDB = await connectToLibSQL2(credentials2);
  89224. const customDefaults = getCustomDefaults(sqliteSchema2, casing2);
  89225. let dbUrl = `turso://${credentials2.url}/${credentials2.authToken}`;
  89226. const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
  89227. return {
  89228. dbHash,
  89229. dialect: "sqlite",
  89230. driver: void 0,
  89231. packageName: sqliteDB.packageName,
  89232. proxy: sqliteDB.proxy,
  89233. transactionProxy: sqliteDB.transactionProxy,
  89234. customDefaults,
  89235. schema: sqliteSchema2,
  89236. relations: relations5,
  89237. schemaFiles,
  89238. casing: casing2
  89239. };
  89240. };
  89241. drizzleForSingleStore = async (credentials2, singlestoreSchema2, relations5, schemaFiles, casing2) => {
  89242. const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  89243. const { proxy, transactionProxy, database, packageName } = await connectToSingleStore2(credentials2);
  89244. const customDefaults = getCustomDefaults(singlestoreSchema2, casing2);
  89245. let dbUrl;
  89246. if ("url" in credentials2) {
  89247. dbUrl = credentials2.url;
  89248. } else {
  89249. dbUrl = `singlestore://${credentials2.user}:${credentials2.password}@${credentials2.host}:${credentials2.port}/${credentials2.database}`;
  89250. }
  89251. const dbHash = (0, import_crypto9.createHash)("sha256").update(dbUrl).digest("hex");
  89252. return {
  89253. dbHash,
  89254. dialect: "singlestore",
  89255. databaseName: database,
  89256. packageName,
  89257. proxy,
  89258. transactionProxy,
  89259. customDefaults,
  89260. schema: singlestoreSchema2,
  89261. relations: relations5,
  89262. schemaFiles,
  89263. casing: casing2
  89264. };
  89265. };
  89266. extractRelations = (tablesConfig, casing2) => {
  89267. const relations5 = Object.values(tablesConfig.tables).map(
  89268. (it) => Object.entries(it.relations).map(([name, relation]) => {
  89269. try {
  89270. const normalized = (0, import_relations3.normalizeRelation)(
  89271. tablesConfig.tables,
  89272. tablesConfig.tableNamesMap,
  89273. relation
  89274. );
  89275. const rel = relation;
  89276. const refTableName = rel.referencedTableName;
  89277. const refTable = rel.referencedTable;
  89278. const fields = normalized.fields.map((it2) => getColumnCasing(it2, casing2)).flat();
  89279. const refColumns = normalized.references.map((it2) => getColumnCasing(it2, casing2)).flat();
  89280. let refSchema;
  89281. if ((0, import_drizzle_orm11.is)(refTable, import_pg_core3.PgTable)) {
  89282. refSchema = (0, import_pg_core3.getTableConfig)(refTable).schema;
  89283. } else if ((0, import_drizzle_orm11.is)(refTable, import_mysql_core3.MySqlTable)) {
  89284. refSchema = (0, import_mysql_core3.getTableConfig)(refTable).schema;
  89285. } else if ((0, import_drizzle_orm11.is)(refTable, import_sqlite_core3.SQLiteTable)) {
  89286. refSchema = void 0;
  89287. } else if ((0, import_drizzle_orm11.is)(refTable, import_singlestore_core3.SingleStoreTable)) {
  89288. refSchema = (0, import_singlestore_core3.getTableConfig)(refTable).schema;
  89289. } else {
  89290. throw new Error("unsupported dialect");
  89291. }
  89292. let type;
  89293. if ((0, import_drizzle_orm11.is)(rel, import_relations3.One)) {
  89294. type = "one";
  89295. } else if ((0, import_drizzle_orm11.is)(rel, import_relations3.Many)) {
  89296. type = "many";
  89297. } else {
  89298. throw new Error("unsupported relation type");
  89299. }
  89300. return {
  89301. name,
  89302. type,
  89303. table: it.dbName,
  89304. schema: it.schema || "public",
  89305. columns: fields,
  89306. refTable: refTableName,
  89307. refSchema: refSchema || "public",
  89308. refColumns
  89309. };
  89310. } catch {
  89311. throw new Error(
  89312. `Invalid relation "${relation.fieldName}" for table "${it.schema ? `${it.schema}.${it.dbName}` : it.dbName}"`
  89313. );
  89314. }
  89315. })
  89316. ).flat();
  89317. return relations5;
  89318. };
  89319. init = external_exports.object({
  89320. type: external_exports.literal("init")
  89321. });
  89322. proxySchema = external_exports.object({
  89323. type: external_exports.literal("proxy"),
  89324. data: external_exports.object({
  89325. sql: external_exports.string(),
  89326. params: external_exports.array(external_exports.any()).optional(),
  89327. typings: external_exports.string().array().optional(),
  89328. mode: external_exports.enum(["array", "object"]).default("object"),
  89329. method: external_exports.union([
  89330. external_exports.literal("values"),
  89331. external_exports.literal("get"),
  89332. external_exports.literal("all"),
  89333. external_exports.literal("run"),
  89334. external_exports.literal("execute")
  89335. ])
  89336. })
  89337. });
  89338. transactionProxySchema = external_exports.object({
  89339. type: external_exports.literal("tproxy"),
  89340. data: external_exports.object({
  89341. sql: external_exports.string(),
  89342. method: external_exports.union([
  89343. external_exports.literal("values"),
  89344. external_exports.literal("get"),
  89345. external_exports.literal("all"),
  89346. external_exports.literal("run"),
  89347. external_exports.literal("execute")
  89348. ]).optional()
  89349. }).array()
  89350. });
  89351. defaultsSchema = external_exports.object({
  89352. type: external_exports.literal("defaults"),
  89353. data: external_exports.array(
  89354. external_exports.object({
  89355. schema: external_exports.string(),
  89356. table: external_exports.string(),
  89357. column: external_exports.string()
  89358. })
  89359. ).min(1)
  89360. });
  89361. schema5 = external_exports.union([
  89362. init,
  89363. proxySchema,
  89364. transactionProxySchema,
  89365. defaultsSchema
  89366. ]);
  89367. jsonStringify = (data) => {
  89368. return JSON.stringify(data, (_key, value) => {
  89369. if (value instanceof Error) {
  89370. return {
  89371. error: value.message
  89372. };
  89373. }
  89374. if (typeof value === "bigint") {
  89375. return value.toString();
  89376. }
  89377. if (value && typeof value === "object" && "type" in value && "data" in value && value.type === "Buffer" || value instanceof ArrayBuffer || value instanceof Buffer) {
  89378. return Buffer.from(value).toString("base64");
  89379. }
  89380. return value;
  89381. });
  89382. };
  89383. prepareServer = async ({
  89384. dialect: dialect6,
  89385. driver: driver2,
  89386. packageName,
  89387. databaseName,
  89388. proxy,
  89389. transactionProxy,
  89390. customDefaults,
  89391. schema: drizzleSchema,
  89392. relations: relations5,
  89393. dbHash,
  89394. casing: casing2,
  89395. schemaFiles
  89396. }, app) => {
  89397. app = app !== void 0 ? app : new Hono2();
  89398. app.use(compress());
  89399. app.use(async (ctx, next) => {
  89400. await next();
  89401. ctx.header("Access-Control-Allow-Private-Network", "true");
  89402. });
  89403. app.use(cors());
  89404. app.onError((err2, ctx) => {
  89405. console.error(err2);
  89406. return ctx.json({
  89407. status: "error",
  89408. error: err2.message
  89409. });
  89410. });
  89411. const relationalSchema = {
  89412. ...Object.fromEntries(
  89413. Object.entries(drizzleSchema).map(([schemaName, schema6]) => {
  89414. const mappedTableEntries = Object.entries(schema6).map(
  89415. ([tableName, table6]) => {
  89416. return [`__${schemaName}__.${tableName}`, table6];
  89417. }
  89418. );
  89419. return mappedTableEntries;
  89420. }).flat()
  89421. ),
  89422. ...relations5
  89423. };
  89424. const relationsConfig = (0, import_relations3.extractTablesRelationalConfig)(
  89425. relationalSchema,
  89426. import_relations3.createTableRelationsHelpers
  89427. );
  89428. app.post("/", zValidator("json", schema5), async (c3) => {
  89429. const body = c3.req.valid("json");
  89430. const { type } = body;
  89431. if (type === "init") {
  89432. const preparedDefaults = customDefaults.map((d3) => ({
  89433. schema: d3.schema,
  89434. table: d3.table,
  89435. column: d3.column
  89436. }));
  89437. let relations6 = [];
  89438. try {
  89439. relations6 = extractRelations(relationsConfig, casing2);
  89440. } catch (error2) {
  89441. console.warn(
  89442. "Failed to extract relations. This is likely due to ambiguous or misconfigured relations."
  89443. );
  89444. console.warn(
  89445. "Please check your schema and ensure that all relations are correctly defined."
  89446. );
  89447. console.warn(
  89448. "See: https://orm.drizzle.team/docs/relations#disambiguating-relations"
  89449. );
  89450. console.warn("Error message:", error2.message);
  89451. }
  89452. return c3.json({
  89453. version: "6.2",
  89454. dialect: dialect6,
  89455. driver: driver2,
  89456. packageName,
  89457. schemaFiles,
  89458. customDefaults: preparedDefaults,
  89459. relations: relations6,
  89460. dbHash,
  89461. databaseName
  89462. });
  89463. }
  89464. if (type === "proxy") {
  89465. const result = await proxy({
  89466. ...body.data,
  89467. params: body.data.params || []
  89468. });
  89469. return c3.json(JSON.parse(jsonStringify(result)));
  89470. }
  89471. if (type === "tproxy") {
  89472. const result = await transactionProxy(body.data);
  89473. return c3.json(JSON.parse(jsonStringify(result)));
  89474. }
  89475. if (type === "defaults") {
  89476. const columns = body.data;
  89477. const result = columns.map((column11) => {
  89478. const found = customDefaults.find((d3) => {
  89479. return d3.schema === column11.schema && d3.table === column11.table && d3.column === column11.column;
  89480. });
  89481. if (!found) {
  89482. throw new Error(
  89483. `Custom default not found for ${column11.schema}.${column11.table}.${column11.column}`
  89484. );
  89485. }
  89486. const value = found.func();
  89487. return {
  89488. ...column11,
  89489. value
  89490. };
  89491. });
  89492. return c3.json(JSON.parse(jsonStringify(result)));
  89493. }
  89494. throw new Error(`Unknown type: ${type}`);
  89495. });
  89496. return {
  89497. start: (params) => {
  89498. serve(
  89499. {
  89500. fetch: app.fetch,
  89501. createServer: params.key ? import_node_https2.createServer : void 0,
  89502. hostname: params.host,
  89503. port: params.port,
  89504. serverOptions: {
  89505. key: params.key,
  89506. cert: params.cert
  89507. }
  89508. },
  89509. () => params.cb(null, `${params.host}:${params.port}`)
  89510. );
  89511. }
  89512. };
  89513. };
  89514. }
  89515. });
  89516. // ../node_modules/.pnpm/@drizzle-team+brocli@0.10.2/node_modules/@drizzle-team/brocli/index.js
  89517. var __create2 = Object.create;
  89518. var __defProp2 = Object.defineProperty;
  89519. var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
  89520. var __getOwnPropNames2 = Object.getOwnPropertyNames;
  89521. var __getProtoOf2 = Object.getPrototypeOf;
  89522. var __hasOwnProp2 = Object.prototype.hasOwnProperty;
  89523. var __commonJS2 = (cb, mod) => function __require() {
  89524. return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  89525. };
  89526. var __copyProps2 = (to, from, except, desc) => {
  89527. if (from && typeof from === "object" || typeof from === "function") {
  89528. for (let key of __getOwnPropNames2(from))
  89529. if (!__hasOwnProp2.call(to, key) && key !== except)
  89530. __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
  89531. }
  89532. return to;
  89533. };
  89534. var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
  89535. // If the importer is in node compatibility mode or this is not an ESM
  89536. // file that has been converted to a CommonJS file using a Babel-
  89537. // compatible transform (i.e. "__esModule" has not been set), then set
  89538. // "default" to the CommonJS "module.exports" for node compatibility.
  89539. isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
  89540. mod
  89541. ));
  89542. var require_clone = __commonJS2({
  89543. "node_modules/.pnpm/clone@2.1.2/node_modules/clone/clone.js"(exports2, module2) {
  89544. "use strict";
  89545. var clone2 = function() {
  89546. "use strict";
  89547. function _instanceof(obj, type) {
  89548. return type != null && obj instanceof type;
  89549. }
  89550. var nativeMap;
  89551. try {
  89552. nativeMap = Map;
  89553. } catch (_3) {
  89554. nativeMap = function() {
  89555. };
  89556. }
  89557. var nativeSet;
  89558. try {
  89559. nativeSet = Set;
  89560. } catch (_3) {
  89561. nativeSet = function() {
  89562. };
  89563. }
  89564. var nativePromise;
  89565. try {
  89566. nativePromise = Promise;
  89567. } catch (_3) {
  89568. nativePromise = function() {
  89569. };
  89570. }
  89571. function clone3(parent, circular, depth, prototype, includeNonEnumerable) {
  89572. if (typeof circular === "object") {
  89573. depth = circular.depth;
  89574. prototype = circular.prototype;
  89575. includeNonEnumerable = circular.includeNonEnumerable;
  89576. circular = circular.circular;
  89577. }
  89578. var allParents = [];
  89579. var allChildren = [];
  89580. var useBuffer = typeof Buffer != "undefined";
  89581. if (typeof circular == "undefined")
  89582. circular = true;
  89583. if (typeof depth == "undefined")
  89584. depth = Infinity;
  89585. function _clone(parent2, depth2) {
  89586. if (parent2 === null)
  89587. return null;
  89588. if (depth2 === 0)
  89589. return parent2;
  89590. var child;
  89591. var proto2;
  89592. if (typeof parent2 != "object") {
  89593. return parent2;
  89594. }
  89595. if (_instanceof(parent2, nativeMap)) {
  89596. child = new nativeMap();
  89597. } else if (_instanceof(parent2, nativeSet)) {
  89598. child = new nativeSet();
  89599. } else if (_instanceof(parent2, nativePromise)) {
  89600. child = new nativePromise(function(resolve2, reject) {
  89601. parent2.then(function(value) {
  89602. resolve2(_clone(value, depth2 - 1));
  89603. }, function(err2) {
  89604. reject(_clone(err2, depth2 - 1));
  89605. });
  89606. });
  89607. } else if (clone3.__isArray(parent2)) {
  89608. child = [];
  89609. } else if (clone3.__isRegExp(parent2)) {
  89610. child = new RegExp(parent2.source, __getRegExpFlags(parent2));
  89611. if (parent2.lastIndex) child.lastIndex = parent2.lastIndex;
  89612. } else if (clone3.__isDate(parent2)) {
  89613. child = new Date(parent2.getTime());
  89614. } else if (useBuffer && Buffer.isBuffer(parent2)) {
  89615. if (Buffer.allocUnsafe) {
  89616. child = Buffer.allocUnsafe(parent2.length);
  89617. } else {
  89618. child = new Buffer(parent2.length);
  89619. }
  89620. parent2.copy(child);
  89621. return child;
  89622. } else if (_instanceof(parent2, Error)) {
  89623. child = Object.create(parent2);
  89624. } else {
  89625. if (typeof prototype == "undefined") {
  89626. proto2 = Object.getPrototypeOf(parent2);
  89627. child = Object.create(proto2);
  89628. } else {
  89629. child = Object.create(prototype);
  89630. proto2 = prototype;
  89631. }
  89632. }
  89633. if (circular) {
  89634. var index6 = allParents.indexOf(parent2);
  89635. if (index6 != -1) {
  89636. return allChildren[index6];
  89637. }
  89638. allParents.push(parent2);
  89639. allChildren.push(child);
  89640. }
  89641. if (_instanceof(parent2, nativeMap)) {
  89642. parent2.forEach(function(value, key) {
  89643. var keyChild = _clone(key, depth2 - 1);
  89644. var valueChild = _clone(value, depth2 - 1);
  89645. child.set(keyChild, valueChild);
  89646. });
  89647. }
  89648. if (_instanceof(parent2, nativeSet)) {
  89649. parent2.forEach(function(value) {
  89650. var entryChild = _clone(value, depth2 - 1);
  89651. child.add(entryChild);
  89652. });
  89653. }
  89654. for (var i4 in parent2) {
  89655. var attrs;
  89656. if (proto2) {
  89657. attrs = Object.getOwnPropertyDescriptor(proto2, i4);
  89658. }
  89659. if (attrs && attrs.set == null) {
  89660. continue;
  89661. }
  89662. child[i4] = _clone(parent2[i4], depth2 - 1);
  89663. }
  89664. if (Object.getOwnPropertySymbols) {
  89665. var symbols = Object.getOwnPropertySymbols(parent2);
  89666. for (var i4 = 0; i4 < symbols.length; i4++) {
  89667. var symbol = symbols[i4];
  89668. var descriptor = Object.getOwnPropertyDescriptor(parent2, symbol);
  89669. if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
  89670. continue;
  89671. }
  89672. child[symbol] = _clone(parent2[symbol], depth2 - 1);
  89673. if (!descriptor.enumerable) {
  89674. Object.defineProperty(child, symbol, {
  89675. enumerable: false
  89676. });
  89677. }
  89678. }
  89679. }
  89680. if (includeNonEnumerable) {
  89681. var allPropertyNames = Object.getOwnPropertyNames(parent2);
  89682. for (var i4 = 0; i4 < allPropertyNames.length; i4++) {
  89683. var propertyName = allPropertyNames[i4];
  89684. var descriptor = Object.getOwnPropertyDescriptor(parent2, propertyName);
  89685. if (descriptor && descriptor.enumerable) {
  89686. continue;
  89687. }
  89688. child[propertyName] = _clone(parent2[propertyName], depth2 - 1);
  89689. Object.defineProperty(child, propertyName, {
  89690. enumerable: false
  89691. });
  89692. }
  89693. }
  89694. return child;
  89695. }
  89696. return _clone(parent, depth);
  89697. }
  89698. clone3.clonePrototype = function clonePrototype(parent) {
  89699. if (parent === null)
  89700. return null;
  89701. var c3 = function() {
  89702. };
  89703. c3.prototype = parent;
  89704. return new c3();
  89705. };
  89706. function __objToStr(o3) {
  89707. return Object.prototype.toString.call(o3);
  89708. }
  89709. clone3.__objToStr = __objToStr;
  89710. function __isDate(o3) {
  89711. return typeof o3 === "object" && __objToStr(o3) === "[object Date]";
  89712. }
  89713. clone3.__isDate = __isDate;
  89714. function __isArray(o3) {
  89715. return typeof o3 === "object" && __objToStr(o3) === "[object Array]";
  89716. }
  89717. clone3.__isArray = __isArray;
  89718. function __isRegExp(o3) {
  89719. return typeof o3 === "object" && __objToStr(o3) === "[object RegExp]";
  89720. }
  89721. clone3.__isRegExp = __isRegExp;
  89722. function __getRegExpFlags(re) {
  89723. var flags = "";
  89724. if (re.global) flags += "g";
  89725. if (re.ignoreCase) flags += "i";
  89726. if (re.multiline) flags += "m";
  89727. return flags;
  89728. }
  89729. clone3.__getRegExpFlags = __getRegExpFlags;
  89730. return clone3;
  89731. }();
  89732. if (typeof module2 === "object" && module2.exports) {
  89733. module2.exports = clone2;
  89734. }
  89735. }
  89736. });
  89737. var require_quote = __commonJS2({
  89738. "node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/quote.js"(exports2, module2) {
  89739. "use strict";
  89740. module2.exports = function quote(xs) {
  89741. return xs.map(function(s4) {
  89742. if (s4 && typeof s4 === "object") {
  89743. return s4.op.replace(/(.)/g, "\\$1");
  89744. }
  89745. if (/["\s]/.test(s4) && !/'/.test(s4)) {
  89746. return "'" + s4.replace(/(['\\])/g, "\\$1") + "'";
  89747. }
  89748. if (/["'\s]/.test(s4)) {
  89749. return '"' + s4.replace(/(["\\$`!])/g, "\\$1") + '"';
  89750. }
  89751. return String(s4).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
  89752. }).join(" ");
  89753. };
  89754. }
  89755. });
  89756. var require_parse = __commonJS2({
  89757. "node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/parse.js"(exports2, module2) {
  89758. "use strict";
  89759. var CONTROL = "(?:" + [
  89760. "\\|\\|",
  89761. "\\&\\&",
  89762. ";;",
  89763. "\\|\\&",
  89764. "\\<\\(",
  89765. "\\<\\<\\<",
  89766. ">>",
  89767. ">\\&",
  89768. "<\\&",
  89769. "[&;()|<>]"
  89770. ].join("|") + ")";
  89771. var controlRE = new RegExp("^" + CONTROL + "$");
  89772. var META = "|&;()<> \\t";
  89773. var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
  89774. var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
  89775. var hash = /^#$/;
  89776. var SQ = "'";
  89777. var DQ = '"';
  89778. var DS = "$";
  89779. var TOKEN = "";
  89780. var mult = 4294967296;
  89781. for (i4 = 0; i4 < 4; i4++) {
  89782. TOKEN += (mult * Math.random()).toString(16);
  89783. }
  89784. var i4;
  89785. var startsWithToken = new RegExp("^" + TOKEN);
  89786. function matchAll(s4, r4) {
  89787. var origIndex = r4.lastIndex;
  89788. var matches = [];
  89789. var matchObj;
  89790. while (matchObj = r4.exec(s4)) {
  89791. matches.push(matchObj);
  89792. if (r4.lastIndex === matchObj.index) {
  89793. r4.lastIndex += 1;
  89794. }
  89795. }
  89796. r4.lastIndex = origIndex;
  89797. return matches;
  89798. }
  89799. function getVar(env3, pre, key) {
  89800. var r4 = typeof env3 === "function" ? env3(key) : env3[key];
  89801. if (typeof r4 === "undefined" && key != "") {
  89802. r4 = "";
  89803. } else if (typeof r4 === "undefined") {
  89804. r4 = "$";
  89805. }
  89806. if (typeof r4 === "object") {
  89807. return pre + TOKEN + JSON.stringify(r4) + TOKEN;
  89808. }
  89809. return pre + r4;
  89810. }
  89811. function parseInternal(string2, env3, opts) {
  89812. if (!opts) {
  89813. opts = {};
  89814. }
  89815. var BS = opts.escape || "\\";
  89816. var BAREWORD = "(\\" + BS + `['"` + META + `]|[^\\s'"` + META + "])+";
  89817. var chunker = new RegExp([
  89818. "(" + CONTROL + ")",
  89819. // control chars
  89820. "(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"
  89821. ].join("|"), "g");
  89822. var matches = matchAll(string2, chunker);
  89823. if (matches.length === 0) {
  89824. return [];
  89825. }
  89826. if (!env3) {
  89827. env3 = {};
  89828. }
  89829. var commented = false;
  89830. return matches.map(function(match2) {
  89831. var s4 = match2[0];
  89832. if (!s4 || commented) {
  89833. return void 0;
  89834. }
  89835. if (controlRE.test(s4)) {
  89836. return { op: s4 };
  89837. }
  89838. var quote = false;
  89839. var esc = false;
  89840. var out = "";
  89841. var isGlob = false;
  89842. var i22;
  89843. function parseEnvVar() {
  89844. i22 += 1;
  89845. var varend;
  89846. var varname;
  89847. var char = s4.charAt(i22);
  89848. if (char === "{") {
  89849. i22 += 1;
  89850. if (s4.charAt(i22) === "}") {
  89851. throw new Error("Bad substitution: " + s4.slice(i22 - 2, i22 + 1));
  89852. }
  89853. varend = s4.indexOf("}", i22);
  89854. if (varend < 0) {
  89855. throw new Error("Bad substitution: " + s4.slice(i22));
  89856. }
  89857. varname = s4.slice(i22, varend);
  89858. i22 = varend;
  89859. } else if (/[*@#?$!_-]/.test(char)) {
  89860. varname = char;
  89861. i22 += 1;
  89862. } else {
  89863. var slicedFromI = s4.slice(i22);
  89864. varend = slicedFromI.match(/[^\w\d_]/);
  89865. if (!varend) {
  89866. varname = slicedFromI;
  89867. i22 = s4.length;
  89868. } else {
  89869. varname = slicedFromI.slice(0, varend.index);
  89870. i22 += varend.index - 1;
  89871. }
  89872. }
  89873. return getVar(env3, "", varname);
  89874. }
  89875. for (i22 = 0; i22 < s4.length; i22++) {
  89876. var c3 = s4.charAt(i22);
  89877. isGlob = isGlob || !quote && (c3 === "*" || c3 === "?");
  89878. if (esc) {
  89879. out += c3;
  89880. esc = false;
  89881. } else if (quote) {
  89882. if (c3 === quote) {
  89883. quote = false;
  89884. } else if (quote == SQ) {
  89885. out += c3;
  89886. } else {
  89887. if (c3 === BS) {
  89888. i22 += 1;
  89889. c3 = s4.charAt(i22);
  89890. if (c3 === DQ || c3 === BS || c3 === DS) {
  89891. out += c3;
  89892. } else {
  89893. out += BS + c3;
  89894. }
  89895. } else if (c3 === DS) {
  89896. out += parseEnvVar();
  89897. } else {
  89898. out += c3;
  89899. }
  89900. }
  89901. } else if (c3 === DQ || c3 === SQ) {
  89902. quote = c3;
  89903. } else if (controlRE.test(c3)) {
  89904. return { op: s4 };
  89905. } else if (hash.test(c3)) {
  89906. commented = true;
  89907. var commentObj = { comment: string2.slice(match2.index + i22 + 1) };
  89908. if (out.length) {
  89909. return [out, commentObj];
  89910. }
  89911. return [commentObj];
  89912. } else if (c3 === BS) {
  89913. esc = true;
  89914. } else if (c3 === DS) {
  89915. out += parseEnvVar();
  89916. } else {
  89917. out += c3;
  89918. }
  89919. }
  89920. if (isGlob) {
  89921. return { op: "glob", pattern: out };
  89922. }
  89923. return out;
  89924. }).reduce(function(prev, arg) {
  89925. return typeof arg === "undefined" ? prev : prev.concat(arg);
  89926. }, []);
  89927. }
  89928. module2.exports = function parse4(s4, env3, opts) {
  89929. var mapped = parseInternal(s4, env3, opts);
  89930. if (typeof env3 !== "function") {
  89931. return mapped;
  89932. }
  89933. return mapped.reduce(function(acc, s22) {
  89934. if (typeof s22 === "object") {
  89935. return acc.concat(s22);
  89936. }
  89937. var xs = s22.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
  89938. if (xs.length === 1) {
  89939. return acc.concat(xs[0]);
  89940. }
  89941. return acc.concat(xs.filter(Boolean).map(function(x4) {
  89942. if (startsWithToken.test(x4)) {
  89943. return JSON.parse(x4.split(TOKEN)[1]);
  89944. }
  89945. return x4;
  89946. }));
  89947. }, []);
  89948. };
  89949. }
  89950. });
  89951. var require_shell_quote = __commonJS2({
  89952. "node_modules/.pnpm/shell-quote@1.8.1/node_modules/shell-quote/index.js"(exports2) {
  89953. "use strict";
  89954. exports2.quote = require_quote();
  89955. exports2.parse = require_parse();
  89956. }
  89957. });
  89958. var BroCliError = class extends Error {
  89959. constructor(message, event) {
  89960. const errPrefix = "BroCli error: ";
  89961. super(message === void 0 ? message : `${errPrefix}${message}`);
  89962. this.event = event;
  89963. }
  89964. };
  89965. var import_clone = __toESM2(require_clone(), 1);
  89966. var getOptionTypeText = (option) => {
  89967. let result = "";
  89968. switch (option.type) {
  89969. case "boolean":
  89970. result = "";
  89971. break;
  89972. case "number": {
  89973. if ((option.minVal ?? option.maxVal) !== void 0) {
  89974. let text = "";
  89975. if (option.isInt) text = text + `integer `;
  89976. if (option.minVal !== void 0) text = text + `[${option.minVal};`;
  89977. else text = text + `(\u221E;`;
  89978. if (option.maxVal !== void 0) text = text + `${option.maxVal}]`;
  89979. else text = text + `\u221E)`;
  89980. result = text;
  89981. break;
  89982. }
  89983. if (option.isInt) {
  89984. result = "integer";
  89985. break;
  89986. }
  89987. result = "number";
  89988. break;
  89989. }
  89990. case "string": {
  89991. if (option.enumVals) {
  89992. result = "[ " + option.enumVals.join(" | ") + " ]";
  89993. break;
  89994. }
  89995. result = "string";
  89996. break;
  89997. }
  89998. case "positional": {
  89999. result = `${option.isRequired ? "<" : "["}${option.enumVals ? option.enumVals.join("|") : option.name}${option.isRequired ? ">" : "]"}`;
  90000. break;
  90001. }
  90002. }
  90003. if (option.isRequired && option.type !== "positional") result = "!" + result.length ? " " : "" + result;
  90004. return result;
  90005. };
  90006. var defaultEventHandler = async (event) => {
  90007. var _a2;
  90008. switch (event.type) {
  90009. case "command_help": {
  90010. const command3 = event.command;
  90011. const commandName = getCommandNameWithParents(command3);
  90012. const cliName = event.name;
  90013. const desc = command3.desc ?? command3.shortDesc;
  90014. const subs = (_a2 = command3.subcommands) == null ? void 0 : _a2.filter((s4) => !s4.hidden);
  90015. const subcommands = subs && subs.length ? subs : void 0;
  90016. if (desc !== void 0) {
  90017. console.log(`
  90018. ${desc}`);
  90019. }
  90020. const opts = Object.values(command3.options ?? {}).filter(
  90021. (opt) => !opt.config.isHidden
  90022. );
  90023. const positionals = opts.filter((opt) => opt.config.type === "positional");
  90024. const options = opts.filter((opt) => opt.config.type !== "positional");
  90025. console.log("\nUsage:");
  90026. if (command3.handler) {
  90027. console.log(
  90028. ` ${cliName ? cliName + " " : ""}${commandName}${positionals.length ? " " + positionals.map(({ config: p3 }) => getOptionTypeText(p3)).join(" ") : ""} [flags]`
  90029. );
  90030. } else console.log(` ${cliName ? cliName + " " : ""}${commandName} [command]`);
  90031. if (command3.aliases) {
  90032. console.log(`
  90033. Aliases:`);
  90034. console.log(` ${[command3.name, ...command3.aliases].join(", ")}`);
  90035. }
  90036. if (subcommands) {
  90037. console.log("\nAvailable Commands:");
  90038. const padding = 3;
  90039. const maxLength = subcommands.reduce((p3, e4) => e4.name.length > p3 ? e4.name.length : p3, 0);
  90040. const paddedLength = maxLength + padding;
  90041. const preDescPad = 2 + paddedLength;
  90042. const data = subcommands.map(
  90043. (s4) => ` ${s4.name.padEnd(paddedLength)}${(() => {
  90044. const description = s4.shortDesc ?? s4.desc;
  90045. if (!(description == null ? void 0 : description.length)) return "";
  90046. const split = description.split("\n");
  90047. const first = split.shift();
  90048. const final = [first, ...split.map((s22) => "".padEnd(preDescPad) + s22)].join("\n");
  90049. return final;
  90050. })()}`
  90051. ).join("\n");
  90052. console.log(data);
  90053. }
  90054. if (options.length) {
  90055. const aliasLength = options.reduce((p3, e4) => {
  90056. const currentLength = e4.config.aliases.reduce((pa, a3) => pa + a3.length, 0) + (e4.config.aliases.length - 1) * 2 + 1;
  90057. return currentLength > p3 ? currentLength : p3;
  90058. }, 0);
  90059. const paddedAliasLength = aliasLength > 0 ? aliasLength + 1 : 0;
  90060. const nameLength = options.reduce((p3, e4) => {
  90061. const typeLen = getOptionTypeText(e4.config).length;
  90062. const length = typeLen > 0 ? e4.config.name.length + 1 + typeLen : e4.config.name.length;
  90063. return length > p3 ? length : p3;
  90064. }, 0) + 3;
  90065. const preDescPad = paddedAliasLength + nameLength + 2;
  90066. const data = options.map(
  90067. ({ config: opt }) => ` ${`${opt.aliases.length ? opt.aliases.join(", ") + "," : ""}`.padEnd(paddedAliasLength)}${`${opt.name}${(() => {
  90068. const typeText = getOptionTypeText(opt);
  90069. return typeText.length ? " " + typeText : "";
  90070. })()}`.padEnd(nameLength)}${(() => {
  90071. var _a3;
  90072. if (!((_a3 = opt.description) == null ? void 0 : _a3.length)) {
  90073. return opt.default !== void 0 ? `default: ${JSON.stringify(opt.default)}` : "";
  90074. }
  90075. const split = opt.description.split("\n");
  90076. const first = split.shift();
  90077. const def = opt.default !== void 0 ? ` (default: ${JSON.stringify(opt.default)})` : "";
  90078. const final = [first, ...split.map((s4) => "".padEnd(preDescPad) + s4)].join("\n") + def;
  90079. return final;
  90080. })()}`
  90081. ).join("\n");
  90082. console.log("\nFlags:");
  90083. console.log(data);
  90084. }
  90085. console.log("\nGlobal flags:");
  90086. console.log(` -h, --help help for ${commandName}`);
  90087. console.log(` -v, --version version${cliName ? ` for ${cliName}` : ""}`);
  90088. if (subcommands) {
  90089. console.log(
  90090. `
  90091. Use "${cliName ? cliName + " " : ""}${commandName} [command] --help" for more information about a command.
  90092. `
  90093. );
  90094. }
  90095. return true;
  90096. }
  90097. case "global_help": {
  90098. const cliName = event.name;
  90099. const desc = event.description;
  90100. const commands3 = event.commands.filter((c3) => !c3.hidden);
  90101. if (desc !== void 0) {
  90102. console.log(`${desc}
  90103. `);
  90104. }
  90105. console.log("Usage:");
  90106. console.log(` ${cliName ? cliName + " " : ""}[command]`);
  90107. if (commands3.length) {
  90108. console.log("\nAvailable Commands:");
  90109. const padding = 3;
  90110. const maxLength = commands3.reduce((p3, e4) => e4.name.length > p3 ? e4.name.length : p3, 0);
  90111. const paddedLength = maxLength + padding;
  90112. const data = commands3.map(
  90113. (c3) => ` ${c3.name.padEnd(paddedLength)}${(() => {
  90114. const desc2 = c3.shortDesc ?? c3.desc;
  90115. if (!(desc2 == null ? void 0 : desc2.length)) return "";
  90116. const split = desc2.split("\n");
  90117. const first = split.shift();
  90118. const final = [first, ...split.map((s4) => "".padEnd(paddedLength + 2) + s4)].join("\n");
  90119. return final;
  90120. })()}`
  90121. ).join("\n");
  90122. console.log(data);
  90123. } else {
  90124. console.log("\nNo available commands.");
  90125. }
  90126. console.log("\nFlags:");
  90127. console.log(` -h, --help help${cliName ? ` for ${cliName}` : ""}`);
  90128. console.log(` -v, --version version${cliName ? ` for ${cliName}` : ""}`);
  90129. console.log("\n");
  90130. return true;
  90131. }
  90132. case "version": {
  90133. return true;
  90134. }
  90135. case "error": {
  90136. let msg;
  90137. switch (event.violation) {
  90138. case "above_max": {
  90139. const matchedName = event.offender.namePart;
  90140. const data = event.offender.dataPart;
  90141. const option = event.option;
  90142. const max = option.maxVal;
  90143. msg = `Invalid value: number type argument '${matchedName}' expects maximal value of ${max} as an input, got: ${data}`;
  90144. break;
  90145. }
  90146. case "below_min": {
  90147. const matchedName = event.offender.namePart;
  90148. const data = event.offender.dataPart;
  90149. const option = event.option;
  90150. const min = option.minVal;
  90151. msg = `Invalid value: number type argument '${matchedName}' expects minimal value of ${min} as an input, got: ${data}`;
  90152. break;
  90153. }
  90154. case "expected_int": {
  90155. const matchedName = event.offender.namePart;
  90156. const data = event.offender.dataPart;
  90157. msg = `Invalid value: number type argument '${matchedName}' expects an integer as an input, got: ${data}`;
  90158. break;
  90159. }
  90160. case "invalid_boolean_syntax": {
  90161. const matchedName = event.offender.namePart;
  90162. const data = event.offender.dataPart;
  90163. msg = `Invalid syntax: boolean type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value> | ${matchedName}.
  90164. Allowed values: true, false, 0, 1`;
  90165. break;
  90166. }
  90167. case "invalid_string_syntax": {
  90168. const matchedName = event.offender.namePart;
  90169. msg = `Invalid syntax: string type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
  90170. break;
  90171. }
  90172. case "invalid_number_syntax": {
  90173. const matchedName = event.offender.namePart;
  90174. msg = `Invalid syntax: number type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
  90175. break;
  90176. }
  90177. case "invalid_number_value": {
  90178. const matchedName = event.offender.namePart;
  90179. const data = event.offender.dataPart;
  90180. msg = `Invalid value: number type argument '${matchedName}' expects a number as an input, got: ${data}`;
  90181. break;
  90182. }
  90183. case "enum_violation": {
  90184. const matchedName = event.offender.namePart;
  90185. const data = event.offender.dataPart;
  90186. const option = event.option;
  90187. const values = option.enumVals;
  90188. msg = option.type === "positional" ? `Invalid value: value for the positional argument '${option.name}' must be either one of the following: ${values.join(", ")}; Received: ${data}` : `Invalid value: value for the argument '${matchedName}' must be either one of the following: ${values.join(", ")}; Received: ${data}`;
  90189. break;
  90190. }
  90191. case "unknown_command_error": {
  90192. const msg2 = `Unknown command: '${event.offender}'.
  90193. Type '--help' to get help on the cli.`;
  90194. console.error(msg2);
  90195. return true;
  90196. }
  90197. case "unknown_subcommand_error": {
  90198. const cName = getCommandNameWithParents(event.command);
  90199. const msg2 = `Unknown command: ${cName} ${event.offender}.
  90200. Type '${cName} --help' to get the help on command.`;
  90201. console.error(msg2);
  90202. return true;
  90203. }
  90204. case "missing_args_error": {
  90205. const { missing: missingOpts, command: command3 } = event;
  90206. msg = `Command '${command3.name}' is missing following required options: ${missingOpts.map((opt) => {
  90207. const name = opt.shift();
  90208. const aliases = opt;
  90209. if (aliases.length) return `${name} [${aliases.join(", ")}]`;
  90210. return name;
  90211. }).join(", ")}`;
  90212. break;
  90213. }
  90214. case "unrecognized_args_error": {
  90215. const { command: command3, unrecognized } = event;
  90216. msg = `Unrecognized options for command '${command3.name}': ${unrecognized.join(", ")}`;
  90217. break;
  90218. }
  90219. case "unknown_error": {
  90220. const e4 = event.error;
  90221. console.error(typeof e4 === "object" && e4 !== null && "message" in e4 ? e4.message : e4);
  90222. return true;
  90223. }
  90224. }
  90225. console.error(msg);
  90226. return true;
  90227. }
  90228. }
  90229. return false;
  90230. };
  90231. var eventHandlerWrapper = (customEventHandler) => async (event) => await customEventHandler(event) ? true : await defaultEventHandler(event);
  90232. var import_shell_quote = __toESM2(require_shell_quote(), 1);
  90233. function isInt(value) {
  90234. return value === Math.floor(value);
  90235. }
  90236. var executeOrLog = async (target) => typeof target === "string" ? console.log(target) : target ? await target() : void 0;
  90237. var generatePrefix = (name) => name.startsWith("-") ? name : name.length > 1 ? `--${name}` : `-${name}`;
  90238. var validateOptions = (config) => {
  90239. const cloned = (0, import_clone.default)(config);
  90240. const entries = [];
  90241. const storedNames = [];
  90242. const cfgEntries = Object.entries(cloned);
  90243. for (const [key, value] of cfgEntries) {
  90244. const cfg = value._.config;
  90245. if (cfg.name === void 0) cfg.name = key;
  90246. if (cfg.type === "positional") continue;
  90247. if (cfg.name.includes("=")) {
  90248. throw new BroCliError(
  90249. `Can't define option '${generatePrefix(cfg.name)}' - option names and aliases cannot contain '='!`
  90250. );
  90251. }
  90252. for (const alias of cfg.aliases) {
  90253. if (alias.includes("=")) {
  90254. throw new BroCliError(
  90255. `Can't define option '${generatePrefix(cfg.name)}' - option names and aliases cannot contain '='!`
  90256. );
  90257. }
  90258. }
  90259. cfg.name = generatePrefix(cfg.name);
  90260. cfg.aliases = cfg.aliases.map((a3) => generatePrefix(a3));
  90261. }
  90262. for (const [key, value] of cfgEntries) {
  90263. const cfg = value._.config;
  90264. if (cfg.type === "positional") {
  90265. entries.push([key, { config: cfg, $output: void 0 }]);
  90266. continue;
  90267. }
  90268. const reservedNames = ["--help", "-h", "--version", "-v"];
  90269. const allNames = [cfg.name, ...cfg.aliases];
  90270. for (const name of allNames) {
  90271. const match2 = reservedNames.find((n3) => n3 === name);
  90272. if (match2) throw new BroCliError(`Can't define option '${cfg.name}' - name '${match2}' is reserved!`);
  90273. }
  90274. for (const storage of storedNames) {
  90275. const nameOccupier = storage.find((e4) => e4 === cfg.name);
  90276. if (!nameOccupier) continue;
  90277. throw new BroCliError(
  90278. `Can't define option '${cfg.name}' - name is already in use by option '${storage[0]}'!`
  90279. );
  90280. }
  90281. for (const alias of cfg.aliases) {
  90282. for (const storage of storedNames) {
  90283. const nameOccupier = storage.find((e4) => e4 === alias);
  90284. if (!nameOccupier) continue;
  90285. throw new BroCliError(
  90286. `Can't define option '${cfg.name}' - alias '${alias}' is already in use by option '${storage[0]}'!`
  90287. );
  90288. }
  90289. }
  90290. const currentNames = [cfg.name, ...cfg.aliases];
  90291. storedNames.push(currentNames);
  90292. currentNames.forEach((name, idx) => {
  90293. if (currentNames.findIndex((e4) => e4 === name) === idx) return;
  90294. throw new BroCliError(
  90295. `Can't define option '${cfg.name}' - duplicate alias '${name}'!`
  90296. );
  90297. });
  90298. entries.push([key, { config: cfg, $output: void 0 }]);
  90299. }
  90300. return Object.fromEntries(entries);
  90301. };
  90302. var assignParent = (parent, subcommands) => subcommands.forEach((e4) => {
  90303. e4.parent = parent;
  90304. if (e4.subcommands) assignParent(e4, e4.subcommands);
  90305. });
  90306. var command2 = (command3) => {
  90307. var _a2, _b, _c;
  90308. const allNames = command3.aliases ? [command3.name, ...command3.aliases] : [command3.name];
  90309. const cmd = (0, import_clone.default)(command3);
  90310. if (command3.subcommands && command3.options && Object.values(command3.options).find((opt) => opt._.config.type === "positional")) {
  90311. throw new BroCliError(
  90312. `Can't define command '${cmd.name}' - command can't have subcommands and positional args at the same time!`
  90313. );
  90314. }
  90315. if (!command3.handler && !command3.subcommands) {
  90316. throw new BroCliError(
  90317. `Can't define command '${cmd.name}' - command without subcommands must have a handler present!`
  90318. );
  90319. }
  90320. const processedOptions = command3.options ? validateOptions(command3.options) : void 0;
  90321. cmd.options = processedOptions;
  90322. cmd.name = cmd.name ?? ((_a2 = cmd.aliases) == null ? void 0 : _a2.shift());
  90323. if (!cmd.name) throw new BroCliError(`Can't define command without name!`);
  90324. cmd.aliases = ((_b = cmd.aliases) == null ? void 0 : _b.length) ? cmd.aliases : void 0;
  90325. if (cmd.name.startsWith("-")) {
  90326. throw new BroCliError(`Can't define command '${cmd.name}' - command name can't start with '-'!`);
  90327. }
  90328. (_c = cmd.aliases) == null ? void 0 : _c.forEach((a3) => {
  90329. if (a3.startsWith("-")) {
  90330. throw new BroCliError(`Can't define command '${cmd.name}' - command aliases can't start with '-'!`);
  90331. }
  90332. });
  90333. allNames.forEach((n3, i4) => {
  90334. if (n3 === "help") {
  90335. throw new BroCliError(
  90336. `Can't define command '${cmd.name}' - 'help' is a reserved name. If you want to redefine help message - do so in runCli's config.`
  90337. );
  90338. }
  90339. const lCaseName = n3 == null ? void 0 : n3.toLowerCase();
  90340. if (lCaseName === "0" || lCaseName === "1" || lCaseName === "true" || lCaseName === "false") {
  90341. throw new BroCliError(
  90342. `Can't define command '${cmd.name}' - '${n3}' is a reserved for boolean values name!`
  90343. );
  90344. }
  90345. const idx = allNames.findIndex((an) => an === n3);
  90346. if (idx !== i4) throw new BroCliError(`Can't define command '${cmd.name}' - duplicate alias '${n3}'!`);
  90347. });
  90348. if (cmd.subcommands) {
  90349. assignParent(cmd, cmd.subcommands);
  90350. }
  90351. return cmd;
  90352. };
  90353. var getCommandInner = (commands3, candidates, args, cliName, cliDescription) => {
  90354. const { data: arg, originalIndex: index6 } = candidates.shift();
  90355. const command3 = commands3.find((c3) => {
  90356. const names = c3.aliases ? [c3.name, ...c3.aliases] : [c3.name];
  90357. const res = names.find((name) => name === arg);
  90358. return res;
  90359. });
  90360. if (!command3) {
  90361. return {
  90362. command: command3,
  90363. args
  90364. };
  90365. }
  90366. const newArgs = removeByIndex(args, index6);
  90367. if (!candidates.length || !command3.subcommands) {
  90368. return {
  90369. command: command3,
  90370. args: newArgs
  90371. };
  90372. }
  90373. const newCandidates = candidates.map((c3) => ({ data: c3.data, originalIndex: c3.originalIndex - 1 }));
  90374. const subcommand = getCommandInner(command3.subcommands, newCandidates, newArgs, cliName, cliDescription);
  90375. if (!subcommand.command) {
  90376. throw new BroCliError(void 0, {
  90377. type: "error",
  90378. violation: "unknown_subcommand_error",
  90379. name: cliName,
  90380. description: cliDescription,
  90381. command: command3,
  90382. offender: candidates[0].data
  90383. });
  90384. }
  90385. return subcommand;
  90386. };
  90387. var getCommand = (commands3, args, cliName, cliDescription) => {
  90388. var _a2;
  90389. const candidates = [];
  90390. for (let i4 = 0; i4 < args.length; ++i4) {
  90391. const arg = args[i4];
  90392. if (arg === "--help" || arg === "-h" || arg === "--version" || arg === "-v") {
  90393. const lCaseNext = (_a2 = args[i4 + 1]) == null ? void 0 : _a2.toLowerCase();
  90394. if (lCaseNext === "0" || lCaseNext === "1" || lCaseNext === "true" || lCaseNext === "false") ++i4;
  90395. continue;
  90396. }
  90397. if (arg == null ? void 0 : arg.startsWith("-")) {
  90398. if (!arg.includes("=")) ++i4;
  90399. continue;
  90400. }
  90401. candidates.push({
  90402. data: arg,
  90403. originalIndex: i4
  90404. });
  90405. }
  90406. if (!candidates.length) {
  90407. return {
  90408. command: void 0,
  90409. args
  90410. };
  90411. }
  90412. const firstCandidate = candidates[0];
  90413. if (firstCandidate.data === "help") {
  90414. return {
  90415. command: "help",
  90416. args: removeByIndex(args, firstCandidate.originalIndex)
  90417. };
  90418. }
  90419. const { command: command3, args: argsRes } = getCommandInner(commands3, candidates, args, cliName, cliDescription);
  90420. if (!command3) {
  90421. throw new BroCliError(void 0, {
  90422. type: "error",
  90423. violation: "unknown_command_error",
  90424. commands: commands3,
  90425. name: cliName,
  90426. description: cliDescription,
  90427. offender: firstCandidate.data
  90428. });
  90429. }
  90430. return {
  90431. command: command3,
  90432. args: argsRes
  90433. };
  90434. };
  90435. var parseArg = (command3, options, positionals, arg, nextArg, cliName, cliDescription) => {
  90436. let data = void 0;
  90437. const argSplit = arg.split("=");
  90438. const hasEq = arg.includes("=");
  90439. const namePart = argSplit.shift();
  90440. const dataPart = hasEq ? argSplit.join("=") : nextArg;
  90441. let skipNext = !hasEq;
  90442. if (namePart === "--help" || namePart === "-h") {
  90443. return {
  90444. isHelp: true
  90445. };
  90446. }
  90447. if (namePart === "--version" || namePart === "-v") {
  90448. return {
  90449. isVersion: true
  90450. };
  90451. }
  90452. if (!arg.startsWith("-")) {
  90453. if (!positionals.length) return {};
  90454. const pos = positionals.shift();
  90455. if (pos[1].enumVals && !pos[1].enumVals.find((val2) => val2 === arg)) {
  90456. throw new BroCliError(void 0, {
  90457. type: "error",
  90458. name: cliName,
  90459. description: cliDescription,
  90460. violation: "enum_violation",
  90461. command: command3,
  90462. option: pos[1],
  90463. offender: {
  90464. dataPart: arg
  90465. }
  90466. });
  90467. }
  90468. data = arg;
  90469. return {
  90470. data,
  90471. skipNext: false,
  90472. name: pos[0],
  90473. option: pos[1]
  90474. };
  90475. }
  90476. const option = options.find(([optKey, opt]) => {
  90477. const names = [opt.name, ...opt.aliases];
  90478. if (opt.type === "boolean") {
  90479. const match2 = names.find((name) => name === namePart);
  90480. if (!match2) return false;
  90481. let lcaseData = dataPart == null ? void 0 : dataPart.toLowerCase();
  90482. if (!hasEq && (nextArg == null ? void 0 : nextArg.startsWith("-"))) {
  90483. data = true;
  90484. skipNext = false;
  90485. return true;
  90486. }
  90487. if (lcaseData === void 0 || lcaseData === "" || lcaseData === "true" || lcaseData === "1") {
  90488. data = true;
  90489. return true;
  90490. }
  90491. if (lcaseData === "false" || lcaseData === "0") {
  90492. data = false;
  90493. return true;
  90494. }
  90495. if (!hasEq) {
  90496. data = true;
  90497. skipNext = false;
  90498. return true;
  90499. }
  90500. throw new BroCliError(void 0, {
  90501. type: "error",
  90502. name: cliName,
  90503. description: cliDescription,
  90504. violation: "invalid_boolean_syntax",
  90505. option: opt,
  90506. command: command3,
  90507. offender: {
  90508. namePart,
  90509. dataPart
  90510. }
  90511. });
  90512. } else {
  90513. const match2 = names.find((name) => name === namePart);
  90514. if (!match2) return false;
  90515. if (opt.type === "string") {
  90516. if (!hasEq && nextArg === void 0) {
  90517. throw new BroCliError(void 0, {
  90518. type: "error",
  90519. name: cliName,
  90520. description: cliDescription,
  90521. violation: "invalid_string_syntax",
  90522. option: opt,
  90523. command: command3,
  90524. offender: {
  90525. namePart,
  90526. dataPart
  90527. }
  90528. });
  90529. }
  90530. if (opt.enumVals && !opt.enumVals.find((val2) => val2 === dataPart)) {
  90531. throw new BroCliError(void 0, {
  90532. type: "error",
  90533. name: cliName,
  90534. description: cliDescription,
  90535. violation: "enum_violation",
  90536. option: opt,
  90537. command: command3,
  90538. offender: {
  90539. namePart,
  90540. dataPart
  90541. }
  90542. });
  90543. }
  90544. data = dataPart;
  90545. return true;
  90546. }
  90547. if (!hasEq && nextArg === void 0) {
  90548. throw new BroCliError(void 0, {
  90549. type: "error",
  90550. name: cliName,
  90551. description: cliDescription,
  90552. violation: "invalid_number_syntax",
  90553. option: opt,
  90554. command: command3,
  90555. offender: {
  90556. namePart,
  90557. dataPart
  90558. }
  90559. });
  90560. }
  90561. const numData = Number(dataPart);
  90562. if (isNaN(numData)) {
  90563. throw new BroCliError(void 0, {
  90564. type: "error",
  90565. name: cliName,
  90566. description: cliDescription,
  90567. violation: "invalid_number_value",
  90568. option: opt,
  90569. command: command3,
  90570. offender: {
  90571. namePart,
  90572. dataPart
  90573. }
  90574. });
  90575. }
  90576. if (opt.isInt && !isInt(numData)) {
  90577. throw new BroCliError(void 0, {
  90578. type: "error",
  90579. name: cliName,
  90580. description: cliDescription,
  90581. violation: "expected_int",
  90582. option: opt,
  90583. command: command3,
  90584. offender: {
  90585. namePart,
  90586. dataPart
  90587. }
  90588. });
  90589. }
  90590. if (opt.minVal !== void 0 && numData < opt.minVal) {
  90591. throw new BroCliError(void 0, {
  90592. type: "error",
  90593. name: cliName,
  90594. description: cliDescription,
  90595. violation: "below_min",
  90596. option: opt,
  90597. command: command3,
  90598. offender: {
  90599. namePart,
  90600. dataPart
  90601. }
  90602. });
  90603. }
  90604. if (opt.maxVal !== void 0 && numData > opt.maxVal) {
  90605. throw new BroCliError(void 0, {
  90606. type: "error",
  90607. name: cliName,
  90608. description: cliDescription,
  90609. violation: "above_max",
  90610. option: opt,
  90611. command: command3,
  90612. offender: {
  90613. namePart,
  90614. dataPart
  90615. }
  90616. });
  90617. }
  90618. data = numData;
  90619. return true;
  90620. }
  90621. });
  90622. return {
  90623. data,
  90624. skipNext,
  90625. name: option == null ? void 0 : option[0],
  90626. option: option == null ? void 0 : option[1]
  90627. };
  90628. };
  90629. var parseOptions = (command3, args, cliName, cliDescription, omitKeysOfUndefinedOptions) => {
  90630. const options = command3.options;
  90631. const optEntries = Object.entries(options ?? {}).map(
  90632. (opt) => [opt[0], opt[1].config]
  90633. );
  90634. const nonPositionalEntries = optEntries.filter(([key, opt]) => opt.type !== "positional");
  90635. const positionalEntries = optEntries.filter(([key, opt]) => opt.type === "positional");
  90636. const result = {};
  90637. const missingRequiredArr = [];
  90638. const unrecognizedArgsArr = [];
  90639. for (let i4 = 0; i4 < args.length; ++i4) {
  90640. const arg = args[i4];
  90641. const nextArg = args[i4 + 1];
  90642. const {
  90643. data,
  90644. name,
  90645. option,
  90646. skipNext,
  90647. isHelp,
  90648. isVersion
  90649. } = parseArg(command3, nonPositionalEntries, positionalEntries, arg, nextArg, cliName, cliDescription);
  90650. if (!option) unrecognizedArgsArr.push(arg.split("=")[0]);
  90651. if (skipNext) ++i4;
  90652. if (isHelp) return "help";
  90653. if (isVersion) return "version";
  90654. result[name] = data;
  90655. }
  90656. for (const [optKey, option] of optEntries) {
  90657. const data = result[optKey] ?? option.default;
  90658. if (!omitKeysOfUndefinedOptions) {
  90659. result[optKey] = data;
  90660. } else {
  90661. if (data !== void 0) result[optKey] = data;
  90662. }
  90663. if (option.isRequired && result[optKey] === void 0) missingRequiredArr.push([option.name, ...option.aliases]);
  90664. }
  90665. if (missingRequiredArr.length) {
  90666. throw new BroCliError(void 0, {
  90667. type: "error",
  90668. violation: "missing_args_error",
  90669. name: cliName,
  90670. description: cliDescription,
  90671. command: command3,
  90672. missing: missingRequiredArr
  90673. });
  90674. }
  90675. if (unrecognizedArgsArr.length) {
  90676. throw new BroCliError(void 0, {
  90677. type: "error",
  90678. violation: "unrecognized_args_error",
  90679. name: cliName,
  90680. description: cliDescription,
  90681. command: command3,
  90682. unrecognized: unrecognizedArgsArr
  90683. });
  90684. }
  90685. return Object.keys(result).length ? result : void 0;
  90686. };
  90687. var getCommandNameWithParents = (command3) => command3.parent ? `${getCommandNameWithParents(command3.parent)} ${command3.name}` : command3.name;
  90688. var validateCommands = (commands3, parent) => {
  90689. const storedNames = {};
  90690. for (const cmd of commands3) {
  90691. const storageVals = Object.values(storedNames);
  90692. for (const storage of storageVals) {
  90693. const nameOccupier = storage.find((e4) => e4 === cmd.name);
  90694. if (!nameOccupier) continue;
  90695. throw new BroCliError(
  90696. `Can't define command '${getCommandNameWithParents(cmd)}': name is already in use by command '${parent ? `${getCommandNameWithParents(parent)} ` : ""}${storage[0]}'!`
  90697. );
  90698. }
  90699. if (cmd.aliases) {
  90700. for (const alias of cmd.aliases) {
  90701. for (const storage of storageVals) {
  90702. const nameOccupier = storage.find((e4) => e4 === alias);
  90703. if (!nameOccupier) continue;
  90704. throw new BroCliError(
  90705. `Can't define command '${getCommandNameWithParents(cmd)}': alias '${alias}' is already in use by command '${parent ? `${getCommandNameWithParents(parent)} ` : ""}${storage[0]}'!`
  90706. );
  90707. }
  90708. }
  90709. }
  90710. storedNames[cmd.name] = cmd.aliases ? [cmd.name, ...cmd.aliases] : [cmd.name];
  90711. if (cmd.subcommands) cmd.subcommands = validateCommands(cmd.subcommands, cmd);
  90712. }
  90713. return commands3;
  90714. };
  90715. var removeByIndex = (arr, idx) => [...arr.slice(0, idx), ...arr.slice(idx + 1, arr.length)];
  90716. var run = async (commands3, config) => {
  90717. var _a2, _b;
  90718. const eventHandler = (config == null ? void 0 : config.theme) ? eventHandlerWrapper(config.theme) : defaultEventHandler;
  90719. const argSource = (config == null ? void 0 : config.argSource) ?? process.argv;
  90720. const version3 = config == null ? void 0 : config.version;
  90721. const help = config == null ? void 0 : config.help;
  90722. const omitKeysOfUndefinedOptions = (config == null ? void 0 : config.omitKeysOfUndefinedOptions) ?? false;
  90723. const cliName = config == null ? void 0 : config.name;
  90724. const cliDescription = config == null ? void 0 : config.description;
  90725. try {
  90726. const processedCmds = validateCommands(commands3);
  90727. let args = argSource.slice(2, argSource.length);
  90728. if (!args.length) {
  90729. return help !== void 0 ? await executeOrLog(help) : await eventHandler({
  90730. type: "global_help",
  90731. description: cliDescription,
  90732. name: cliName,
  90733. commands: processedCmds
  90734. });
  90735. }
  90736. const helpIndex = args.findIndex((arg) => arg === "--help" || arg === "-h");
  90737. if (helpIndex !== -1 && (helpIndex > 0 ? ((_a2 = args[helpIndex - 1]) == null ? void 0 : _a2.startsWith("-")) && !args[helpIndex - 1].includes("=") ? false : true : true)) {
  90738. const command4 = getCommand(processedCmds, args, cliName, cliDescription).command;
  90739. if (typeof command4 === "object") {
  90740. return command4.help !== void 0 ? await executeOrLog(command4.help) : await eventHandler({
  90741. type: "command_help",
  90742. description: cliDescription,
  90743. name: cliName,
  90744. command: command4
  90745. });
  90746. } else {
  90747. return help !== void 0 ? await executeOrLog(help) : await eventHandler({
  90748. type: "global_help",
  90749. description: cliDescription,
  90750. name: cliName,
  90751. commands: processedCmds
  90752. });
  90753. }
  90754. }
  90755. const versionIndex = args.findIndex((arg) => arg === "--version" || arg === "-v");
  90756. if (versionIndex !== -1 && (versionIndex > 0 ? ((_b = args[versionIndex - 1]) == null ? void 0 : _b.startsWith("-")) ? false : true : true)) {
  90757. return version3 !== void 0 ? await executeOrLog(version3) : await eventHandler({
  90758. type: "version",
  90759. name: cliName,
  90760. description: cliDescription
  90761. });
  90762. }
  90763. const { command: command3, args: newArgs } = getCommand(processedCmds, args, cliName, cliDescription);
  90764. if (!command3) {
  90765. return help !== void 0 ? await executeOrLog(help) : await eventHandler({
  90766. type: "global_help",
  90767. description: cliDescription,
  90768. name: cliName,
  90769. commands: processedCmds
  90770. });
  90771. }
  90772. if (command3 === "help") {
  90773. let helpCommand;
  90774. let newestArgs = newArgs;
  90775. do {
  90776. const res = getCommand(processedCmds, newestArgs, cliName, cliDescription);
  90777. helpCommand = res.command;
  90778. newestArgs = res.args;
  90779. } while (helpCommand === "help");
  90780. return helpCommand ? helpCommand.help !== void 0 ? await executeOrLog(helpCommand.help) : await eventHandler({
  90781. type: "command_help",
  90782. description: cliDescription,
  90783. name: cliName,
  90784. command: helpCommand
  90785. }) : help !== void 0 ? await executeOrLog(help) : await eventHandler({
  90786. type: "global_help",
  90787. description: cliDescription,
  90788. name: cliName,
  90789. commands: processedCmds
  90790. });
  90791. }
  90792. const optionResult = parseOptions(command3, newArgs, cliName, cliDescription, omitKeysOfUndefinedOptions);
  90793. if (optionResult === "help") {
  90794. return command3.help !== void 0 ? await executeOrLog(command3.help) : await eventHandler({
  90795. type: "command_help",
  90796. description: cliDescription,
  90797. name: cliName,
  90798. command: command3
  90799. });
  90800. }
  90801. if (optionResult === "version") {
  90802. return version3 !== void 0 ? await executeOrLog(version3) : await eventHandler({
  90803. type: "version",
  90804. name: cliName,
  90805. description: cliDescription
  90806. });
  90807. }
  90808. if (command3.handler) {
  90809. if (config == null ? void 0 : config.hook) await config.hook("before", command3);
  90810. await command3.handler(command3.transform ? await command3.transform(optionResult) : optionResult);
  90811. if (config == null ? void 0 : config.hook) await config.hook("after", command3);
  90812. return;
  90813. } else {
  90814. return command3.help !== void 0 ? await executeOrLog(command3.help) : await eventHandler({
  90815. type: "command_help",
  90816. description: cliDescription,
  90817. name: cliName,
  90818. command: command3
  90819. });
  90820. }
  90821. } catch (e4) {
  90822. if (e4 instanceof BroCliError) {
  90823. if (e4.event) await eventHandler(e4.event);
  90824. else {
  90825. if (!(config == null ? void 0 : config.noExit)) console.error(e4.message);
  90826. else return e4.message;
  90827. }
  90828. } else {
  90829. await eventHandler({
  90830. type: "error",
  90831. violation: "unknown_error",
  90832. name: cliName,
  90833. description: cliDescription,
  90834. error: e4
  90835. });
  90836. }
  90837. if (!(config == null ? void 0 : config.noExit)) process.exit(1);
  90838. return;
  90839. }
  90840. };
  90841. var OptionBuilderBase = class _OptionBuilderBase {
  90842. _;
  90843. config = () => this._.config;
  90844. constructor(config) {
  90845. this._ = {
  90846. config: config ?? {
  90847. aliases: [],
  90848. type: "string"
  90849. },
  90850. $output: void 0
  90851. };
  90852. }
  90853. string(name) {
  90854. const config = this.config();
  90855. return new _OptionBuilderBase({ ...config, type: "string", name });
  90856. }
  90857. number(name) {
  90858. const config = this.config();
  90859. return new _OptionBuilderBase({ ...config, type: "number", name });
  90860. }
  90861. boolean(name) {
  90862. const config = this.config();
  90863. return new _OptionBuilderBase({ ...config, type: "boolean", name });
  90864. }
  90865. positional(displayName) {
  90866. const config = this.config();
  90867. return new _OptionBuilderBase({ ...config, type: "positional", name: displayName });
  90868. }
  90869. alias(...aliases) {
  90870. const config = this.config();
  90871. return new _OptionBuilderBase({ ...config, aliases });
  90872. }
  90873. desc(description) {
  90874. const config = this.config();
  90875. return new _OptionBuilderBase({ ...config, description });
  90876. }
  90877. hidden() {
  90878. const config = this.config();
  90879. return new _OptionBuilderBase({ ...config, isHidden: true });
  90880. }
  90881. required() {
  90882. const config = this.config();
  90883. return new _OptionBuilderBase({ ...config, isRequired: true });
  90884. }
  90885. default(value) {
  90886. const config = this.config();
  90887. const enums = config.enumVals;
  90888. if (enums && !enums.find((v6) => value === v6)) {
  90889. throw new Error(
  90890. `Option enums [ ${enums.join(", ")} ] are incompatible with default value ${value}`
  90891. );
  90892. }
  90893. return new _OptionBuilderBase({ ...config, default: value });
  90894. }
  90895. enum(...values) {
  90896. const config = this.config();
  90897. const defaultVal = config.default;
  90898. if (defaultVal !== void 0 && !values.find((v6) => defaultVal === v6)) {
  90899. throw new Error(
  90900. `Option enums [ ${values.join(", ")} ] are incompatible with default value ${defaultVal}`
  90901. );
  90902. }
  90903. return new _OptionBuilderBase({ ...config, enumVals: values });
  90904. }
  90905. min(value) {
  90906. const config = this.config();
  90907. const maxVal = config.maxVal;
  90908. if (maxVal !== void 0 && maxVal < value) {
  90909. throw new BroCliError("Unable to define option's min value to be higher than max value!");
  90910. }
  90911. return new _OptionBuilderBase({ ...config, minVal: value });
  90912. }
  90913. max(value) {
  90914. const config = this.config();
  90915. const minVal = config.minVal;
  90916. if (minVal !== void 0 && minVal > value) {
  90917. throw new BroCliError("Unable to define option's max value to be lower than min value!");
  90918. }
  90919. return new _OptionBuilderBase({ ...config, maxVal: value });
  90920. }
  90921. int() {
  90922. const config = this.config();
  90923. return new _OptionBuilderBase({ ...config, isInt: true });
  90924. }
  90925. };
  90926. function string(name) {
  90927. return typeof name === "string" ? new OptionBuilderBase().string(name) : new OptionBuilderBase().string();
  90928. }
  90929. function number(name) {
  90930. return typeof name === "string" ? new OptionBuilderBase().number(name) : new OptionBuilderBase().number();
  90931. }
  90932. function boolean(name) {
  90933. return typeof name === "string" ? new OptionBuilderBase().boolean(name) : new OptionBuilderBase().boolean();
  90934. }
  90935. // src/cli/index.ts
  90936. init_source();
  90937. // src/cli/schema.ts
  90938. init_source();
  90939. // ../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/config.js
  90940. (function() {
  90941. require_main().config(
  90942. Object.assign(
  90943. {},
  90944. require_env_options(),
  90945. require_cli_options()(process.argv)
  90946. )
  90947. );
  90948. })();
  90949. // src/cli/schema.ts
  90950. var import_fs13 = require("fs");
  90951. var import_hanji15 = __toESM(require_hanji());
  90952. init_schemaValidator();
  90953. init_utils();
  90954. init_global();
  90955. init_utils2();
  90956. // ../node_modules/.pnpm/env-paths@3.0.0/node_modules/env-paths/index.js
  90957. var import_node_path = __toESM(require("node:path"), 1);
  90958. var import_node_os2 = __toESM(require("node:os"), 1);
  90959. var import_node_process2 = __toESM(require("node:process"), 1);
  90960. var homedir = import_node_os2.default.homedir();
  90961. var tmpdir = import_node_os2.default.tmpdir();
  90962. var { env: env2 } = import_node_process2.default;
  90963. var macos = (name) => {
  90964. const library = import_node_path.default.join(homedir, "Library");
  90965. return {
  90966. data: import_node_path.default.join(library, "Application Support", name),
  90967. config: import_node_path.default.join(library, "Preferences", name),
  90968. cache: import_node_path.default.join(library, "Caches", name),
  90969. log: import_node_path.default.join(library, "Logs", name),
  90970. temp: import_node_path.default.join(tmpdir, name)
  90971. };
  90972. };
  90973. var windows = (name) => {
  90974. const appData = env2.APPDATA || import_node_path.default.join(homedir, "AppData", "Roaming");
  90975. const localAppData = env2.LOCALAPPDATA || import_node_path.default.join(homedir, "AppData", "Local");
  90976. return {
  90977. // Data/config/cache/log are invented by me as Windows isn't opinionated about this
  90978. data: import_node_path.default.join(localAppData, name, "Data"),
  90979. config: import_node_path.default.join(appData, name, "Config"),
  90980. cache: import_node_path.default.join(localAppData, name, "Cache"),
  90981. log: import_node_path.default.join(localAppData, name, "Log"),
  90982. temp: import_node_path.default.join(tmpdir, name)
  90983. };
  90984. };
  90985. var linux = (name) => {
  90986. const username = import_node_path.default.basename(homedir);
  90987. return {
  90988. data: import_node_path.default.join(env2.XDG_DATA_HOME || import_node_path.default.join(homedir, ".local", "share"), name),
  90989. config: import_node_path.default.join(env2.XDG_CONFIG_HOME || import_node_path.default.join(homedir, ".config"), name),
  90990. cache: import_node_path.default.join(env2.XDG_CACHE_HOME || import_node_path.default.join(homedir, ".cache"), name),
  90991. // https://wiki.debian.org/XDGBaseDirectorySpecification#state
  90992. log: import_node_path.default.join(env2.XDG_STATE_HOME || import_node_path.default.join(homedir, ".local", "state"), name),
  90993. temp: import_node_path.default.join(tmpdir, username, name)
  90994. };
  90995. };
  90996. function envPaths(name, { suffix = "nodejs" } = {}) {
  90997. if (typeof name !== "string") {
  90998. throw new TypeError(`Expected a string, got ${typeof name}`);
  90999. }
  91000. if (suffix) {
  91001. name += `-${suffix}`;
  91002. }
  91003. if (import_node_process2.default.platform === "darwin") {
  91004. return macos(name);
  91005. }
  91006. if (import_node_process2.default.platform === "win32") {
  91007. return windows(name);
  91008. }
  91009. return linux(name);
  91010. }
  91011. // src/utils/certs.ts
  91012. var import_fs2 = require("fs");
  91013. var import_promises = require("fs/promises");
  91014. var import_node_child_process = require("node:child_process");
  91015. var import_path2 = require("path");
  91016. function runCommand(command, options = {}) {
  91017. return new Promise((resolve2) => {
  91018. (0, import_node_child_process.exec)(command, options, (error2) => {
  91019. return resolve2({ exitCode: (error2 == null ? void 0 : error2.code) ?? 0 });
  91020. });
  91021. });
  91022. }
  91023. var certs = async () => {
  91024. const res = await runCommand("mkcert --help");
  91025. if (res.exitCode === 0) {
  91026. const p3 = envPaths("drizzle-studio", {
  91027. suffix: ""
  91028. });
  91029. (0, import_fs2.mkdirSync)(p3.data, { recursive: true });
  91030. const keyPath = (0, import_path2.join)(p3.data, "localhost-key.pem");
  91031. const certPath = (0, import_path2.join)(p3.data, "localhost.pem");
  91032. try {
  91033. await Promise.all([(0, import_promises.access)(keyPath), (0, import_promises.access)(certPath)]);
  91034. } catch (e4) {
  91035. await runCommand(`mkcert localhost`, { cwd: p3.data });
  91036. }
  91037. const [key, cert] = await Promise.all([
  91038. (0, import_promises.readFile)(keyPath, { encoding: "utf-8" }),
  91039. (0, import_promises.readFile)(certPath, { encoding: "utf-8" })
  91040. ]);
  91041. return key && cert ? { key, cert } : null;
  91042. }
  91043. return null;
  91044. };
  91045. // src/cli/commands/check.ts
  91046. init_utils2();
  91047. var checkHandler = (out, dialect6) => {
  91048. const { snapshots } = prepareOutFolder(out, dialect6);
  91049. const report = validateWithReport(snapshots, dialect6);
  91050. if (report.nonLatest.length > 0) {
  91051. console.log(
  91052. report.nonLatest.map((it) => {
  91053. return `${it} is not of the latest version, please run "drizzle-kit up"`;
  91054. }).join("\n")
  91055. );
  91056. process.exit(1);
  91057. }
  91058. if (report.malformed.length) {
  91059. const message2 = report.malformed.map((it) => {
  91060. return `${it} data is malformed`;
  91061. }).join("\n");
  91062. console.log(message2);
  91063. }
  91064. const collisionEntries = Object.entries(report.idsMap).filter(
  91065. (it) => it[1].snapshots.length > 1
  91066. );
  91067. const message = collisionEntries.map((it) => {
  91068. const data = it[1];
  91069. return `[${data.snapshots.join(
  91070. ", "
  91071. )}] are pointing to a parent snapshot: ${data.parent}/snapshot.json which is a collision.`;
  91072. }).join("\n");
  91073. if (message) {
  91074. console.log(message);
  91075. }
  91076. const abort = report.malformed.length || collisionEntries.length > 0;
  91077. if (abort) {
  91078. process.exit(1);
  91079. }
  91080. };
  91081. // src/cli/commands/drop.ts
  91082. init_source();
  91083. var import_fs7 = require("fs");
  91084. var import_fs8 = __toESM(require("fs"));
  91085. var import_hanji4 = __toESM(require_hanji());
  91086. var import_path6 = require("path");
  91087. init_views();
  91088. init_migrate();
  91089. var dropMigration = async ({
  91090. out,
  91091. bundle
  91092. }) => {
  91093. const metaFilePath = (0, import_path6.join)(out, "meta", "_journal.json");
  91094. const journal = JSON.parse((0, import_fs7.readFileSync)(metaFilePath, "utf-8"));
  91095. if (journal.entries.length === 0) {
  91096. console.log(
  91097. `[${source_default.blue("i")}] no migration entries found in ${metaFilePath}`
  91098. );
  91099. return;
  91100. }
  91101. const result = await (0, import_hanji4.render)(new DropMigrationView(journal.entries));
  91102. if (result.status === "aborted") return;
  91103. delete journal.entries[journal.entries.indexOf(result.data)];
  91104. const resultJournal = {
  91105. ...journal,
  91106. entries: journal.entries.filter(Boolean)
  91107. };
  91108. const sqlFilePath = (0, import_path6.join)(out, `${result.data.tag}.sql`);
  91109. const snapshotFilePath = (0, import_path6.join)(
  91110. out,
  91111. "meta",
  91112. `${result.data.tag.split("_")[0]}_snapshot.json`
  91113. );
  91114. (0, import_fs7.rmSync)(sqlFilePath);
  91115. (0, import_fs7.rmSync)(snapshotFilePath);
  91116. (0, import_fs7.writeFileSync)(metaFilePath, JSON.stringify(resultJournal, null, 2));
  91117. if (bundle) {
  91118. import_fs8.default.writeFileSync(
  91119. (0, import_path6.join)(out, `migrations.js`),
  91120. embeddedMigrations(resultJournal)
  91121. );
  91122. }
  91123. console.log(
  91124. `[${source_default.green("\u2713")}] ${source_default.bold(
  91125. result.data.tag
  91126. )} migration successfully dropped`
  91127. );
  91128. };
  91129. // src/cli/commands/mysqlUp.ts
  91130. var upMysqlHandler = (out) => {
  91131. };
  91132. // src/cli/commands/pgUp.ts
  91133. init_source();
  91134. var import_fs9 = require("fs");
  91135. init_pgSchema();
  91136. init_utils2();
  91137. var upPgHandler = (out) => {
  91138. const { snapshots } = prepareOutFolder(out, "postgresql");
  91139. const report = validateWithReport(snapshots, "postgresql");
  91140. report.nonLatest.map((it) => ({
  91141. path: it,
  91142. raw: report.rawMap[it]
  91143. })).forEach((it) => {
  91144. const path4 = it.path;
  91145. let resultV6 = it.raw;
  91146. if (it.raw.version === "5") {
  91147. resultV6 = updateUpToV6(it.raw);
  91148. }
  91149. const result = updateUpToV7(resultV6);
  91150. console.log(`[${source_default.green("\u2713")}] ${path4}`);
  91151. (0, import_fs9.writeFileSync)(path4, JSON.stringify(result, null, 2));
  91152. });
  91153. console.log("Everything's fine \u{1F436}\u{1F525}");
  91154. };
  91155. var updateUpToV6 = (json) => {
  91156. const schema6 = pgSchemaV5.parse(json);
  91157. const tables = Object.fromEntries(
  91158. Object.entries(schema6.tables).map((it) => {
  91159. const table6 = it[1];
  91160. const schema7 = table6.schema || "public";
  91161. return [`${schema7}.${table6.name}`, table6];
  91162. })
  91163. );
  91164. const enums = Object.fromEntries(
  91165. Object.entries(schema6.enums).map((it) => {
  91166. const en = it[1];
  91167. return [
  91168. `public.${en.name}`,
  91169. {
  91170. name: en.name,
  91171. schema: "public",
  91172. values: Object.values(en.values)
  91173. }
  91174. ];
  91175. })
  91176. );
  91177. return {
  91178. ...schema6,
  91179. version: "6",
  91180. dialect: "postgresql",
  91181. tables,
  91182. enums
  91183. };
  91184. };
  91185. var updateUpToV7 = (json) => {
  91186. const schema6 = pgSchemaV6.parse(json);
  91187. const tables = Object.fromEntries(
  91188. Object.entries(schema6.tables).map((it) => {
  91189. const table6 = it[1];
  91190. const mappedIndexes = Object.fromEntries(
  91191. Object.entries(table6.indexes).map((idx) => {
  91192. const { columns, ...rest } = idx[1];
  91193. const mappedColumns = columns.map((it2) => {
  91194. return {
  91195. expression: it2,
  91196. isExpression: false,
  91197. asc: true,
  91198. nulls: "last",
  91199. opClass: void 0
  91200. };
  91201. });
  91202. return [idx[0], { columns: mappedColumns, with: {}, ...rest }];
  91203. })
  91204. );
  91205. return [it[0], { ...table6, indexes: mappedIndexes, policies: {}, isRLSEnabled: false, checkConstraints: {} }];
  91206. })
  91207. );
  91208. return {
  91209. ...schema6,
  91210. version: "7",
  91211. dialect: "postgresql",
  91212. sequences: {},
  91213. tables,
  91214. policies: {},
  91215. views: {},
  91216. roles: {}
  91217. };
  91218. };
  91219. // src/cli/commands/singlestoreUp.ts
  91220. var upSinglestoreHandler = (out) => {
  91221. };
  91222. // src/cli/commands/sqliteUp.ts
  91223. init_source();
  91224. var import_fs10 = require("fs");
  91225. init_global();
  91226. init_sqliteSchema();
  91227. init_utils2();
  91228. var upSqliteHandler = (out) => {
  91229. const { snapshots } = prepareOutFolder(out, "sqlite");
  91230. const report = validateWithReport(snapshots, "sqlite");
  91231. report.nonLatest.map((it) => ({
  91232. path: it,
  91233. raw: report.rawMap[it]
  91234. })).forEach((it) => {
  91235. const path4 = it.path;
  91236. const result = updateUpToV62(it.raw);
  91237. console.log(`[${source_default.green("\u2713")}] ${path4}`);
  91238. (0, import_fs10.writeFileSync)(path4, JSON.stringify(result, null, 2));
  91239. });
  91240. console.log("Everything's fine \u{1F436}\u{1F525}");
  91241. };
  91242. var updateUpToV62 = (json) => {
  91243. const schema6 = sqliteSchemaV5.parse(json);
  91244. const tables = mapEntries(schema6.tables, (tableKey2, table6) => {
  91245. const columns = mapEntries(table6.columns, (key, value) => {
  91246. if (value.default && (typeof value.default === "object" || Array.isArray(value.default))) {
  91247. value.default = `'${JSON.stringify(value.default)}'`;
  91248. }
  91249. return [key, value];
  91250. });
  91251. table6.columns = columns;
  91252. return [tableKey2, table6];
  91253. });
  91254. return {
  91255. ...schema6,
  91256. version: "6",
  91257. dialect: "sqlite",
  91258. tables,
  91259. views: {}
  91260. };
  91261. };
  91262. // src/cli/schema.ts
  91263. init_utils3();
  91264. init_utils5();
  91265. init_common();
  91266. init_outputs();
  91267. init_views();
  91268. var optionDialect = string("dialect").enum(...dialects).desc(
  91269. `Database dialect: 'gel', 'postgresql', 'mysql', 'sqlite', 'turso' or 'singlestore'`
  91270. );
  91271. var optionOut = string().desc("Output folder, 'drizzle' by default");
  91272. var optionConfig = string().desc("Path to drizzle config file");
  91273. var optionBreakpoints = boolean().desc(
  91274. `Prepare SQL statements with breakpoints`
  91275. );
  91276. var optionDriver = string().enum(...drivers).desc("Database driver");
  91277. var optionCasing = string().enum("camelCase", "snake_case").desc("Casing for serialization");
  91278. var generate = command2({
  91279. name: "generate",
  91280. options: {
  91281. config: optionConfig,
  91282. dialect: optionDialect,
  91283. driver: optionDriver,
  91284. casing: optionCasing,
  91285. schema: string().desc("Path to a schema file or folder"),
  91286. out: optionOut,
  91287. name: string().desc("Migration file name"),
  91288. breakpoints: optionBreakpoints,
  91289. custom: boolean().desc("Prepare empty migration file for custom SQL").default(false),
  91290. prefix: string().enum(...prefixes).default("index")
  91291. },
  91292. transform: async (opts) => {
  91293. const from = assertCollisions(
  91294. "generate",
  91295. opts,
  91296. ["prefix", "name", "custom"],
  91297. ["driver", "breakpoints", "schema", "out", "dialect", "casing"]
  91298. );
  91299. return prepareGenerateConfig(opts, from);
  91300. },
  91301. handler: async (opts) => {
  91302. await assertOrmCoreVersion();
  91303. await assertPackages("drizzle-orm");
  91304. const {
  91305. prepareAndMigratePg: prepareAndMigratePg2,
  91306. prepareAndMigrateMysql: prepareAndMigrateMysql2,
  91307. prepareAndMigrateSqlite: prepareAndMigrateSqlite2,
  91308. prepareAndMigrateLibSQL: prepareAndMigrateLibSQL2,
  91309. prepareAndMigrateSingleStore: prepareAndMigrateSingleStore2
  91310. } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
  91311. const dialect6 = opts.dialect;
  91312. if (dialect6 === "postgresql") {
  91313. await prepareAndMigratePg2(opts);
  91314. } else if (dialect6 === "mysql") {
  91315. await prepareAndMigrateMysql2(opts);
  91316. } else if (dialect6 === "sqlite") {
  91317. await prepareAndMigrateSqlite2(opts);
  91318. } else if (dialect6 === "turso") {
  91319. await prepareAndMigrateLibSQL2(opts);
  91320. } else if (dialect6 === "singlestore") {
  91321. await prepareAndMigrateSingleStore2(opts);
  91322. } else if (dialect6 === "gel") {
  91323. console.log(
  91324. error(
  91325. `You can't use 'generate' command with Gel dialect`
  91326. )
  91327. );
  91328. process.exit(1);
  91329. } else {
  91330. assertUnreachable(dialect6);
  91331. }
  91332. }
  91333. });
  91334. var migrate = command2({
  91335. name: "migrate",
  91336. options: {
  91337. config: optionConfig
  91338. },
  91339. transform: async (opts) => {
  91340. return await prepareMigrateConfig(opts.config);
  91341. },
  91342. handler: async (opts) => {
  91343. await assertOrmCoreVersion();
  91344. await assertPackages("drizzle-orm");
  91345. const { dialect: dialect6, schema: schema6, table: table6, out, credentials: credentials2 } = opts;
  91346. try {
  91347. if (dialect6 === "postgresql") {
  91348. if ("driver" in credentials2) {
  91349. const { driver: driver2 } = credentials2;
  91350. if (driver2 === "aws-data-api") {
  91351. if (!await ormVersionGt("0.30.10")) {
  91352. console.log(
  91353. "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
  91354. );
  91355. process.exit(1);
  91356. }
  91357. } else if (driver2 === "pglite") {
  91358. if (!await ormVersionGt("0.30.6")) {
  91359. console.log(
  91360. "To use 'pglite' driver - please update drizzle-orm to the latest version"
  91361. );
  91362. process.exit(1);
  91363. }
  91364. } else {
  91365. assertUnreachable(driver2);
  91366. }
  91367. }
  91368. const { preparePostgresDB: preparePostgresDB2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  91369. const { migrate: migrate2 } = await preparePostgresDB2(credentials2);
  91370. await (0, import_hanji15.renderWithTask)(
  91371. new MigrateProgress(),
  91372. migrate2({
  91373. migrationsFolder: out,
  91374. migrationsTable: table6,
  91375. migrationsSchema: schema6
  91376. })
  91377. );
  91378. } else if (dialect6 === "mysql") {
  91379. const { connectToMySQL: connectToMySQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  91380. const { migrate: migrate2 } = await connectToMySQL2(credentials2);
  91381. await (0, import_hanji15.renderWithTask)(
  91382. new MigrateProgress(),
  91383. migrate2({
  91384. migrationsFolder: out,
  91385. migrationsTable: table6,
  91386. migrationsSchema: schema6
  91387. })
  91388. );
  91389. } else if (dialect6 === "singlestore") {
  91390. const { connectToSingleStore: connectToSingleStore2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  91391. const { migrate: migrate2 } = await connectToSingleStore2(credentials2);
  91392. await (0, import_hanji15.renderWithTask)(
  91393. new MigrateProgress(),
  91394. migrate2({
  91395. migrationsFolder: out,
  91396. migrationsTable: table6,
  91397. migrationsSchema: schema6
  91398. })
  91399. );
  91400. } else if (dialect6 === "sqlite") {
  91401. const { connectToSQLite: connectToSQLite2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  91402. const { migrate: migrate2 } = await connectToSQLite2(credentials2);
  91403. await (0, import_hanji15.renderWithTask)(
  91404. new MigrateProgress(),
  91405. migrate2({
  91406. migrationsFolder: opts.out,
  91407. migrationsTable: table6,
  91408. migrationsSchema: schema6
  91409. })
  91410. );
  91411. } else if (dialect6 === "turso") {
  91412. const { connectToLibSQL: connectToLibSQL2 } = await Promise.resolve().then(() => (init_connections(), connections_exports));
  91413. const { migrate: migrate2 } = await connectToLibSQL2(credentials2);
  91414. await (0, import_hanji15.renderWithTask)(
  91415. new MigrateProgress(),
  91416. migrate2({
  91417. migrationsFolder: opts.out,
  91418. migrationsTable: table6,
  91419. migrationsSchema: schema6
  91420. })
  91421. );
  91422. } else if (dialect6 === "gel") {
  91423. console.log(
  91424. error(
  91425. `You can't use 'migrate' command with Gel dialect`
  91426. )
  91427. );
  91428. process.exit(1);
  91429. } else {
  91430. assertUnreachable(dialect6);
  91431. }
  91432. } catch (e4) {
  91433. console.error(e4);
  91434. process.exit(1);
  91435. }
  91436. process.exit(0);
  91437. }
  91438. });
  91439. var optionsFilters = {
  91440. tablesFilter: string().desc("Table name filters"),
  91441. schemaFilters: string().desc("Schema name filters"),
  91442. extensionsFilters: string().desc(
  91443. "`Database extensions internal database filters"
  91444. )
  91445. };
  91446. var optionsDatabaseCredentials = {
  91447. url: string().desc("Database connection URL"),
  91448. host: string().desc("Database host"),
  91449. port: string().desc("Database port"),
  91450. user: string().desc("Database user"),
  91451. password: string().desc("Database password"),
  91452. database: string().desc("Database name"),
  91453. ssl: string().desc("ssl mode"),
  91454. // Turso
  91455. authToken: string("auth-token").desc("Database auth token [Turso]"),
  91456. // gel
  91457. tlsSecurity: string("tlsSecurity").desc("tls security mode"),
  91458. // specific cases
  91459. driver: optionDriver
  91460. };
  91461. var push = command2({
  91462. name: "push",
  91463. options: {
  91464. config: optionConfig,
  91465. dialect: optionDialect,
  91466. casing: optionCasing,
  91467. schema: string().desc("Path to a schema file or folder"),
  91468. ...optionsFilters,
  91469. ...optionsDatabaseCredentials,
  91470. verbose: boolean().desc("Print all statements for each push").default(false),
  91471. strict: boolean().desc("Always ask for confirmation").default(false),
  91472. force: boolean().desc(
  91473. "Auto-approve all data loss statements. Note: Data loss statements may truncate your tables and data"
  91474. ).default(false)
  91475. },
  91476. transform: async (opts) => {
  91477. const from = assertCollisions(
  91478. "push",
  91479. opts,
  91480. ["force", "verbose", "strict"],
  91481. [
  91482. "schema",
  91483. "dialect",
  91484. "driver",
  91485. "url",
  91486. "host",
  91487. "port",
  91488. "user",
  91489. "password",
  91490. "database",
  91491. "ssl",
  91492. "authToken",
  91493. "schemaFilters",
  91494. "extensionsFilters",
  91495. "tablesFilter",
  91496. "casing",
  91497. "tlsSecurity"
  91498. ]
  91499. );
  91500. return preparePushConfig(opts, from);
  91501. },
  91502. handler: async (config) => {
  91503. await assertPackages("drizzle-orm");
  91504. await assertOrmCoreVersion();
  91505. const {
  91506. dialect: dialect6,
  91507. schemaPath,
  91508. strict,
  91509. verbose,
  91510. credentials: credentials2,
  91511. tablesFilter,
  91512. schemasFilter,
  91513. force,
  91514. casing: casing2,
  91515. entities
  91516. } = config;
  91517. try {
  91518. if (dialect6 === "mysql") {
  91519. const { mysqlPush: mysqlPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
  91520. await mysqlPush2(
  91521. schemaPath,
  91522. credentials2,
  91523. tablesFilter,
  91524. strict,
  91525. verbose,
  91526. force,
  91527. casing2
  91528. );
  91529. } else if (dialect6 === "postgresql") {
  91530. if ("driver" in credentials2) {
  91531. const { driver: driver2 } = credentials2;
  91532. if (driver2 === "aws-data-api") {
  91533. if (!await ormVersionGt("0.30.10")) {
  91534. console.log(
  91535. "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
  91536. );
  91537. process.exit(1);
  91538. }
  91539. } else if (driver2 === "pglite") {
  91540. if (!await ormVersionGt("0.30.6")) {
  91541. console.log(
  91542. "To use 'pglite' driver - please update drizzle-orm to the latest version"
  91543. );
  91544. process.exit(1);
  91545. }
  91546. } else {
  91547. assertUnreachable(driver2);
  91548. }
  91549. }
  91550. const { pgPush: pgPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
  91551. await pgPush2(
  91552. schemaPath,
  91553. verbose,
  91554. strict,
  91555. credentials2,
  91556. tablesFilter,
  91557. schemasFilter,
  91558. entities,
  91559. force,
  91560. casing2
  91561. );
  91562. } else if (dialect6 === "sqlite") {
  91563. const { sqlitePush: sqlitePush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
  91564. await sqlitePush2(
  91565. schemaPath,
  91566. verbose,
  91567. strict,
  91568. credentials2,
  91569. tablesFilter,
  91570. force,
  91571. casing2
  91572. );
  91573. } else if (dialect6 === "turso") {
  91574. const { libSQLPush: libSQLPush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
  91575. await libSQLPush2(
  91576. schemaPath,
  91577. verbose,
  91578. strict,
  91579. credentials2,
  91580. tablesFilter,
  91581. force,
  91582. casing2
  91583. );
  91584. } else if (dialect6 === "singlestore") {
  91585. const { singlestorePush: singlestorePush2 } = await Promise.resolve().then(() => (init_push(), push_exports));
  91586. await singlestorePush2(
  91587. schemaPath,
  91588. credentials2,
  91589. tablesFilter,
  91590. strict,
  91591. verbose,
  91592. force,
  91593. casing2
  91594. );
  91595. } else if (dialect6 === "gel") {
  91596. console.log(
  91597. error(
  91598. `You can't use 'push' command with Gel dialect`
  91599. )
  91600. );
  91601. process.exit(1);
  91602. } else {
  91603. assertUnreachable(dialect6);
  91604. }
  91605. } catch (e4) {
  91606. console.error(e4);
  91607. }
  91608. process.exit(0);
  91609. }
  91610. });
  91611. var check = command2({
  91612. name: "check",
  91613. options: {
  91614. config: optionConfig,
  91615. dialect: optionDialect,
  91616. out: optionOut
  91617. },
  91618. transform: async (opts) => {
  91619. const from = assertCollisions("check", opts, [], ["dialect", "out"]);
  91620. return prepareCheckParams(opts, from);
  91621. },
  91622. handler: async (config) => {
  91623. await assertOrmCoreVersion();
  91624. const { out, dialect: dialect6 } = config;
  91625. checkHandler(out, dialect6);
  91626. console.log("Everything's fine \u{1F436}\u{1F525}");
  91627. }
  91628. });
  91629. var up = command2({
  91630. name: "up",
  91631. options: {
  91632. config: optionConfig,
  91633. dialect: optionDialect,
  91634. out: optionOut
  91635. },
  91636. transform: async (opts) => {
  91637. const from = assertCollisions("check", opts, [], ["dialect", "out"]);
  91638. return prepareCheckParams(opts, from);
  91639. },
  91640. handler: async (config) => {
  91641. await assertOrmCoreVersion();
  91642. const { out, dialect: dialect6 } = config;
  91643. await assertPackages("drizzle-orm");
  91644. if (dialect6 === "postgresql") {
  91645. upPgHandler(out);
  91646. }
  91647. if (dialect6 === "mysql") {
  91648. upMysqlHandler(out);
  91649. }
  91650. if (dialect6 === "sqlite" || dialect6 === "turso") {
  91651. upSqliteHandler(out);
  91652. }
  91653. if (dialect6 === "singlestore") {
  91654. upSinglestoreHandler(out);
  91655. }
  91656. if (dialect6 === "gel") {
  91657. console.log(
  91658. error(
  91659. `You can't use 'up' command with Gel dialect`
  91660. )
  91661. );
  91662. process.exit(1);
  91663. }
  91664. }
  91665. });
  91666. var pull = command2({
  91667. name: "introspect",
  91668. aliases: ["pull"],
  91669. options: {
  91670. config: optionConfig,
  91671. dialect: optionDialect,
  91672. out: optionOut,
  91673. breakpoints: optionBreakpoints,
  91674. casing: string("introspect-casing").enum("camel", "preserve"),
  91675. ...optionsFilters,
  91676. ...optionsDatabaseCredentials
  91677. },
  91678. transform: async (opts) => {
  91679. const from = assertCollisions(
  91680. "introspect",
  91681. opts,
  91682. [],
  91683. [
  91684. "dialect",
  91685. "driver",
  91686. "out",
  91687. "url",
  91688. "host",
  91689. "port",
  91690. "user",
  91691. "password",
  91692. "database",
  91693. "ssl",
  91694. "authToken",
  91695. "casing",
  91696. "breakpoints",
  91697. "tablesFilter",
  91698. "schemaFilters",
  91699. "extensionsFilters",
  91700. "tlsSecurity"
  91701. ]
  91702. );
  91703. return preparePullConfig(opts, from);
  91704. },
  91705. handler: async (config) => {
  91706. await assertPackages("drizzle-orm");
  91707. await assertOrmCoreVersion();
  91708. const {
  91709. dialect: dialect6,
  91710. credentials: credentials2,
  91711. out,
  91712. casing: casing2,
  91713. breakpoints,
  91714. tablesFilter,
  91715. schemasFilter,
  91716. prefix: prefix2,
  91717. entities
  91718. } = config;
  91719. (0, import_fs13.mkdirSync)(out, { recursive: true });
  91720. console.log(
  91721. grey(
  91722. `Pulling from [${schemasFilter.map((it) => `'${it}'`).join(", ")}] list of schemas`
  91723. )
  91724. );
  91725. console.log();
  91726. try {
  91727. if (dialect6 === "postgresql") {
  91728. if ("driver" in credentials2) {
  91729. const { driver: driver2 } = credentials2;
  91730. if (driver2 === "aws-data-api") {
  91731. if (!await ormVersionGt("0.30.10")) {
  91732. console.log(
  91733. "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
  91734. );
  91735. process.exit(1);
  91736. }
  91737. } else if (driver2 === "pglite") {
  91738. if (!await ormVersionGt("0.30.6")) {
  91739. console.log(
  91740. "To use 'pglite' driver - please update drizzle-orm to the latest version"
  91741. );
  91742. process.exit(1);
  91743. }
  91744. } else {
  91745. assertUnreachable(driver2);
  91746. }
  91747. }
  91748. const { introspectPostgres: introspectPostgres2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
  91749. await introspectPostgres2(
  91750. casing2,
  91751. out,
  91752. breakpoints,
  91753. credentials2,
  91754. tablesFilter,
  91755. schemasFilter,
  91756. prefix2,
  91757. entities
  91758. );
  91759. } else if (dialect6 === "mysql") {
  91760. const { introspectMysql: introspectMysql2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
  91761. await introspectMysql2(
  91762. casing2,
  91763. out,
  91764. breakpoints,
  91765. credentials2,
  91766. tablesFilter,
  91767. prefix2
  91768. );
  91769. } else if (dialect6 === "sqlite") {
  91770. const { introspectSqlite: introspectSqlite2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
  91771. await introspectSqlite2(
  91772. casing2,
  91773. out,
  91774. breakpoints,
  91775. credentials2,
  91776. tablesFilter,
  91777. prefix2
  91778. );
  91779. } else if (dialect6 === "turso") {
  91780. const { introspectLibSQL: introspectLibSQL2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
  91781. await introspectLibSQL2(
  91782. casing2,
  91783. out,
  91784. breakpoints,
  91785. credentials2,
  91786. tablesFilter,
  91787. prefix2
  91788. );
  91789. } else if (dialect6 === "singlestore") {
  91790. const { introspectSingleStore: introspectSingleStore2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
  91791. await introspectSingleStore2(
  91792. casing2,
  91793. out,
  91794. breakpoints,
  91795. credentials2,
  91796. tablesFilter,
  91797. prefix2
  91798. );
  91799. } else if (dialect6 === "gel") {
  91800. const { introspectGel: introspectGel2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
  91801. await introspectGel2(
  91802. casing2,
  91803. out,
  91804. breakpoints,
  91805. credentials2,
  91806. tablesFilter,
  91807. schemasFilter,
  91808. prefix2,
  91809. entities
  91810. );
  91811. } else {
  91812. assertUnreachable(dialect6);
  91813. }
  91814. } catch (e4) {
  91815. console.error(e4);
  91816. }
  91817. process.exit(0);
  91818. }
  91819. });
  91820. var drop = command2({
  91821. name: "drop",
  91822. options: {
  91823. config: optionConfig,
  91824. out: optionOut,
  91825. driver: optionDriver
  91826. },
  91827. transform: async (opts) => {
  91828. const from = assertCollisions("check", opts, [], ["driver", "out"]);
  91829. return prepareDropParams(opts, from);
  91830. },
  91831. handler: async (config) => {
  91832. await assertOrmCoreVersion();
  91833. assertV1OutFolder(config.out);
  91834. await dropMigration(config);
  91835. }
  91836. });
  91837. var studio = command2({
  91838. name: "studio",
  91839. options: {
  91840. config: optionConfig,
  91841. port: number().desc("Custom port for drizzle studio [default=4983]"),
  91842. host: string().desc("Custom host for drizzle studio [default=0.0.0.0]"),
  91843. verbose: boolean().default(false).desc("Print all stataments that are executed by Studio")
  91844. },
  91845. handler: async (opts) => {
  91846. await assertOrmCoreVersion();
  91847. await assertPackages("drizzle-orm");
  91848. assertStudioNodeVersion();
  91849. const {
  91850. dialect: dialect6,
  91851. schema: schemaPath,
  91852. port,
  91853. host,
  91854. credentials: credentials2,
  91855. casing: casing2
  91856. } = await prepareStudioConfig(opts);
  91857. const {
  91858. drizzleForPostgres: drizzleForPostgres2,
  91859. preparePgSchema: preparePgSchema2,
  91860. prepareMySqlSchema: prepareMySqlSchema2,
  91861. drizzleForMySQL: drizzleForMySQL2,
  91862. prepareSQLiteSchema: prepareSQLiteSchema2,
  91863. drizzleForSQLite: drizzleForSQLite2,
  91864. prepareSingleStoreSchema: prepareSingleStoreSchema2,
  91865. drizzleForSingleStore: drizzleForSingleStore2,
  91866. drizzleForLibSQL: drizzleForLibSQL2
  91867. } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  91868. let setup;
  91869. try {
  91870. if (dialect6 === "postgresql") {
  91871. if ("driver" in credentials2) {
  91872. const { driver: driver2 } = credentials2;
  91873. if (driver2 === "aws-data-api") {
  91874. if (!await ormVersionGt("0.30.10")) {
  91875. console.log(
  91876. "To use 'aws-data-api' driver - please update drizzle-orm to the latest version"
  91877. );
  91878. process.exit(1);
  91879. }
  91880. } else if (driver2 === "pglite") {
  91881. if (!await ormVersionGt("0.30.6")) {
  91882. console.log(
  91883. "To use 'pglite' driver - please update drizzle-orm to the latest version"
  91884. );
  91885. process.exit(1);
  91886. }
  91887. } else {
  91888. assertUnreachable(driver2);
  91889. }
  91890. }
  91891. const { schema: schema6, relations: relations5, files } = schemaPath ? await preparePgSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
  91892. setup = await drizzleForPostgres2(credentials2, schema6, relations5, files, casing2);
  91893. } else if (dialect6 === "mysql") {
  91894. const { schema: schema6, relations: relations5, files } = schemaPath ? await prepareMySqlSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
  91895. setup = await drizzleForMySQL2(credentials2, schema6, relations5, files, casing2);
  91896. } else if (dialect6 === "sqlite") {
  91897. const { schema: schema6, relations: relations5, files } = schemaPath ? await prepareSQLiteSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
  91898. setup = await drizzleForSQLite2(credentials2, schema6, relations5, files, casing2);
  91899. } else if (dialect6 === "turso") {
  91900. const { schema: schema6, relations: relations5, files } = schemaPath ? await prepareSQLiteSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
  91901. setup = await drizzleForLibSQL2(credentials2, schema6, relations5, files, casing2);
  91902. } else if (dialect6 === "singlestore") {
  91903. const { schema: schema6, relations: relations5, files } = schemaPath ? await prepareSingleStoreSchema2(schemaPath) : { schema: {}, relations: {}, files: [] };
  91904. setup = await drizzleForSingleStore2(
  91905. credentials2,
  91906. schema6,
  91907. relations5,
  91908. files,
  91909. casing2
  91910. );
  91911. } else if (dialect6 === "gel") {
  91912. console.log(
  91913. error(
  91914. `You can't use 'studio' command with Gel dialect`
  91915. )
  91916. );
  91917. process.exit(1);
  91918. } else {
  91919. assertUnreachable(dialect6);
  91920. }
  91921. const { prepareServer: prepareServer2 } = await Promise.resolve().then(() => (init_studio2(), studio_exports));
  91922. const server = await prepareServer2(setup);
  91923. console.log();
  91924. console.log(
  91925. withStyle.fullWarning(
  91926. "Drizzle Studio is currently in Beta. If you find anything that is not working as expected or should be improved, feel free to create an issue on GitHub: https://github.com/drizzle-team/drizzle-kit-mirror/issues/new or write to us on Discord: https://discord.gg/WcRKz2FFxN"
  91927. )
  91928. );
  91929. const { key, cert } = await certs() || {};
  91930. server.start({
  91931. host,
  91932. port,
  91933. key,
  91934. cert,
  91935. cb: (err2, _address) => {
  91936. if (err2) {
  91937. console.error(err2);
  91938. } else {
  91939. const queryParams = {};
  91940. if (port !== 4983) {
  91941. queryParams.port = port;
  91942. }
  91943. if (host !== "127.0.0.1") {
  91944. queryParams.host = host;
  91945. }
  91946. const queryString = Object.keys(queryParams).map((key2) => {
  91947. return `${key2}=${queryParams[key2]}`;
  91948. }).join("&");
  91949. console.log(
  91950. `
  91951. Drizzle Studio is up and running on ${source_default.blue(
  91952. `https://local.drizzle.studio${queryString ? `?${queryString}` : ""}`
  91953. )}`
  91954. );
  91955. }
  91956. }
  91957. });
  91958. } catch (e4) {
  91959. console.error(e4);
  91960. process.exit(0);
  91961. }
  91962. }
  91963. });
  91964. var exportRaw = command2({
  91965. name: "export",
  91966. desc: "Generate diff between current state and empty state in specified formats: sql",
  91967. options: {
  91968. sql: boolean("sql").default(true).desc("Generate as sql"),
  91969. config: optionConfig,
  91970. dialect: optionDialect,
  91971. schema: string().desc("Path to a schema file or folder")
  91972. },
  91973. transform: async (opts) => {
  91974. const from = assertCollisions("export", opts, ["sql"], ["dialect", "schema"]);
  91975. return prepareExportConfig(opts, from);
  91976. },
  91977. handler: async (opts) => {
  91978. await assertOrmCoreVersion();
  91979. await assertPackages("drizzle-orm");
  91980. const {
  91981. prepareAndExportPg: prepareAndExportPg2,
  91982. prepareAndExportMysql: prepareAndExportMysql2,
  91983. prepareAndExportSqlite: prepareAndExportSqlite2,
  91984. prepareAndExportLibSQL: prepareAndExportLibSQL2,
  91985. prepareAndExportSinglestore: prepareAndExportSinglestore2
  91986. } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
  91987. const dialect6 = opts.dialect;
  91988. if (dialect6 === "postgresql") {
  91989. await prepareAndExportPg2(opts);
  91990. } else if (dialect6 === "mysql") {
  91991. await prepareAndExportMysql2(opts);
  91992. } else if (dialect6 === "sqlite") {
  91993. await prepareAndExportSqlite2(opts);
  91994. } else if (dialect6 === "turso") {
  91995. await prepareAndExportLibSQL2(opts);
  91996. } else if (dialect6 === "singlestore") {
  91997. await prepareAndExportSinglestore2(opts);
  91998. } else if (dialect6 === "gel") {
  91999. console.log(
  92000. error(
  92001. `You can't use 'export' command with Gel dialect`
  92002. )
  92003. );
  92004. process.exit(1);
  92005. } else {
  92006. assertUnreachable(dialect6);
  92007. }
  92008. }
  92009. });
  92010. // src/cli/index.ts
  92011. init_utils5();
  92012. var version2 = async () => {
  92013. const { npmVersion } = await ormCoreVersions();
  92014. const ormVersion = npmVersion ? `drizzle-orm: v${npmVersion}` : "";
  92015. const envVersion = "0.31.10";
  92016. const kitVersion = envVersion ? `v${envVersion}` : "--";
  92017. const versions = `drizzle-kit: ${kitVersion}
  92018. ${ormVersion}`;
  92019. console.log(source_default.gray(versions), "\n");
  92020. };
  92021. var legacyCommand = (name, newName) => {
  92022. return command2({
  92023. name,
  92024. hidden: true,
  92025. handler: () => {
  92026. console.log(
  92027. `This command is deprecated, please use updated '${newName}' command (see https://orm.drizzle.team/kit-docs/upgrade-21#how-to-migrate-to-0210)`
  92028. );
  92029. }
  92030. });
  92031. };
  92032. var legacy = [
  92033. legacyCommand("generate:pg", "generate"),
  92034. legacyCommand("generate:mysql", "generate"),
  92035. legacyCommand("generate:sqlite", "generate"),
  92036. legacyCommand("push:pg", "push"),
  92037. legacyCommand("push:mysql", "push"),
  92038. legacyCommand("push:sqlite", "push"),
  92039. legacyCommand("introspect:pg", "introspect"),
  92040. legacyCommand("introspect:mysql", "introspect"),
  92041. legacyCommand("introspect:sqlite", "introspect"),
  92042. legacyCommand("up:pg", "up"),
  92043. legacyCommand("up:mysql", "up"),
  92044. legacyCommand("up:sqlite", "up"),
  92045. legacyCommand("check:pg", "check"),
  92046. legacyCommand("check:mysql", "check"),
  92047. legacyCommand("check:sqlite", "check")
  92048. ];
  92049. run([generate, migrate, pull, push, studio, up, check, drop, exportRaw, ...legacy], {
  92050. name: "drizzle-kit",
  92051. version: version2
  92052. });
  92053. /*! Bundled license information:
  92054. web-streams-polyfill/dist/ponyfill.es2018.js:
  92055. (**
  92056. * @license
  92057. * web-streams-polyfill v3.3.3
  92058. * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
  92059. * This code is released under the MIT license.
  92060. * SPDX-License-Identifier: MIT
  92061. *)
  92062. fetch-blob/index.js:
  92063. (*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
  92064. formdata-polyfill/esm.min.js:
  92065. (*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
  92066. node-domexception/index.js:
  92067. (*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)
  92068. gel/dist/primitives/chars.js:
  92069. gel/dist/primitives/buffer.js:
  92070. gel/dist/errors/index.js:
  92071. gel/dist/primitives/lru.js:
  92072. gel/dist/codecs/consts.js:
  92073. gel/dist/codecs/ifaces.js:
  92074. gel/dist/codecs/boolean.js:
  92075. gel/dist/codecs/numbers.js:
  92076. gel/dist/codecs/numerics.js:
  92077. gel/dist/codecs/text.js:
  92078. gel/dist/codecs/uuid.js:
  92079. gel/dist/codecs/bytes.js:
  92080. gel/dist/codecs/json.js:
  92081. gel/dist/datatypes/datetime.js:
  92082. gel/dist/codecs/datetime.js:
  92083. gel/dist/datatypes/memory.js:
  92084. gel/dist/codecs/memory.js:
  92085. gel/dist/codecs/pgvector.js:
  92086. gel/dist/codecs/codecs.js:
  92087. gel/dist/codecs/tuple.js:
  92088. gel/dist/datatypes/range.js:
  92089. gel/dist/codecs/range.js:
  92090. gel/dist/codecs/namedtuple.js:
  92091. gel/dist/codecs/array.js:
  92092. gel/dist/codecs/enum.js:
  92093. gel/dist/codecs/object.js:
  92094. gel/dist/codecs/set.js:
  92095. gel/dist/codecs/record.js:
  92096. gel/dist/codecs/sparseObject.js:
  92097. gel/dist/codecs/registry.js:
  92098. gel/dist/retry.js:
  92099. gel/dist/conUtils.js:
  92100. gel/dist/errors/map.js:
  92101. gel/dist/errors/resolve.js:
  92102. gel/dist/baseConn.js:
  92103. gel/dist/scram.js:
  92104. gel/dist/rawConn.js:
  92105. gel/dist/index.shared.js:
  92106. gel/dist/index.node.js:
  92107. (*!
  92108. * This source file is part of the Gel open source project.
  92109. *
  92110. * Copyright 2019-present MagicStack Inc. and the Gel authors.
  92111. *
  92112. * Licensed under the Apache License, Version 2.0 (the "License");
  92113. * you may not use this file except in compliance with the License.
  92114. * You may obtain a copy of the License at
  92115. *
  92116. * http://www.apache.org/licenses/LICENSE-2.0
  92117. *
  92118. * Unless required by applicable law or agreed to in writing, software
  92119. * distributed under the License is distributed on an "AS IS" BASIS,
  92120. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  92121. * See the License for the specific language governing permissions and
  92122. * limitations under the License.
  92123. *)
  92124. gel/dist/datatypes/dateutil.js:
  92125. (*!
  92126. * Portions Copyright (c) 2019 MagicStack Inc. and the Gel authors.
  92127. * Portions Copyright (c) 2001-2019 Python Software Foundation.
  92128. * All rights reserved.
  92129. * Licence: PSFL https://docs.python.org/3/license.html
  92130. *)
  92131. gel/dist/utils.js:
  92132. gel/dist/ifaces.js:
  92133. gel/dist/primitives/queues.js:
  92134. gel/dist/baseClient.js:
  92135. gel/dist/reflection/strictMap.js:
  92136. gel/dist/reflection/index.js:
  92137. (*!
  92138. * This source file is part of the Gel open source project.
  92139. *
  92140. * Copyright 2020-present MagicStack Inc. and the Gel authors.
  92141. *
  92142. * Licensed under the Apache License, Version 2.0 (the "License");
  92143. * you may not use this file except in compliance with the License.
  92144. * You may obtain a copy of the License at
  92145. *
  92146. * http://www.apache.org/licenses/LICENSE-2.0
  92147. *
  92148. * Unless required by applicable law or agreed to in writing, software
  92149. * distributed under the License is distributed on an "AS IS" BASIS,
  92150. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  92151. * See the License for the specific language governing permissions and
  92152. * limitations under the License.
  92153. *)
  92154. gel/dist/primitives/event.js:
  92155. (*!
  92156. * This source file is part of the Gel open source project.
  92157. *
  92158. * Copyright 2021-present MagicStack Inc. and the Gel authors.
  92159. *
  92160. * Licensed under the Apache License, Version 2.0 (the "License");
  92161. * you may not use this file except in compliance with the License.
  92162. * You may obtain a copy of the License at
  92163. *
  92164. * http://www.apache.org/licenses/LICENSE-2.0
  92165. *
  92166. * Unless required by applicable law or agreed to in writing, software
  92167. * distributed under the License is distributed on an "AS IS" BASIS,
  92168. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  92169. * See the License for the specific language governing permissions and
  92170. * limitations under the License.
  92171. *)
  92172. gel/dist/fetchConn.js:
  92173. (*!
  92174. * This source file is part of the Gel open source project.
  92175. *
  92176. * Copyright 2022-present MagicStack Inc. and the Gel authors.
  92177. *
  92178. * Licensed under the Apache License, Version 2.0 (the "License");
  92179. * you may not use this file except in compliance with the License.
  92180. * You may obtain a copy of the License at
  92181. *
  92182. * http://www.apache.org/licenses/LICENSE-2.0
  92183. *
  92184. * Unless required by applicable law or agreed to in writing, software
  92185. * distributed under the License is distributed on an "AS IS" BASIS,
  92186. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  92187. * See the License for the specific language governing permissions and
  92188. * limitations under the License.
  92189. *)
  92190. */