| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414 |
- #!/usr/bin/env node
- "use strict";
- var __create = Object.create;
- var __defProp = Object.defineProperty;
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
- var __getOwnPropNames = Object.getOwnPropertyNames;
- var __getProtoOf = Object.getPrototypeOf;
- var __hasOwnProp = Object.prototype.hasOwnProperty;
- var __commonJS = (cb, mod) => function __require() {
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
- };
- var __export = (target, all) => {
- for (var name in all)
- __defProp(target, name, { get: all[name], enumerable: true });
- };
- var __copyProps = (to, from, except, desc) => {
- if (from && typeof from === "object" || typeof from === "function") {
- for (let key of __getOwnPropNames(from))
- if (!__hasOwnProp.call(to, key) && key !== except)
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
- }
- return to;
- };
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
- // If the importer is in node compatibility mode or this is not an ESM
- // file that has been converted to a CommonJS file using a Babel-
- // compatible transform (i.e. "__esModule" has not been set), then set
- // "default" to the CommonJS "module.exports" for node compatibility.
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
- mod
- ));
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
- // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/readline.js
- var require_readline = __commonJS({
- "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/readline.js"(exports2) {
- "use strict";
- var __importDefault = exports2 && exports2.__importDefault || function(mod) {
- return mod && mod.__esModule ? mod : { "default": mod };
- };
- Object.defineProperty(exports2, "__esModule", { value: true });
- exports2.createClosable = exports2.stdout = exports2.stdin = void 0;
- var readline_1 = __importDefault(require("readline"));
- exports2.stdin = process.stdin;
- exports2.stdout = process.stdout;
- readline_1.default.emitKeypressEvents(exports2.stdin);
- var createClosable = () => {
- return readline_1.default.createInterface({
- input: exports2.stdin,
- escapeCodeTimeout: 50
- });
- };
- exports2.createClosable = createClosable;
- }
- });
- // ../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
- var require_src = __commonJS({
- "../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2, module2) {
- "use strict";
- var ESC = "\x1B";
- var CSI = `${ESC}[`;
- var beep = "\x07";
- var cursor = {
- to(x, y) {
- if (!y) return `${CSI}${x + 1}G`;
- return `${CSI}${y + 1};${x + 1}H`;
- },
- move(x, y) {
- let ret = "";
- if (x < 0) ret += `${CSI}${-x}D`;
- else if (x > 0) ret += `${CSI}${x}C`;
- if (y < 0) ret += `${CSI}${-y}A`;
- else if (y > 0) ret += `${CSI}${y}B`;
- return ret;
- },
- up: (count = 1) => `${CSI}${count}A`,
- down: (count = 1) => `${CSI}${count}B`,
- forward: (count = 1) => `${CSI}${count}C`,
- backward: (count = 1) => `${CSI}${count}D`,
- nextLine: (count = 1) => `${CSI}E`.repeat(count),
- prevLine: (count = 1) => `${CSI}F`.repeat(count),
- left: `${CSI}G`,
- hide: `${CSI}?25l`,
- show: `${CSI}?25h`,
- save: `${ESC}7`,
- restore: `${ESC}8`
- };
- var scroll = {
- up: (count = 1) => `${CSI}S`.repeat(count),
- down: (count = 1) => `${CSI}T`.repeat(count)
- };
- var erase = {
- screen: `${CSI}2J`,
- up: (count = 1) => `${CSI}1J`.repeat(count),
- down: (count = 1) => `${CSI}J`.repeat(count),
- line: `${CSI}2K`,
- lineEnd: `${CSI}K`,
- lineStart: `${CSI}1K`,
- lines(count) {
- let clear = "";
- for (let i = 0; i < count; i++)
- clear += this.line + (i < count - 1 ? cursor.up() : "");
- if (count)
- clear += cursor.left;
- return clear;
- }
- };
- module2.exports = { cursor, scroll, erase, beep };
- }
- });
- // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/utils.js
- var require_utils = __commonJS({
- "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/utils.js"(exports2) {
- "use strict";
- Object.defineProperty(exports2, "__esModule", { value: true });
- exports2.clear = exports2.stringWidth = exports2.fallbackStringWidth = exports2.stripAnsi = exports2.strip = void 0;
- var sisteransi_1 = require_src();
- var strip = (str) => {
- const pattern = [
- "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
- "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
- ].join("|");
- const RGX = new RegExp(pattern, "g");
- return typeof str === "string" ? str.replace(RGX, "") : str;
- };
- exports2.strip = strip;
- var stripAnsi = (str) => {
- if (typeof Bun !== "undefined" && Bun.stripANSI) {
- return Bun.stripANSI(str);
- }
- return (0, exports2.strip)(str);
- };
- exports2.stripAnsi = stripAnsi;
- var fallbackStringWidth = (str) => {
- let len = 0;
- const stripped = (0, exports2.stripAnsi)(str);
- for (const _ of stripped)
- len++;
- return len;
- };
- exports2.fallbackStringWidth = fallbackStringWidth;
- var stringWidth = (str) => {
- if (typeof Bun !== "undefined" && Bun.stringWidth)
- return Bun.stringWidth(str);
- return (0, exports2.fallbackStringWidth)(str);
- };
- exports2.stringWidth = stringWidth;
- var clear = function(prompt, perLine) {
- if (!perLine)
- return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
- let rows = 0;
- const lines = prompt.split(/\r?\n/);
- for (let line of lines) {
- rows += 1 + Math.floor(Math.max((0, exports2.stringWidth)(line) - 1, 0) / perLine);
- }
- return sisteransi_1.erase.lines(rows);
- };
- exports2.clear = clear;
- }
- });
- // ../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
- var require_lodash = __commonJS({
- "../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports2, module2) {
- var FUNC_ERROR_TEXT = "Expected a function";
- var NAN = 0 / 0;
- var symbolTag = "[object Symbol]";
- var reTrim = /^\s+|\s+$/g;
- var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
- var reIsBinary = /^0b[01]+$/i;
- var reIsOctal = /^0o[0-7]+$/i;
- var freeParseInt = parseInt;
- var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
- var freeSelf = typeof self == "object" && self && self.Object === Object && self;
- var root = freeGlobal || freeSelf || Function("return this")();
- var objectProto = Object.prototype;
- var objectToString = objectProto.toString;
- var nativeMax = Math.max;
- var nativeMin = Math.min;
- var now = function() {
- return root.Date.now();
- };
- function debounce(func, wait, options) {
- var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
- if (typeof func != "function") {
- throw new TypeError(FUNC_ERROR_TEXT);
- }
- wait = toNumber(wait) || 0;
- if (isObject(options)) {
- leading = !!options.leading;
- maxing = "maxWait" in options;
- maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
- trailing = "trailing" in options ? !!options.trailing : trailing;
- }
- function invokeFunc(time) {
- var args = lastArgs, thisArg = lastThis;
- lastArgs = lastThis = void 0;
- lastInvokeTime = time;
- result = func.apply(thisArg, args);
- return result;
- }
- function leadingEdge(time) {
- lastInvokeTime = time;
- timerId = setTimeout(timerExpired, wait);
- return leading ? invokeFunc(time) : result;
- }
- function remainingWait(time) {
- var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
- return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
- }
- function shouldInvoke(time) {
- var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
- return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
- }
- function timerExpired() {
- var time = now();
- if (shouldInvoke(time)) {
- return trailingEdge(time);
- }
- timerId = setTimeout(timerExpired, remainingWait(time));
- }
- function trailingEdge(time) {
- timerId = void 0;
- if (trailing && lastArgs) {
- return invokeFunc(time);
- }
- lastArgs = lastThis = void 0;
- return result;
- }
- function cancel() {
- if (timerId !== void 0) {
- clearTimeout(timerId);
- }
- lastInvokeTime = 0;
- lastArgs = lastCallTime = lastThis = timerId = void 0;
- }
- function flush() {
- return timerId === void 0 ? result : trailingEdge(now());
- }
- function debounced() {
- var time = now(), isInvoking = shouldInvoke(time);
- lastArgs = arguments;
- lastThis = this;
- lastCallTime = time;
- if (isInvoking) {
- if (timerId === void 0) {
- return leadingEdge(lastCallTime);
- }
- if (maxing) {
- timerId = setTimeout(timerExpired, wait);
- return invokeFunc(lastCallTime);
- }
- }
- if (timerId === void 0) {
- timerId = setTimeout(timerExpired, wait);
- }
- return result;
- }
- debounced.cancel = cancel;
- debounced.flush = flush;
- return debounced;
- }
- function throttle(func, wait, options) {
- var leading = true, trailing = true;
- if (typeof func != "function") {
- throw new TypeError(FUNC_ERROR_TEXT);
- }
- if (isObject(options)) {
- leading = "leading" in options ? !!options.leading : leading;
- trailing = "trailing" in options ? !!options.trailing : trailing;
- }
- return debounce(func, wait, {
- "leading": leading,
- "maxWait": wait,
- "trailing": trailing
- });
- }
- function isObject(value) {
- var type = typeof value;
- return !!value && (type == "object" || type == "function");
- }
- function isObjectLike(value) {
- return !!value && typeof value == "object";
- }
- function isSymbol(value) {
- return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
- }
- function toNumber(value) {
- if (typeof value == "number") {
- return value;
- }
- if (isSymbol(value)) {
- return NAN;
- }
- if (isObject(value)) {
- var other = typeof value.valueOf == "function" ? value.valueOf() : value;
- value = isObject(other) ? other + "" : other;
- }
- if (typeof value != "string") {
- return value === 0 ? value : +value;
- }
- value = value.replace(reTrim, "");
- var isBinary = reIsBinary.test(value);
- return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
- }
- module2.exports = throttle;
- }
- });
- // ../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/index.js
- var require_hanji = __commonJS({
- "../node_modules/.pnpm/hanji@0.0.8/node_modules/hanji/index.js"(exports2) {
- "use strict";
- var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
- function adopt(value) {
- return value instanceof P ? value : new P(function(resolve) {
- resolve(value);
- });
- }
- return new (P || (P = Promise))(function(resolve, reject) {
- function fulfilled(value) {
- try {
- step(generator.next(value));
- } catch (e) {
- reject(e);
- }
- }
- function rejected(value) {
- try {
- step(generator["throw"](value));
- } catch (e) {
- reject(e);
- }
- }
- function step(result) {
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
- }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __importDefault = exports2 && exports2.__importDefault || function(mod) {
- return mod && mod.__esModule ? mod : { "default": mod };
- };
- Object.defineProperty(exports2, "__esModule", { value: true });
- exports2.TaskTerminal = exports2.TaskView = exports2.Terminal = exports2.deferred = exports2.SelectState = exports2.Prompt = void 0;
- exports2.render = render2;
- exports2.renderWithTask = renderWithTask;
- exports2.onTerminate = onTerminate;
- var readline_1 = require_readline();
- var sisteransi_1 = require_src();
- var utils_1 = require_utils();
- var lodash_throttle_1 = __importDefault(require_lodash());
- var Prompt2 = class {
- constructor() {
- this.attachCallbacks = [];
- this.detachCallbacks = [];
- this.inputCallbacks = [];
- }
- requestLayout() {
- this.terminal.requestLayout();
- }
- on(type, callback) {
- if (type === "attach") {
- this.attachCallbacks.push(callback);
- } else if (type === "detach") {
- this.detachCallbacks.push(callback);
- } else if (type === "input") {
- this.inputCallbacks.push(callback);
- }
- }
- attach(terminal) {
- this.terminal = terminal;
- this.attachCallbacks.forEach((it) => it(terminal));
- }
- detach(terminal) {
- this.detachCallbacks.forEach((it) => it(terminal));
- this.terminal = void 0;
- }
- input(str, key) {
- this.inputCallbacks.forEach((it) => it(str, key));
- }
- };
- exports2.Prompt = Prompt2;
- var SelectState2 = class {
- constructor(items) {
- this.items = items;
- this.selectedIdx = 0;
- }
- bind(prompt) {
- prompt.on("input", (str, key) => {
- const invalidate = this.consume(str, key);
- if (invalidate)
- prompt.requestLayout();
- });
- }
- consume(str, key) {
- if (!key)
- return false;
- if (key.name === "down") {
- this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
- return true;
- }
- if (key.name === "up") {
- this.selectedIdx -= 1;
- this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
- return true;
- }
- return false;
- }
- };
- exports2.SelectState = SelectState2;
- var deferred = () => {
- let resolve;
- let reject;
- const promise = new Promise((res, rej) => {
- resolve = res;
- reject = rej;
- });
- return {
- resolve,
- reject,
- promise
- };
- };
- exports2.deferred = deferred;
- var Terminal = class {
- constructor(view5, stdin, stdout, closable) {
- this.view = view5;
- this.stdin = stdin;
- this.stdout = stdout;
- this.closable = closable;
- this.text = "";
- this.status = "idle";
- if (this.stdin.isTTY)
- this.stdin.setRawMode(true);
- const keypress = (str, key) => {
- if (key.name === "c" && key.ctrl === true) {
- this.requestLayout();
- this.view.detach(this);
- this.tearDown(keypress);
- if (terminateHandler) {
- terminateHandler(this.stdin, this.stdout);
- return;
- }
- this.stdout.write(`
- ^C
- `);
- process.exit(1);
- }
- if (key.name === "escape") {
- this.status = "aborted";
- this.requestLayout();
- this.view.detach(this);
- this.tearDown(keypress);
- this.resolve({ status: "aborted", data: void 0 });
- return;
- }
- if (key.name === "return") {
- this.status = "submitted";
- this.requestLayout();
- this.view.detach(this);
- this.tearDown(keypress);
- this.resolve({ status: "submitted", data: this.view.result() });
- return;
- }
- view5.input(str, key);
- };
- this.stdin.on("keypress", keypress);
- this.view.attach(this);
- const { resolve, promise } = (0, exports2.deferred)();
- this.resolve = resolve;
- this.promise = promise;
- this.renderFunc = (0, lodash_throttle_1.default)((str) => {
- this.stdout.write(str);
- });
- }
- tearDown(keypress) {
- this.stdout.write(sisteransi_1.cursor.show);
- this.stdin.removeListener("keypress", keypress);
- if (this.stdin.isTTY)
- this.stdin.setRawMode(false);
- this.closable.close();
- }
- result() {
- return this.promise;
- }
- toggleCursor(state) {
- if (state === "hide") {
- this.stdout.write(sisteransi_1.cursor.hide);
- } else {
- this.stdout.write(sisteransi_1.cursor.show);
- }
- }
- requestLayout() {
- const string = this.view.render(this.status);
- const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
- this.text = string;
- this.renderFunc(`${clearPrefix}${string}`);
- }
- };
- exports2.Terminal = Terminal;
- var TaskView2 = class {
- constructor() {
- this.attachCallbacks = [];
- this.detachCallbacks = [];
- }
- requestLayout() {
- this.terminal.requestLayout();
- }
- attach(terminal) {
- this.terminal = terminal;
- this.attachCallbacks.forEach((it) => it(terminal));
- }
- detach(terminal) {
- this.detachCallbacks.forEach((it) => it(terminal));
- this.terminal = void 0;
- }
- on(type, callback) {
- if (type === "attach") {
- this.attachCallbacks.push(callback);
- } else if (type === "detach") {
- this.detachCallbacks.push(callback);
- }
- }
- };
- exports2.TaskView = TaskView2;
- var TaskTerminal = class {
- constructor(view5, stdout) {
- this.view = view5;
- this.stdout = stdout;
- this.text = "";
- this.view.attach(this);
- }
- requestLayout() {
- const string = this.view.render("pending");
- const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
- this.text = string;
- this.stdout.write(`${clearPrefix}${string}`);
- }
- clear() {
- const string = this.view.render("done");
- this.view.detach(this);
- const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
- this.stdout.write(`${clearPrefix}${string}`);
- }
- reject(err) {
- const string = this.view.render("rejected", err);
- this.view.detach(this);
- const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
- this.stdout.write(`${clearPrefix}${string}`);
- }
- };
- exports2.TaskTerminal = TaskTerminal;
- function render2(view5) {
- if (typeof view5 === "string") {
- process.stdout.write(`${view5}
- `);
- return;
- }
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
- 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."));
- }
- const closable = (0, readline_1.createClosable)();
- const terminal = new Terminal(view5, readline_1.stdin, readline_1.stdout, closable);
- terminal.requestLayout();
- return terminal.result();
- }
- function renderWithTask(view5, task) {
- return __awaiter(this, void 0, void 0, function* () {
- const terminal = new TaskTerminal(view5, process.stdout);
- terminal.requestLayout();
- try {
- const result = yield task;
- terminal.clear();
- return result;
- } catch (err) {
- terminal.reject(err);
- process.exit(1);
- }
- });
- }
- var terminateHandler;
- function onTerminate(callback) {
- terminateHandler = callback;
- }
- }
- });
- // src/utils.ts
- var utils_exports = {};
- __export(utils_exports, {
- assertV1OutFolder: () => assertV1OutFolder,
- columnRenameKey: () => columnRenameKey,
- copy: () => copy,
- dryJournal: () => dryJournal,
- escapeSingleQuotes: () => escapeSingleQuotes,
- findAddedAndRemoved: () => findAddedAndRemoved,
- isPgArrayType: () => isPgArrayType,
- kloudMeta: () => kloudMeta,
- normalisePGliteUrl: () => normalisePGliteUrl,
- normaliseSQLiteUrl: () => normaliseSQLiteUrl,
- objectValues: () => objectValues,
- prepareMigrationFolder: () => prepareMigrationFolder,
- prepareMigrationMeta: () => prepareMigrationMeta,
- prepareOutFolder: () => prepareOutFolder,
- schemaRenameKey: () => schemaRenameKey,
- tableRenameKey: () => tableRenameKey,
- unescapeSingleQuotes: () => unescapeSingleQuotes,
- validateWithReport: () => validateWithReport
- });
- module.exports = __toCommonJS(utils_exports);
- // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js
- var ANSI_BACKGROUND_OFFSET = 10;
- var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
- var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
- var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
- var styles = {
- modifier: {
- reset: [0, 0],
- // 21 isn't widely supported and 22 does the same thing
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- overline: [53, 55],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29]
- },
- color: {
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- // Bright color
- blackBright: [90, 39],
- gray: [90, 39],
- // Alias of `blackBright`
- grey: [90, 39],
- // Alias of `blackBright`
- redBright: [91, 39],
- greenBright: [92, 39],
- yellowBright: [93, 39],
- blueBright: [94, 39],
- magentaBright: [95, 39],
- cyanBright: [96, 39],
- whiteBright: [97, 39]
- },
- bgColor: {
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- // Bright color
- bgBlackBright: [100, 49],
- bgGray: [100, 49],
- // Alias of `bgBlackBright`
- bgGrey: [100, 49],
- // Alias of `bgBlackBright`
- bgRedBright: [101, 49],
- bgGreenBright: [102, 49],
- bgYellowBright: [103, 49],
- bgBlueBright: [104, 49],
- bgMagentaBright: [105, 49],
- bgCyanBright: [106, 49],
- bgWhiteBright: [107, 49]
- }
- };
- var modifierNames = Object.keys(styles.modifier);
- var foregroundColorNames = Object.keys(styles.color);
- var backgroundColorNames = Object.keys(styles.bgColor);
- var colorNames = [...foregroundColorNames, ...backgroundColorNames];
- function assembleStyles() {
- const codes = /* @__PURE__ */ new Map();
- for (const [groupName, group] of Object.entries(styles)) {
- for (const [styleName, style] of Object.entries(group)) {
- styles[styleName] = {
- open: `\x1B[${style[0]}m`,
- close: `\x1B[${style[1]}m`
- };
- group[styleName] = styles[styleName];
- codes.set(style[0], style[1]);
- }
- Object.defineProperty(styles, groupName, {
- value: group,
- enumerable: false
- });
- }
- Object.defineProperty(styles, "codes", {
- value: codes,
- enumerable: false
- });
- styles.color.close = "\x1B[39m";
- styles.bgColor.close = "\x1B[49m";
- styles.color.ansi = wrapAnsi16();
- styles.color.ansi256 = wrapAnsi256();
- styles.color.ansi16m = wrapAnsi16m();
- styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
- styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
- styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
- Object.defineProperties(styles, {
- rgbToAnsi256: {
- value(red, green, blue) {
- if (red === green && green === blue) {
- if (red < 8) {
- return 16;
- }
- if (red > 248) {
- return 231;
- }
- return Math.round((red - 8) / 247 * 24) + 232;
- }
- return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
- },
- enumerable: false
- },
- hexToRgb: {
- value(hex) {
- const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
- if (!matches) {
- return [0, 0, 0];
- }
- let [colorString] = matches;
- if (colorString.length === 3) {
- colorString = [...colorString].map((character) => character + character).join("");
- }
- const integer = Number.parseInt(colorString, 16);
- return [
- /* eslint-disable no-bitwise */
- integer >> 16 & 255,
- integer >> 8 & 255,
- integer & 255
- /* eslint-enable no-bitwise */
- ];
- },
- enumerable: false
- },
- hexToAnsi256: {
- value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
- enumerable: false
- },
- ansi256ToAnsi: {
- value(code) {
- if (code < 8) {
- return 30 + code;
- }
- if (code < 16) {
- return 90 + (code - 8);
- }
- let red;
- let green;
- let blue;
- if (code >= 232) {
- red = ((code - 232) * 10 + 8) / 255;
- green = red;
- blue = red;
- } else {
- code -= 16;
- const remainder = code % 36;
- red = Math.floor(code / 36) / 5;
- green = Math.floor(remainder / 6) / 5;
- blue = remainder % 6 / 5;
- }
- const value = Math.max(red, green, blue) * 2;
- if (value === 0) {
- return 30;
- }
- let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
- if (value === 2) {
- result += 60;
- }
- return result;
- },
- enumerable: false
- },
- rgbToAnsi: {
- value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
- enumerable: false
- },
- hexToAnsi: {
- value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
- enumerable: false
- }
- });
- return styles;
- }
- var ansiStyles = assembleStyles();
- var ansi_styles_default = ansiStyles;
- // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js
- var import_node_process = __toESM(require("node:process"), 1);
- var import_node_os = __toESM(require("node:os"), 1);
- var import_node_tty = __toESM(require("node:tty"), 1);
- function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
- const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
- const position = argv.indexOf(prefix + flag);
- const terminatorPosition = argv.indexOf("--");
- return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
- }
- var { env } = import_node_process.default;
- var flagForceColor;
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
- flagForceColor = 0;
- } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
- flagForceColor = 1;
- }
- function envForceColor() {
- if ("FORCE_COLOR" in env) {
- if (env.FORCE_COLOR === "true") {
- return 1;
- }
- if (env.FORCE_COLOR === "false") {
- return 0;
- }
- return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
- }
- }
- function translateLevel(level) {
- if (level === 0) {
- return false;
- }
- return {
- level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3
- };
- }
- function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
- const noFlagForceColor = envForceColor();
- if (noFlagForceColor !== void 0) {
- flagForceColor = noFlagForceColor;
- }
- const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
- if (forceColor === 0) {
- return 0;
- }
- if (sniffFlags) {
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
- return 3;
- }
- if (hasFlag("color=256")) {
- return 2;
- }
- }
- if ("TF_BUILD" in env && "AGENT_NAME" in env) {
- return 1;
- }
- if (haveStream && !streamIsTTY && forceColor === void 0) {
- return 0;
- }
- const min = forceColor || 0;
- if (env.TERM === "dumb") {
- return min;
- }
- if (import_node_process.default.platform === "win32") {
- const osRelease = import_node_os.default.release().split(".");
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
- return 1;
- }
- if ("CI" in env) {
- if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
- return 3;
- }
- if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
- return 1;
- }
- return min;
- }
- if ("TEAMCITY_VERSION" in env) {
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
- }
- if (env.COLORTERM === "truecolor") {
- return 3;
- }
- if (env.TERM === "xterm-kitty") {
- return 3;
- }
- if ("TERM_PROGRAM" in env) {
- const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
- switch (env.TERM_PROGRAM) {
- case "iTerm.app": {
- return version >= 3 ? 3 : 2;
- }
- case "Apple_Terminal": {
- return 2;
- }
- }
- }
- if (/-256(color)?$/i.test(env.TERM)) {
- return 2;
- }
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
- return 1;
- }
- if ("COLORTERM" in env) {
- return 1;
- }
- return min;
- }
- function createSupportsColor(stream, options = {}) {
- const level = _supportsColor(stream, {
- streamIsTTY: stream && stream.isTTY,
- ...options
- });
- return translateLevel(level);
- }
- var supportsColor = {
- stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
- stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
- };
- var supports_color_default = supportsColor;
- // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js
- function stringReplaceAll(string, substring, replacer) {
- let index6 = string.indexOf(substring);
- if (index6 === -1) {
- return string;
- }
- const substringLength = substring.length;
- let endIndex = 0;
- let returnValue = "";
- do {
- returnValue += string.slice(endIndex, index6) + substring + replacer;
- endIndex = index6 + substringLength;
- index6 = string.indexOf(substring, endIndex);
- } while (index6 !== -1);
- returnValue += string.slice(endIndex);
- return returnValue;
- }
- function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index6) {
- let endIndex = 0;
- let returnValue = "";
- do {
- const gotCR = string[index6 - 1] === "\r";
- returnValue += string.slice(endIndex, gotCR ? index6 - 1 : index6) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
- endIndex = index6 + 1;
- index6 = string.indexOf("\n", endIndex);
- } while (index6 !== -1);
- returnValue += string.slice(endIndex);
- return returnValue;
- }
- // ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js
- var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
- var GENERATOR = Symbol("GENERATOR");
- var STYLER = Symbol("STYLER");
- var IS_EMPTY = Symbol("IS_EMPTY");
- var levelMapping = [
- "ansi",
- "ansi",
- "ansi256",
- "ansi16m"
- ];
- var styles2 = /* @__PURE__ */ Object.create(null);
- var applyOptions = (object, options = {}) => {
- if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
- throw new Error("The `level` option should be an integer from 0 to 3");
- }
- const colorLevel = stdoutColor ? stdoutColor.level : 0;
- object.level = options.level === void 0 ? colorLevel : options.level;
- };
- var chalkFactory = (options) => {
- const chalk2 = (...strings) => strings.join(" ");
- applyOptions(chalk2, options);
- Object.setPrototypeOf(chalk2, createChalk.prototype);
- return chalk2;
- };
- function createChalk(options) {
- return chalkFactory(options);
- }
- Object.setPrototypeOf(createChalk.prototype, Function.prototype);
- for (const [styleName, style] of Object.entries(ansi_styles_default)) {
- styles2[styleName] = {
- get() {
- const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
- Object.defineProperty(this, styleName, { value: builder });
- return builder;
- }
- };
- }
- styles2.visible = {
- get() {
- const builder = createBuilder(this, this[STYLER], true);
- Object.defineProperty(this, "visible", { value: builder });
- return builder;
- }
- };
- var getModelAnsi = (model, level, type, ...arguments_) => {
- if (model === "rgb") {
- if (level === "ansi16m") {
- return ansi_styles_default[type].ansi16m(...arguments_);
- }
- if (level === "ansi256") {
- return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
- }
- return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
- }
- if (model === "hex") {
- return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
- }
- return ansi_styles_default[type][model](...arguments_);
- };
- var usedModels = ["rgb", "hex", "ansi256"];
- for (const model of usedModels) {
- styles2[model] = {
- get() {
- const { level } = this;
- return function(...arguments_) {
- const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
- return createBuilder(this, styler, this[IS_EMPTY]);
- };
- }
- };
- const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
- styles2[bgModel] = {
- get() {
- const { level } = this;
- return function(...arguments_) {
- const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
- return createBuilder(this, styler, this[IS_EMPTY]);
- };
- }
- };
- }
- var proto = Object.defineProperties(() => {
- }, {
- ...styles2,
- level: {
- enumerable: true,
- get() {
- return this[GENERATOR].level;
- },
- set(level) {
- this[GENERATOR].level = level;
- }
- }
- });
- var createStyler = (open, close, parent) => {
- let openAll;
- let closeAll;
- if (parent === void 0) {
- openAll = open;
- closeAll = close;
- } else {
- openAll = parent.openAll + open;
- closeAll = close + parent.closeAll;
- }
- return {
- open,
- close,
- openAll,
- closeAll,
- parent
- };
- };
- var createBuilder = (self2, _styler, _isEmpty) => {
- const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
- Object.setPrototypeOf(builder, proto);
- builder[GENERATOR] = self2;
- builder[STYLER] = _styler;
- builder[IS_EMPTY] = _isEmpty;
- return builder;
- };
- var applyStyle = (self2, string) => {
- if (self2.level <= 0 || !string) {
- return self2[IS_EMPTY] ? "" : string;
- }
- let styler = self2[STYLER];
- if (styler === void 0) {
- return string;
- }
- const { openAll, closeAll } = styler;
- if (string.includes("\x1B")) {
- while (styler !== void 0) {
- string = stringReplaceAll(string, styler.close, styler.open);
- styler = styler.parent;
- }
- }
- const lfIndex = string.indexOf("\n");
- if (lfIndex !== -1) {
- string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
- }
- return openAll + string + closeAll;
- };
- Object.defineProperties(createChalk.prototype, styles2);
- var chalk = createChalk();
- var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
- var source_default = chalk;
- // src/utils.ts
- var import_fs = require("fs");
- var import_path = require("path");
- var import_url = require("url");
- // src/cli/views.ts
- var import_hanji = __toESM(require_hanji());
- var info = (msg, greyMsg = "") => {
- return `${source_default.blue.bold("Info:")} ${msg} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
- };
- // src/global.ts
- var originUUID = "00000000-0000-0000-0000-000000000000";
- var snapshotVersion = "7";
- function assertUnreachable(x) {
- throw new Error("Didn't expect to get here");
- }
- // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js
- var util;
- (function(util2) {
- util2.assertEqual = (_) => {
- };
- function assertIs(_arg) {
- }
- util2.assertIs = assertIs;
- function assertNever(_x) {
- throw new Error();
- }
- util2.assertNever = assertNever;
- util2.arrayToEnum = (items) => {
- const obj = {};
- for (const item of items) {
- obj[item] = item;
- }
- return obj;
- };
- util2.getValidEnumValues = (obj) => {
- const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
- const filtered = {};
- for (const k of validKeys) {
- filtered[k] = obj[k];
- }
- return util2.objectValues(filtered);
- };
- util2.objectValues = (obj) => {
- return util2.objectKeys(obj).map(function(e) {
- return obj[e];
- });
- };
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
- const keys = [];
- for (const key in object) {
- if (Object.prototype.hasOwnProperty.call(object, key)) {
- keys.push(key);
- }
- }
- return keys;
- };
- util2.find = (arr, checker) => {
- for (const item of arr) {
- if (checker(item))
- return item;
- }
- return void 0;
- };
- util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
- function joinValues(array, separator = " | ") {
- return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
- }
- util2.joinValues = joinValues;
- util2.jsonStringifyReplacer = (_, value) => {
- if (typeof value === "bigint") {
- return value.toString();
- }
- return value;
- };
- })(util || (util = {}));
- var objectUtil;
- (function(objectUtil2) {
- objectUtil2.mergeShapes = (first, second) => {
- return {
- ...first,
- ...second
- // second overwrites first
- };
- };
- })(objectUtil || (objectUtil = {}));
- var ZodParsedType = util.arrayToEnum([
- "string",
- "nan",
- "number",
- "integer",
- "float",
- "boolean",
- "date",
- "bigint",
- "symbol",
- "function",
- "undefined",
- "null",
- "array",
- "object",
- "unknown",
- "promise",
- "void",
- "never",
- "map",
- "set"
- ]);
- var getParsedType = (data) => {
- const t = typeof data;
- switch (t) {
- case "undefined":
- return ZodParsedType.undefined;
- case "string":
- return ZodParsedType.string;
- case "number":
- return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
- case "boolean":
- return ZodParsedType.boolean;
- case "function":
- return ZodParsedType.function;
- case "bigint":
- return ZodParsedType.bigint;
- case "symbol":
- return ZodParsedType.symbol;
- case "object":
- if (Array.isArray(data)) {
- return ZodParsedType.array;
- }
- if (data === null) {
- return ZodParsedType.null;
- }
- if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
- return ZodParsedType.promise;
- }
- if (typeof Map !== "undefined" && data instanceof Map) {
- return ZodParsedType.map;
- }
- if (typeof Set !== "undefined" && data instanceof Set) {
- return ZodParsedType.set;
- }
- if (typeof Date !== "undefined" && data instanceof Date) {
- return ZodParsedType.date;
- }
- return ZodParsedType.object;
- default:
- return ZodParsedType.unknown;
- }
- };
- // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js
- var ZodIssueCode = util.arrayToEnum([
- "invalid_type",
- "invalid_literal",
- "custom",
- "invalid_union",
- "invalid_union_discriminator",
- "invalid_enum_value",
- "unrecognized_keys",
- "invalid_arguments",
- "invalid_return_type",
- "invalid_date",
- "invalid_string",
- "too_small",
- "too_big",
- "invalid_intersection_types",
- "not_multiple_of",
- "not_finite"
- ]);
- var ZodError = class _ZodError extends Error {
- get errors() {
- return this.issues;
- }
- constructor(issues) {
- super();
- this.issues = [];
- this.addIssue = (sub) => {
- this.issues = [...this.issues, sub];
- };
- this.addIssues = (subs = []) => {
- this.issues = [...this.issues, ...subs];
- };
- const actualProto = new.target.prototype;
- if (Object.setPrototypeOf) {
- Object.setPrototypeOf(this, actualProto);
- } else {
- this.__proto__ = actualProto;
- }
- this.name = "ZodError";
- this.issues = issues;
- }
- format(_mapper) {
- const mapper = _mapper || function(issue) {
- return issue.message;
- };
- const fieldErrors = { _errors: [] };
- const processError = (error) => {
- for (const issue of error.issues) {
- if (issue.code === "invalid_union") {
- issue.unionErrors.map(processError);
- } else if (issue.code === "invalid_return_type") {
- processError(issue.returnTypeError);
- } else if (issue.code === "invalid_arguments") {
- processError(issue.argumentsError);
- } else if (issue.path.length === 0) {
- fieldErrors._errors.push(mapper(issue));
- } else {
- let curr = fieldErrors;
- let i = 0;
- while (i < issue.path.length) {
- const el = issue.path[i];
- const terminal = i === issue.path.length - 1;
- if (!terminal) {
- curr[el] = curr[el] || { _errors: [] };
- } else {
- curr[el] = curr[el] || { _errors: [] };
- curr[el]._errors.push(mapper(issue));
- }
- curr = curr[el];
- i++;
- }
- }
- }
- };
- processError(this);
- return fieldErrors;
- }
- static assert(value) {
- if (!(value instanceof _ZodError)) {
- throw new Error(`Not a ZodError: ${value}`);
- }
- }
- toString() {
- return this.message;
- }
- get message() {
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
- }
- get isEmpty() {
- return this.issues.length === 0;
- }
- flatten(mapper = (issue) => issue.message) {
- const fieldErrors = {};
- const formErrors = [];
- for (const sub of this.issues) {
- if (sub.path.length > 0) {
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
- fieldErrors[sub.path[0]].push(mapper(sub));
- } else {
- formErrors.push(mapper(sub));
- }
- }
- return { formErrors, fieldErrors };
- }
- get formErrors() {
- return this.flatten();
- }
- };
- ZodError.create = (issues) => {
- const error = new ZodError(issues);
- return error;
- };
- // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js
- var errorMap = (issue, _ctx) => {
- let message;
- switch (issue.code) {
- case ZodIssueCode.invalid_type:
- if (issue.received === ZodParsedType.undefined) {
- message = "Required";
- } else {
- message = `Expected ${issue.expected}, received ${issue.received}`;
- }
- break;
- case ZodIssueCode.invalid_literal:
- message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
- break;
- case ZodIssueCode.unrecognized_keys:
- message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
- break;
- case ZodIssueCode.invalid_union:
- message = `Invalid input`;
- break;
- case ZodIssueCode.invalid_union_discriminator:
- message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
- break;
- case ZodIssueCode.invalid_enum_value:
- message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
- break;
- case ZodIssueCode.invalid_arguments:
- message = `Invalid function arguments`;
- break;
- case ZodIssueCode.invalid_return_type:
- message = `Invalid function return type`;
- break;
- case ZodIssueCode.invalid_date:
- message = `Invalid date`;
- break;
- case ZodIssueCode.invalid_string:
- if (typeof issue.validation === "object") {
- if ("includes" in issue.validation) {
- message = `Invalid input: must include "${issue.validation.includes}"`;
- if (typeof issue.validation.position === "number") {
- message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
- }
- } else if ("startsWith" in issue.validation) {
- message = `Invalid input: must start with "${issue.validation.startsWith}"`;
- } else if ("endsWith" in issue.validation) {
- message = `Invalid input: must end with "${issue.validation.endsWith}"`;
- } else {
- util.assertNever(issue.validation);
- }
- } else if (issue.validation !== "regex") {
- message = `Invalid ${issue.validation}`;
- } else {
- message = "Invalid";
- }
- break;
- case ZodIssueCode.too_small:
- if (issue.type === "array")
- message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
- else if (issue.type === "string")
- message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
- else if (issue.type === "number")
- message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
- else if (issue.type === "date")
- message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
- else
- message = "Invalid input";
- break;
- case ZodIssueCode.too_big:
- if (issue.type === "array")
- message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
- else if (issue.type === "string")
- message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
- else if (issue.type === "number")
- message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
- else if (issue.type === "bigint")
- message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
- else if (issue.type === "date")
- message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
- else
- message = "Invalid input";
- break;
- case ZodIssueCode.custom:
- message = `Invalid input`;
- break;
- case ZodIssueCode.invalid_intersection_types:
- message = `Intersection results could not be merged`;
- break;
- case ZodIssueCode.not_multiple_of:
- message = `Number must be a multiple of ${issue.multipleOf}`;
- break;
- case ZodIssueCode.not_finite:
- message = "Number must be finite";
- break;
- default:
- message = _ctx.defaultError;
- util.assertNever(issue);
- }
- return { message };
- };
- var en_default = errorMap;
- // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js
- var overrideErrorMap = en_default;
- function getErrorMap() {
- return overrideErrorMap;
- }
- // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js
- var makeIssue = (params) => {
- const { data, path, errorMaps, issueData } = params;
- const fullPath = [...path, ...issueData.path || []];
- const fullIssue = {
- ...issueData,
- path: fullPath
- };
- if (issueData.message !== void 0) {
- return {
- ...issueData,
- path: fullPath,
- message: issueData.message
- };
- }
- let errorMessage = "";
- const maps = errorMaps.filter((m) => !!m).slice().reverse();
- for (const map of maps) {
- errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
- }
- return {
- ...issueData,
- path: fullPath,
- message: errorMessage
- };
- };
- function addIssueToContext(ctx, issueData) {
- const overrideMap = getErrorMap();
- const issue = makeIssue({
- issueData,
- data: ctx.data,
- path: ctx.path,
- errorMaps: [
- ctx.common.contextualErrorMap,
- // contextual error map is first priority
- ctx.schemaErrorMap,
- // then schema-bound map if available
- overrideMap,
- // then global override map
- overrideMap === en_default ? void 0 : en_default
- // then global default map
- ].filter((x) => !!x)
- });
- ctx.common.issues.push(issue);
- }
- var ParseStatus = class _ParseStatus {
- constructor() {
- this.value = "valid";
- }
- dirty() {
- if (this.value === "valid")
- this.value = "dirty";
- }
- abort() {
- if (this.value !== "aborted")
- this.value = "aborted";
- }
- static mergeArray(status, results) {
- const arrayValue = [];
- for (const s of results) {
- if (s.status === "aborted")
- return INVALID;
- if (s.status === "dirty")
- status.dirty();
- arrayValue.push(s.value);
- }
- return { status: status.value, value: arrayValue };
- }
- static async mergeObjectAsync(status, pairs) {
- const syncPairs = [];
- for (const pair of pairs) {
- const key = await pair.key;
- const value = await pair.value;
- syncPairs.push({
- key,
- value
- });
- }
- return _ParseStatus.mergeObjectSync(status, syncPairs);
- }
- static mergeObjectSync(status, pairs) {
- const finalObject = {};
- for (const pair of pairs) {
- const { key, value } = pair;
- if (key.status === "aborted")
- return INVALID;
- if (value.status === "aborted")
- return INVALID;
- if (key.status === "dirty")
- status.dirty();
- if (value.status === "dirty")
- status.dirty();
- if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
- finalObject[key.value] = value.value;
- }
- }
- return { status: status.value, value: finalObject };
- }
- };
- var INVALID = Object.freeze({
- status: "aborted"
- });
- var DIRTY = (value) => ({ status: "dirty", value });
- var OK = (value) => ({ status: "valid", value });
- var isAborted = (x) => x.status === "aborted";
- var isDirty = (x) => x.status === "dirty";
- var isValid = (x) => x.status === "valid";
- var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
- // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js
- var errorUtil;
- (function(errorUtil2) {
- errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
- errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message;
- })(errorUtil || (errorUtil = {}));
- // ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js
- var ParseInputLazyPath = class {
- constructor(parent, value, path, key) {
- this._cachedPath = [];
- this.parent = parent;
- this.data = value;
- this._path = path;
- this._key = key;
- }
- get path() {
- if (!this._cachedPath.length) {
- if (Array.isArray(this._key)) {
- this._cachedPath.push(...this._path, ...this._key);
- } else {
- this._cachedPath.push(...this._path, this._key);
- }
- }
- return this._cachedPath;
- }
- };
- var handleResult = (ctx, result) => {
- if (isValid(result)) {
- return { success: true, data: result.value };
- } else {
- if (!ctx.common.issues.length) {
- throw new Error("Validation failed but no issues detected.");
- }
- return {
- success: false,
- get error() {
- if (this._error)
- return this._error;
- const error = new ZodError(ctx.common.issues);
- this._error = error;
- return this._error;
- }
- };
- }
- };
- function processCreateParams(params) {
- if (!params)
- return {};
- const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
- if (errorMap2 && (invalid_type_error || required_error)) {
- throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
- }
- if (errorMap2)
- return { errorMap: errorMap2, description };
- const customMap = (iss, ctx) => {
- const { message } = params;
- if (iss.code === "invalid_enum_value") {
- return { message: message ?? ctx.defaultError };
- }
- if (typeof ctx.data === "undefined") {
- return { message: message ?? required_error ?? ctx.defaultError };
- }
- if (iss.code !== "invalid_type")
- return { message: ctx.defaultError };
- return { message: message ?? invalid_type_error ?? ctx.defaultError };
- };
- return { errorMap: customMap, description };
- }
- var ZodType = class {
- get description() {
- return this._def.description;
- }
- _getType(input) {
- return getParsedType(input.data);
- }
- _getOrReturnCtx(input, ctx) {
- return ctx || {
- common: input.parent.common,
- data: input.data,
- parsedType: getParsedType(input.data),
- schemaErrorMap: this._def.errorMap,
- path: input.path,
- parent: input.parent
- };
- }
- _processInputParams(input) {
- return {
- status: new ParseStatus(),
- ctx: {
- common: input.parent.common,
- data: input.data,
- parsedType: getParsedType(input.data),
- schemaErrorMap: this._def.errorMap,
- path: input.path,
- parent: input.parent
- }
- };
- }
- _parseSync(input) {
- const result = this._parse(input);
- if (isAsync(result)) {
- throw new Error("Synchronous parse encountered promise.");
- }
- return result;
- }
- _parseAsync(input) {
- const result = this._parse(input);
- return Promise.resolve(result);
- }
- parse(data, params) {
- const result = this.safeParse(data, params);
- if (result.success)
- return result.data;
- throw result.error;
- }
- safeParse(data, params) {
- const ctx = {
- common: {
- issues: [],
- async: (params == null ? void 0 : params.async) ?? false,
- contextualErrorMap: params == null ? void 0 : params.errorMap
- },
- path: (params == null ? void 0 : params.path) || [],
- schemaErrorMap: this._def.errorMap,
- parent: null,
- data,
- parsedType: getParsedType(data)
- };
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
- return handleResult(ctx, result);
- }
- "~validate"(data) {
- var _a, _b;
- const ctx = {
- common: {
- issues: [],
- async: !!this["~standard"].async
- },
- path: [],
- schemaErrorMap: this._def.errorMap,
- parent: null,
- data,
- parsedType: getParsedType(data)
- };
- if (!this["~standard"].async) {
- try {
- const result = this._parseSync({ data, path: [], parent: ctx });
- return isValid(result) ? {
- value: result.value
- } : {
- issues: ctx.common.issues
- };
- } catch (err) {
- if ((_b = (_a = err == null ? void 0 : err.message) == null ? void 0 : _a.toLowerCase()) == null ? void 0 : _b.includes("encountered")) {
- this["~standard"].async = true;
- }
- ctx.common = {
- issues: [],
- async: true
- };
- }
- }
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
- value: result.value
- } : {
- issues: ctx.common.issues
- });
- }
- async parseAsync(data, params) {
- const result = await this.safeParseAsync(data, params);
- if (result.success)
- return result.data;
- throw result.error;
- }
- async safeParseAsync(data, params) {
- const ctx = {
- common: {
- issues: [],
- contextualErrorMap: params == null ? void 0 : params.errorMap,
- async: true
- },
- path: (params == null ? void 0 : params.path) || [],
- schemaErrorMap: this._def.errorMap,
- parent: null,
- data,
- parsedType: getParsedType(data)
- };
- const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
- return handleResult(ctx, result);
- }
- refine(check, message) {
- const getIssueProperties = (val) => {
- if (typeof message === "string" || typeof message === "undefined") {
- return { message };
- } else if (typeof message === "function") {
- return message(val);
- } else {
- return message;
- }
- };
- return this._refinement((val, ctx) => {
- const result = check(val);
- const setError = () => ctx.addIssue({
- code: ZodIssueCode.custom,
- ...getIssueProperties(val)
- });
- if (typeof Promise !== "undefined" && result instanceof Promise) {
- return result.then((data) => {
- if (!data) {
- setError();
- return false;
- } else {
- return true;
- }
- });
- }
- if (!result) {
- setError();
- return false;
- } else {
- return true;
- }
- });
- }
- refinement(check, refinementData) {
- return this._refinement((val, ctx) => {
- if (!check(val)) {
- ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
- return false;
- } else {
- return true;
- }
- });
- }
- _refinement(refinement) {
- return new ZodEffects({
- schema: this,
- typeName: ZodFirstPartyTypeKind.ZodEffects,
- effect: { type: "refinement", refinement }
- });
- }
- superRefine(refinement) {
- return this._refinement(refinement);
- }
- constructor(def) {
- this.spa = this.safeParseAsync;
- this._def = def;
- this.parse = this.parse.bind(this);
- this.safeParse = this.safeParse.bind(this);
- this.parseAsync = this.parseAsync.bind(this);
- this.safeParseAsync = this.safeParseAsync.bind(this);
- this.spa = this.spa.bind(this);
- this.refine = this.refine.bind(this);
- this.refinement = this.refinement.bind(this);
- this.superRefine = this.superRefine.bind(this);
- this.optional = this.optional.bind(this);
- this.nullable = this.nullable.bind(this);
- this.nullish = this.nullish.bind(this);
- this.array = this.array.bind(this);
- this.promise = this.promise.bind(this);
- this.or = this.or.bind(this);
- this.and = this.and.bind(this);
- this.transform = this.transform.bind(this);
- this.brand = this.brand.bind(this);
- this.default = this.default.bind(this);
- this.catch = this.catch.bind(this);
- this.describe = this.describe.bind(this);
- this.pipe = this.pipe.bind(this);
- this.readonly = this.readonly.bind(this);
- this.isNullable = this.isNullable.bind(this);
- this.isOptional = this.isOptional.bind(this);
- this["~standard"] = {
- version: 1,
- vendor: "zod",
- validate: (data) => this["~validate"](data)
- };
- }
- optional() {
- return ZodOptional.create(this, this._def);
- }
- nullable() {
- return ZodNullable.create(this, this._def);
- }
- nullish() {
- return this.nullable().optional();
- }
- array() {
- return ZodArray.create(this);
- }
- promise() {
- return ZodPromise.create(this, this._def);
- }
- or(option) {
- return ZodUnion.create([this, option], this._def);
- }
- and(incoming) {
- return ZodIntersection.create(this, incoming, this._def);
- }
- transform(transform) {
- return new ZodEffects({
- ...processCreateParams(this._def),
- schema: this,
- typeName: ZodFirstPartyTypeKind.ZodEffects,
- effect: { type: "transform", transform }
- });
- }
- default(def) {
- const defaultValueFunc = typeof def === "function" ? def : () => def;
- return new ZodDefault({
- ...processCreateParams(this._def),
- innerType: this,
- defaultValue: defaultValueFunc,
- typeName: ZodFirstPartyTypeKind.ZodDefault
- });
- }
- brand() {
- return new ZodBranded({
- typeName: ZodFirstPartyTypeKind.ZodBranded,
- type: this,
- ...processCreateParams(this._def)
- });
- }
- catch(def) {
- const catchValueFunc = typeof def === "function" ? def : () => def;
- return new ZodCatch({
- ...processCreateParams(this._def),
- innerType: this,
- catchValue: catchValueFunc,
- typeName: ZodFirstPartyTypeKind.ZodCatch
- });
- }
- describe(description) {
- const This = this.constructor;
- return new This({
- ...this._def,
- description
- });
- }
- pipe(target) {
- return ZodPipeline.create(this, target);
- }
- readonly() {
- return ZodReadonly.create(this);
- }
- isOptional() {
- return this.safeParse(void 0).success;
- }
- isNullable() {
- return this.safeParse(null).success;
- }
- };
- var cuidRegex = /^c[^\s-]{8,}$/i;
- var cuid2Regex = /^[0-9a-z]+$/;
- var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
- var 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;
- var nanoidRegex = /^[a-z0-9_-]{21}$/i;
- var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
- var 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)?)??$/;
- var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
- var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
- var emojiRegex;
- var 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])$/;
- var 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])$/;
- var 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]))$/;
- var 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])$/;
- var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
- var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
- var 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])))`;
- var dateRegex = new RegExp(`^${dateRegexSource}$`);
- function timeRegexSource(args) {
- let secondsRegexSource = `[0-5]\\d`;
- if (args.precision) {
- secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
- } else if (args.precision == null) {
- secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
- }
- const secondsQuantifier = args.precision ? "+" : "?";
- return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
- }
- function timeRegex(args) {
- return new RegExp(`^${timeRegexSource(args)}$`);
- }
- function datetimeRegex(args) {
- let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
- const opts = [];
- opts.push(args.local ? `Z?` : `Z`);
- if (args.offset)
- opts.push(`([+-]\\d{2}:?\\d{2})`);
- regex = `${regex}(${opts.join("|")})`;
- return new RegExp(`^${regex}$`);
- }
- function isValidIP(ip, version) {
- if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
- return true;
- }
- if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
- return true;
- }
- return false;
- }
- function isValidJWT(jwt, alg) {
- if (!jwtRegex.test(jwt))
- return false;
- try {
- const [header] = jwt.split(".");
- const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
- const decoded = JSON.parse(atob(base64));
- if (typeof decoded !== "object" || decoded === null)
- return false;
- if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT")
- return false;
- if (!decoded.alg)
- return false;
- if (alg && decoded.alg !== alg)
- return false;
- return true;
- } catch {
- return false;
- }
- }
- function isValidCidr(ip, version) {
- if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
- return true;
- }
- if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
- return true;
- }
- return false;
- }
- var ZodString = class _ZodString extends ZodType {
- _parse(input) {
- if (this._def.coerce) {
- input.data = String(input.data);
- }
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.string) {
- const ctx2 = this._getOrReturnCtx(input);
- addIssueToContext(ctx2, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.string,
- received: ctx2.parsedType
- });
- return INVALID;
- }
- const status = new ParseStatus();
- let ctx = void 0;
- for (const check of this._def.checks) {
- if (check.kind === "min") {
- if (input.data.length < check.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: check.value,
- type: "string",
- inclusive: true,
- exact: false,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "max") {
- if (input.data.length > check.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: check.value,
- type: "string",
- inclusive: true,
- exact: false,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "length") {
- const tooBig = input.data.length > check.value;
- const tooSmall = input.data.length < check.value;
- if (tooBig || tooSmall) {
- ctx = this._getOrReturnCtx(input, ctx);
- if (tooBig) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: check.value,
- type: "string",
- inclusive: true,
- exact: true,
- message: check.message
- });
- } else if (tooSmall) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: check.value,
- type: "string",
- inclusive: true,
- exact: true,
- message: check.message
- });
- }
- status.dirty();
- }
- } else if (check.kind === "email") {
- if (!emailRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "email",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "emoji") {
- if (!emojiRegex) {
- emojiRegex = new RegExp(_emojiRegex, "u");
- }
- if (!emojiRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "emoji",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "uuid") {
- if (!uuidRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "uuid",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "nanoid") {
- if (!nanoidRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "nanoid",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "cuid") {
- if (!cuidRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "cuid",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "cuid2") {
- if (!cuid2Regex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "cuid2",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "ulid") {
- if (!ulidRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "ulid",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "url") {
- try {
- new URL(input.data);
- } catch {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "url",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "regex") {
- check.regex.lastIndex = 0;
- const testResult = check.regex.test(input.data);
- if (!testResult) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "regex",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "trim") {
- input.data = input.data.trim();
- } else if (check.kind === "includes") {
- if (!input.data.includes(check.value, check.position)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_string,
- validation: { includes: check.value, position: check.position },
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "toLowerCase") {
- input.data = input.data.toLowerCase();
- } else if (check.kind === "toUpperCase") {
- input.data = input.data.toUpperCase();
- } else if (check.kind === "startsWith") {
- if (!input.data.startsWith(check.value)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_string,
- validation: { startsWith: check.value },
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "endsWith") {
- if (!input.data.endsWith(check.value)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_string,
- validation: { endsWith: check.value },
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "datetime") {
- const regex = datetimeRegex(check);
- if (!regex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_string,
- validation: "datetime",
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "date") {
- const regex = dateRegex;
- if (!regex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_string,
- validation: "date",
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "time") {
- const regex = timeRegex(check);
- if (!regex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_string,
- validation: "time",
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "duration") {
- if (!durationRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "duration",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "ip") {
- if (!isValidIP(input.data, check.version)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "ip",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "jwt") {
- if (!isValidJWT(input.data, check.alg)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "jwt",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "cidr") {
- if (!isValidCidr(input.data, check.version)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "cidr",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "base64") {
- if (!base64Regex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "base64",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "base64url") {
- if (!base64urlRegex.test(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- validation: "base64url",
- code: ZodIssueCode.invalid_string,
- message: check.message
- });
- status.dirty();
- }
- } else {
- util.assertNever(check);
- }
- }
- return { status: status.value, value: input.data };
- }
- _regex(regex, validation, message) {
- return this.refinement((data) => regex.test(data), {
- validation,
- code: ZodIssueCode.invalid_string,
- ...errorUtil.errToObj(message)
- });
- }
- _addCheck(check) {
- return new _ZodString({
- ...this._def,
- checks: [...this._def.checks, check]
- });
- }
- email(message) {
- return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
- }
- url(message) {
- return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
- }
- emoji(message) {
- return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
- }
- uuid(message) {
- return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
- }
- nanoid(message) {
- return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
- }
- cuid(message) {
- return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
- }
- cuid2(message) {
- return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
- }
- ulid(message) {
- return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
- }
- base64(message) {
- return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
- }
- base64url(message) {
- return this._addCheck({
- kind: "base64url",
- ...errorUtil.errToObj(message)
- });
- }
- jwt(options) {
- return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
- }
- ip(options) {
- return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
- }
- cidr(options) {
- return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
- }
- datetime(options) {
- if (typeof options === "string") {
- return this._addCheck({
- kind: "datetime",
- precision: null,
- offset: false,
- local: false,
- message: options
- });
- }
- return this._addCheck({
- kind: "datetime",
- precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
- offset: (options == null ? void 0 : options.offset) ?? false,
- local: (options == null ? void 0 : options.local) ?? false,
- ...errorUtil.errToObj(options == null ? void 0 : options.message)
- });
- }
- date(message) {
- return this._addCheck({ kind: "date", message });
- }
- time(options) {
- if (typeof options === "string") {
- return this._addCheck({
- kind: "time",
- precision: null,
- message: options
- });
- }
- return this._addCheck({
- kind: "time",
- precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
- ...errorUtil.errToObj(options == null ? void 0 : options.message)
- });
- }
- duration(message) {
- return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
- }
- regex(regex, message) {
- return this._addCheck({
- kind: "regex",
- regex,
- ...errorUtil.errToObj(message)
- });
- }
- includes(value, options) {
- return this._addCheck({
- kind: "includes",
- value,
- position: options == null ? void 0 : options.position,
- ...errorUtil.errToObj(options == null ? void 0 : options.message)
- });
- }
- startsWith(value, message) {
- return this._addCheck({
- kind: "startsWith",
- value,
- ...errorUtil.errToObj(message)
- });
- }
- endsWith(value, message) {
- return this._addCheck({
- kind: "endsWith",
- value,
- ...errorUtil.errToObj(message)
- });
- }
- min(minLength, message) {
- return this._addCheck({
- kind: "min",
- value: minLength,
- ...errorUtil.errToObj(message)
- });
- }
- max(maxLength, message) {
- return this._addCheck({
- kind: "max",
- value: maxLength,
- ...errorUtil.errToObj(message)
- });
- }
- length(len, message) {
- return this._addCheck({
- kind: "length",
- value: len,
- ...errorUtil.errToObj(message)
- });
- }
- /**
- * Equivalent to `.min(1)`
- */
- nonempty(message) {
- return this.min(1, errorUtil.errToObj(message));
- }
- trim() {
- return new _ZodString({
- ...this._def,
- checks: [...this._def.checks, { kind: "trim" }]
- });
- }
- toLowerCase() {
- return new _ZodString({
- ...this._def,
- checks: [...this._def.checks, { kind: "toLowerCase" }]
- });
- }
- toUpperCase() {
- return new _ZodString({
- ...this._def,
- checks: [...this._def.checks, { kind: "toUpperCase" }]
- });
- }
- get isDatetime() {
- return !!this._def.checks.find((ch) => ch.kind === "datetime");
- }
- get isDate() {
- return !!this._def.checks.find((ch) => ch.kind === "date");
- }
- get isTime() {
- return !!this._def.checks.find((ch) => ch.kind === "time");
- }
- get isDuration() {
- return !!this._def.checks.find((ch) => ch.kind === "duration");
- }
- get isEmail() {
- return !!this._def.checks.find((ch) => ch.kind === "email");
- }
- get isURL() {
- return !!this._def.checks.find((ch) => ch.kind === "url");
- }
- get isEmoji() {
- return !!this._def.checks.find((ch) => ch.kind === "emoji");
- }
- get isUUID() {
- return !!this._def.checks.find((ch) => ch.kind === "uuid");
- }
- get isNANOID() {
- return !!this._def.checks.find((ch) => ch.kind === "nanoid");
- }
- get isCUID() {
- return !!this._def.checks.find((ch) => ch.kind === "cuid");
- }
- get isCUID2() {
- return !!this._def.checks.find((ch) => ch.kind === "cuid2");
- }
- get isULID() {
- return !!this._def.checks.find((ch) => ch.kind === "ulid");
- }
- get isIP() {
- return !!this._def.checks.find((ch) => ch.kind === "ip");
- }
- get isCIDR() {
- return !!this._def.checks.find((ch) => ch.kind === "cidr");
- }
- get isBase64() {
- return !!this._def.checks.find((ch) => ch.kind === "base64");
- }
- get isBase64url() {
- return !!this._def.checks.find((ch) => ch.kind === "base64url");
- }
- get minLength() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min;
- }
- get maxLength() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max;
- }
- };
- ZodString.create = (params) => {
- return new ZodString({
- checks: [],
- typeName: ZodFirstPartyTypeKind.ZodString,
- coerce: (params == null ? void 0 : params.coerce) ?? false,
- ...processCreateParams(params)
- });
- };
- function floatSafeRemainder(val, step) {
- const valDecCount = (val.toString().split(".")[1] || "").length;
- const stepDecCount = (step.toString().split(".")[1] || "").length;
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
- return valInt % stepInt / 10 ** decCount;
- }
- var ZodNumber = class _ZodNumber extends ZodType {
- constructor() {
- super(...arguments);
- this.min = this.gte;
- this.max = this.lte;
- this.step = this.multipleOf;
- }
- _parse(input) {
- if (this._def.coerce) {
- input.data = Number(input.data);
- }
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.number) {
- const ctx2 = this._getOrReturnCtx(input);
- addIssueToContext(ctx2, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.number,
- received: ctx2.parsedType
- });
- return INVALID;
- }
- let ctx = void 0;
- const status = new ParseStatus();
- for (const check of this._def.checks) {
- if (check.kind === "int") {
- if (!util.isInteger(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: "integer",
- received: "float",
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "min") {
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
- if (tooSmall) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: check.value,
- type: "number",
- inclusive: check.inclusive,
- exact: false,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "max") {
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
- if (tooBig) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: check.value,
- type: "number",
- inclusive: check.inclusive,
- exact: false,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "multipleOf") {
- if (floatSafeRemainder(input.data, check.value) !== 0) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.not_multiple_of,
- multipleOf: check.value,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "finite") {
- if (!Number.isFinite(input.data)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.not_finite,
- message: check.message
- });
- status.dirty();
- }
- } else {
- util.assertNever(check);
- }
- }
- return { status: status.value, value: input.data };
- }
- gte(value, message) {
- return this.setLimit("min", value, true, errorUtil.toString(message));
- }
- gt(value, message) {
- return this.setLimit("min", value, false, errorUtil.toString(message));
- }
- lte(value, message) {
- return this.setLimit("max", value, true, errorUtil.toString(message));
- }
- lt(value, message) {
- return this.setLimit("max", value, false, errorUtil.toString(message));
- }
- setLimit(kind, value, inclusive, message) {
- return new _ZodNumber({
- ...this._def,
- checks: [
- ...this._def.checks,
- {
- kind,
- value,
- inclusive,
- message: errorUtil.toString(message)
- }
- ]
- });
- }
- _addCheck(check) {
- return new _ZodNumber({
- ...this._def,
- checks: [...this._def.checks, check]
- });
- }
- int(message) {
- return this._addCheck({
- kind: "int",
- message: errorUtil.toString(message)
- });
- }
- positive(message) {
- return this._addCheck({
- kind: "min",
- value: 0,
- inclusive: false,
- message: errorUtil.toString(message)
- });
- }
- negative(message) {
- return this._addCheck({
- kind: "max",
- value: 0,
- inclusive: false,
- message: errorUtil.toString(message)
- });
- }
- nonpositive(message) {
- return this._addCheck({
- kind: "max",
- value: 0,
- inclusive: true,
- message: errorUtil.toString(message)
- });
- }
- nonnegative(message) {
- return this._addCheck({
- kind: "min",
- value: 0,
- inclusive: true,
- message: errorUtil.toString(message)
- });
- }
- multipleOf(value, message) {
- return this._addCheck({
- kind: "multipleOf",
- value,
- message: errorUtil.toString(message)
- });
- }
- finite(message) {
- return this._addCheck({
- kind: "finite",
- message: errorUtil.toString(message)
- });
- }
- safe(message) {
- return this._addCheck({
- kind: "min",
- inclusive: true,
- value: Number.MIN_SAFE_INTEGER,
- message: errorUtil.toString(message)
- })._addCheck({
- kind: "max",
- inclusive: true,
- value: Number.MAX_SAFE_INTEGER,
- message: errorUtil.toString(message)
- });
- }
- get minValue() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min;
- }
- get maxValue() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max;
- }
- get isInt() {
- return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
- }
- get isFinite() {
- let max = null;
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
- return true;
- } else if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- } else if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return Number.isFinite(min) && Number.isFinite(max);
- }
- };
- ZodNumber.create = (params) => {
- return new ZodNumber({
- checks: [],
- typeName: ZodFirstPartyTypeKind.ZodNumber,
- coerce: (params == null ? void 0 : params.coerce) || false,
- ...processCreateParams(params)
- });
- };
- var ZodBigInt = class _ZodBigInt extends ZodType {
- constructor() {
- super(...arguments);
- this.min = this.gte;
- this.max = this.lte;
- }
- _parse(input) {
- if (this._def.coerce) {
- try {
- input.data = BigInt(input.data);
- } catch {
- return this._getInvalidInput(input);
- }
- }
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.bigint) {
- return this._getInvalidInput(input);
- }
- let ctx = void 0;
- const status = new ParseStatus();
- for (const check of this._def.checks) {
- if (check.kind === "min") {
- const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
- if (tooSmall) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- type: "bigint",
- minimum: check.value,
- inclusive: check.inclusive,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "max") {
- const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
- if (tooBig) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- type: "bigint",
- maximum: check.value,
- inclusive: check.inclusive,
- message: check.message
- });
- status.dirty();
- }
- } else if (check.kind === "multipleOf") {
- if (input.data % check.value !== BigInt(0)) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.not_multiple_of,
- multipleOf: check.value,
- message: check.message
- });
- status.dirty();
- }
- } else {
- util.assertNever(check);
- }
- }
- return { status: status.value, value: input.data };
- }
- _getInvalidInput(input) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.bigint,
- received: ctx.parsedType
- });
- return INVALID;
- }
- gte(value, message) {
- return this.setLimit("min", value, true, errorUtil.toString(message));
- }
- gt(value, message) {
- return this.setLimit("min", value, false, errorUtil.toString(message));
- }
- lte(value, message) {
- return this.setLimit("max", value, true, errorUtil.toString(message));
- }
- lt(value, message) {
- return this.setLimit("max", value, false, errorUtil.toString(message));
- }
- setLimit(kind, value, inclusive, message) {
- return new _ZodBigInt({
- ...this._def,
- checks: [
- ...this._def.checks,
- {
- kind,
- value,
- inclusive,
- message: errorUtil.toString(message)
- }
- ]
- });
- }
- _addCheck(check) {
- return new _ZodBigInt({
- ...this._def,
- checks: [...this._def.checks, check]
- });
- }
- positive(message) {
- return this._addCheck({
- kind: "min",
- value: BigInt(0),
- inclusive: false,
- message: errorUtil.toString(message)
- });
- }
- negative(message) {
- return this._addCheck({
- kind: "max",
- value: BigInt(0),
- inclusive: false,
- message: errorUtil.toString(message)
- });
- }
- nonpositive(message) {
- return this._addCheck({
- kind: "max",
- value: BigInt(0),
- inclusive: true,
- message: errorUtil.toString(message)
- });
- }
- nonnegative(message) {
- return this._addCheck({
- kind: "min",
- value: BigInt(0),
- inclusive: true,
- message: errorUtil.toString(message)
- });
- }
- multipleOf(value, message) {
- return this._addCheck({
- kind: "multipleOf",
- value,
- message: errorUtil.toString(message)
- });
- }
- get minValue() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min;
- }
- get maxValue() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max;
- }
- };
- ZodBigInt.create = (params) => {
- return new ZodBigInt({
- checks: [],
- typeName: ZodFirstPartyTypeKind.ZodBigInt,
- coerce: (params == null ? void 0 : params.coerce) ?? false,
- ...processCreateParams(params)
- });
- };
- var ZodBoolean = class extends ZodType {
- _parse(input) {
- if (this._def.coerce) {
- input.data = Boolean(input.data);
- }
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.boolean) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.boolean,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return OK(input.data);
- }
- };
- ZodBoolean.create = (params) => {
- return new ZodBoolean({
- typeName: ZodFirstPartyTypeKind.ZodBoolean,
- coerce: (params == null ? void 0 : params.coerce) || false,
- ...processCreateParams(params)
- });
- };
- var ZodDate = class _ZodDate extends ZodType {
- _parse(input) {
- if (this._def.coerce) {
- input.data = new Date(input.data);
- }
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.date) {
- const ctx2 = this._getOrReturnCtx(input);
- addIssueToContext(ctx2, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.date,
- received: ctx2.parsedType
- });
- return INVALID;
- }
- if (Number.isNaN(input.data.getTime())) {
- const ctx2 = this._getOrReturnCtx(input);
- addIssueToContext(ctx2, {
- code: ZodIssueCode.invalid_date
- });
- return INVALID;
- }
- const status = new ParseStatus();
- let ctx = void 0;
- for (const check of this._def.checks) {
- if (check.kind === "min") {
- if (input.data.getTime() < check.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- message: check.message,
- inclusive: true,
- exact: false,
- minimum: check.value,
- type: "date"
- });
- status.dirty();
- }
- } else if (check.kind === "max") {
- if (input.data.getTime() > check.value) {
- ctx = this._getOrReturnCtx(input, ctx);
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- message: check.message,
- inclusive: true,
- exact: false,
- maximum: check.value,
- type: "date"
- });
- status.dirty();
- }
- } else {
- util.assertNever(check);
- }
- }
- return {
- status: status.value,
- value: new Date(input.data.getTime())
- };
- }
- _addCheck(check) {
- return new _ZodDate({
- ...this._def,
- checks: [...this._def.checks, check]
- });
- }
- min(minDate, message) {
- return this._addCheck({
- kind: "min",
- value: minDate.getTime(),
- message: errorUtil.toString(message)
- });
- }
- max(maxDate, message) {
- return this._addCheck({
- kind: "max",
- value: maxDate.getTime(),
- message: errorUtil.toString(message)
- });
- }
- get minDate() {
- let min = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "min") {
- if (min === null || ch.value > min)
- min = ch.value;
- }
- }
- return min != null ? new Date(min) : null;
- }
- get maxDate() {
- let max = null;
- for (const ch of this._def.checks) {
- if (ch.kind === "max") {
- if (max === null || ch.value < max)
- max = ch.value;
- }
- }
- return max != null ? new Date(max) : null;
- }
- };
- ZodDate.create = (params) => {
- return new ZodDate({
- checks: [],
- coerce: (params == null ? void 0 : params.coerce) || false,
- typeName: ZodFirstPartyTypeKind.ZodDate,
- ...processCreateParams(params)
- });
- };
- var ZodSymbol = class extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.symbol) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.symbol,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return OK(input.data);
- }
- };
- ZodSymbol.create = (params) => {
- return new ZodSymbol({
- typeName: ZodFirstPartyTypeKind.ZodSymbol,
- ...processCreateParams(params)
- });
- };
- var ZodUndefined = class extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.undefined) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.undefined,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return OK(input.data);
- }
- };
- ZodUndefined.create = (params) => {
- return new ZodUndefined({
- typeName: ZodFirstPartyTypeKind.ZodUndefined,
- ...processCreateParams(params)
- });
- };
- var ZodNull = class extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.null) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.null,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return OK(input.data);
- }
- };
- ZodNull.create = (params) => {
- return new ZodNull({
- typeName: ZodFirstPartyTypeKind.ZodNull,
- ...processCreateParams(params)
- });
- };
- var ZodAny = class extends ZodType {
- constructor() {
- super(...arguments);
- this._any = true;
- }
- _parse(input) {
- return OK(input.data);
- }
- };
- ZodAny.create = (params) => {
- return new ZodAny({
- typeName: ZodFirstPartyTypeKind.ZodAny,
- ...processCreateParams(params)
- });
- };
- var ZodUnknown = class extends ZodType {
- constructor() {
- super(...arguments);
- this._unknown = true;
- }
- _parse(input) {
- return OK(input.data);
- }
- };
- ZodUnknown.create = (params) => {
- return new ZodUnknown({
- typeName: ZodFirstPartyTypeKind.ZodUnknown,
- ...processCreateParams(params)
- });
- };
- var ZodNever = class extends ZodType {
- _parse(input) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.never,
- received: ctx.parsedType
- });
- return INVALID;
- }
- };
- ZodNever.create = (params) => {
- return new ZodNever({
- typeName: ZodFirstPartyTypeKind.ZodNever,
- ...processCreateParams(params)
- });
- };
- var ZodVoid = class extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.undefined) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.void,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return OK(input.data);
- }
- };
- ZodVoid.create = (params) => {
- return new ZodVoid({
- typeName: ZodFirstPartyTypeKind.ZodVoid,
- ...processCreateParams(params)
- });
- };
- var ZodArray = class _ZodArray extends ZodType {
- _parse(input) {
- const { ctx, status } = this._processInputParams(input);
- const def = this._def;
- if (ctx.parsedType !== ZodParsedType.array) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.array,
- received: ctx.parsedType
- });
- return INVALID;
- }
- if (def.exactLength !== null) {
- const tooBig = ctx.data.length > def.exactLength.value;
- const tooSmall = ctx.data.length < def.exactLength.value;
- if (tooBig || tooSmall) {
- addIssueToContext(ctx, {
- code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
- minimum: tooSmall ? def.exactLength.value : void 0,
- maximum: tooBig ? def.exactLength.value : void 0,
- type: "array",
- inclusive: true,
- exact: true,
- message: def.exactLength.message
- });
- status.dirty();
- }
- }
- if (def.minLength !== null) {
- if (ctx.data.length < def.minLength.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: def.minLength.value,
- type: "array",
- inclusive: true,
- exact: false,
- message: def.minLength.message
- });
- status.dirty();
- }
- }
- if (def.maxLength !== null) {
- if (ctx.data.length > def.maxLength.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: def.maxLength.value,
- type: "array",
- inclusive: true,
- exact: false,
- message: def.maxLength.message
- });
- status.dirty();
- }
- }
- if (ctx.common.async) {
- return Promise.all([...ctx.data].map((item, i) => {
- return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
- })).then((result2) => {
- return ParseStatus.mergeArray(status, result2);
- });
- }
- const result = [...ctx.data].map((item, i) => {
- return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
- });
- return ParseStatus.mergeArray(status, result);
- }
- get element() {
- return this._def.type;
- }
- min(minLength, message) {
- return new _ZodArray({
- ...this._def,
- minLength: { value: minLength, message: errorUtil.toString(message) }
- });
- }
- max(maxLength, message) {
- return new _ZodArray({
- ...this._def,
- maxLength: { value: maxLength, message: errorUtil.toString(message) }
- });
- }
- length(len, message) {
- return new _ZodArray({
- ...this._def,
- exactLength: { value: len, message: errorUtil.toString(message) }
- });
- }
- nonempty(message) {
- return this.min(1, message);
- }
- };
- ZodArray.create = (schema4, params) => {
- return new ZodArray({
- type: schema4,
- minLength: null,
- maxLength: null,
- exactLength: null,
- typeName: ZodFirstPartyTypeKind.ZodArray,
- ...processCreateParams(params)
- });
- };
- function deepPartialify(schema4) {
- if (schema4 instanceof ZodObject) {
- const newShape = {};
- for (const key in schema4.shape) {
- const fieldSchema = schema4.shape[key];
- newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
- }
- return new ZodObject({
- ...schema4._def,
- shape: () => newShape
- });
- } else if (schema4 instanceof ZodArray) {
- return new ZodArray({
- ...schema4._def,
- type: deepPartialify(schema4.element)
- });
- } else if (schema4 instanceof ZodOptional) {
- return ZodOptional.create(deepPartialify(schema4.unwrap()));
- } else if (schema4 instanceof ZodNullable) {
- return ZodNullable.create(deepPartialify(schema4.unwrap()));
- } else if (schema4 instanceof ZodTuple) {
- return ZodTuple.create(schema4.items.map((item) => deepPartialify(item)));
- } else {
- return schema4;
- }
- }
- var ZodObject = class _ZodObject extends ZodType {
- constructor() {
- super(...arguments);
- this._cached = null;
- this.nonstrict = this.passthrough;
- this.augment = this.extend;
- }
- _getCached() {
- if (this._cached !== null)
- return this._cached;
- const shape = this._def.shape();
- const keys = util.objectKeys(shape);
- this._cached = { shape, keys };
- return this._cached;
- }
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.object) {
- const ctx2 = this._getOrReturnCtx(input);
- addIssueToContext(ctx2, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.object,
- received: ctx2.parsedType
- });
- return INVALID;
- }
- const { status, ctx } = this._processInputParams(input);
- const { shape, keys: shapeKeys } = this._getCached();
- const extraKeys = [];
- if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
- for (const key in ctx.data) {
- if (!shapeKeys.includes(key)) {
- extraKeys.push(key);
- }
- }
- }
- const pairs = [];
- for (const key of shapeKeys) {
- const keyValidator = shape[key];
- const value = ctx.data[key];
- pairs.push({
- key: { status: "valid", value: key },
- value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
- alwaysSet: key in ctx.data
- });
- }
- if (this._def.catchall instanceof ZodNever) {
- const unknownKeys = this._def.unknownKeys;
- if (unknownKeys === "passthrough") {
- for (const key of extraKeys) {
- pairs.push({
- key: { status: "valid", value: key },
- value: { status: "valid", value: ctx.data[key] }
- });
- }
- } else if (unknownKeys === "strict") {
- if (extraKeys.length > 0) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.unrecognized_keys,
- keys: extraKeys
- });
- status.dirty();
- }
- } else if (unknownKeys === "strip") {
- } else {
- throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
- }
- } else {
- const catchall = this._def.catchall;
- for (const key of extraKeys) {
- const value = ctx.data[key];
- pairs.push({
- key: { status: "valid", value: key },
- value: catchall._parse(
- new ParseInputLazyPath(ctx, value, ctx.path, key)
- //, ctx.child(key), value, getParsedType(value)
- ),
- alwaysSet: key in ctx.data
- });
- }
- }
- if (ctx.common.async) {
- return Promise.resolve().then(async () => {
- const syncPairs = [];
- for (const pair of pairs) {
- const key = await pair.key;
- const value = await pair.value;
- syncPairs.push({
- key,
- value,
- alwaysSet: pair.alwaysSet
- });
- }
- return syncPairs;
- }).then((syncPairs) => {
- return ParseStatus.mergeObjectSync(status, syncPairs);
- });
- } else {
- return ParseStatus.mergeObjectSync(status, pairs);
- }
- }
- get shape() {
- return this._def.shape();
- }
- strict(message) {
- errorUtil.errToObj;
- return new _ZodObject({
- ...this._def,
- unknownKeys: "strict",
- ...message !== void 0 ? {
- errorMap: (issue, ctx) => {
- var _a, _b;
- const defaultError = ((_b = (_a = this._def).errorMap) == null ? void 0 : _b.call(_a, issue, ctx).message) ?? ctx.defaultError;
- if (issue.code === "unrecognized_keys")
- return {
- message: errorUtil.errToObj(message).message ?? defaultError
- };
- return {
- message: defaultError
- };
- }
- } : {}
- });
- }
- strip() {
- return new _ZodObject({
- ...this._def,
- unknownKeys: "strip"
- });
- }
- passthrough() {
- return new _ZodObject({
- ...this._def,
- unknownKeys: "passthrough"
- });
- }
- // const AugmentFactory =
- // <Def extends ZodObjectDef>(def: Def) =>
- // <Augmentation extends ZodRawShape>(
- // augmentation: Augmentation
- // ): ZodObject<
- // extendShape<ReturnType<Def["shape"]>, Augmentation>,
- // Def["unknownKeys"],
- // Def["catchall"]
- // > => {
- // return new ZodObject({
- // ...def,
- // shape: () => ({
- // ...def.shape(),
- // ...augmentation,
- // }),
- // }) as any;
- // };
- extend(augmentation) {
- return new _ZodObject({
- ...this._def,
- shape: () => ({
- ...this._def.shape(),
- ...augmentation
- })
- });
- }
- /**
- * Prior to zod@1.0.12 there was a bug in the
- * inferred type of merged objects. Please
- * upgrade if you are experiencing issues.
- */
- merge(merging) {
- const merged = new _ZodObject({
- unknownKeys: merging._def.unknownKeys,
- catchall: merging._def.catchall,
- shape: () => ({
- ...this._def.shape(),
- ...merging._def.shape()
- }),
- typeName: ZodFirstPartyTypeKind.ZodObject
- });
- return merged;
- }
- // merge<
- // Incoming extends AnyZodObject,
- // Augmentation extends Incoming["shape"],
- // NewOutput extends {
- // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
- // ? Augmentation[k]["_output"]
- // : k extends keyof Output
- // ? Output[k]
- // : never;
- // },
- // NewInput extends {
- // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
- // ? Augmentation[k]["_input"]
- // : k extends keyof Input
- // ? Input[k]
- // : never;
- // }
- // >(
- // merging: Incoming
- // ): ZodObject<
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
- // Incoming["_def"]["unknownKeys"],
- // Incoming["_def"]["catchall"],
- // NewOutput,
- // NewInput
- // > {
- // const merged: any = new ZodObject({
- // unknownKeys: merging._def.unknownKeys,
- // catchall: merging._def.catchall,
- // shape: () =>
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
- // typeName: ZodFirstPartyTypeKind.ZodObject,
- // }) as any;
- // return merged;
- // }
- setKey(key, schema4) {
- return this.augment({ [key]: schema4 });
- }
- // merge<Incoming extends AnyZodObject>(
- // merging: Incoming
- // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
- // ZodObject<
- // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
- // Incoming["_def"]["unknownKeys"],
- // Incoming["_def"]["catchall"]
- // > {
- // // const mergedShape = objectUtil.mergeShapes(
- // // this._def.shape(),
- // // merging._def.shape()
- // // );
- // const merged: any = new ZodObject({
- // unknownKeys: merging._def.unknownKeys,
- // catchall: merging._def.catchall,
- // shape: () =>
- // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
- // typeName: ZodFirstPartyTypeKind.ZodObject,
- // }) as any;
- // return merged;
- // }
- catchall(index6) {
- return new _ZodObject({
- ...this._def,
- catchall: index6
- });
- }
- pick(mask) {
- const shape = {};
- for (const key of util.objectKeys(mask)) {
- if (mask[key] && this.shape[key]) {
- shape[key] = this.shape[key];
- }
- }
- return new _ZodObject({
- ...this._def,
- shape: () => shape
- });
- }
- omit(mask) {
- const shape = {};
- for (const key of util.objectKeys(this.shape)) {
- if (!mask[key]) {
- shape[key] = this.shape[key];
- }
- }
- return new _ZodObject({
- ...this._def,
- shape: () => shape
- });
- }
- /**
- * @deprecated
- */
- deepPartial() {
- return deepPartialify(this);
- }
- partial(mask) {
- const newShape = {};
- for (const key of util.objectKeys(this.shape)) {
- const fieldSchema = this.shape[key];
- if (mask && !mask[key]) {
- newShape[key] = fieldSchema;
- } else {
- newShape[key] = fieldSchema.optional();
- }
- }
- return new _ZodObject({
- ...this._def,
- shape: () => newShape
- });
- }
- required(mask) {
- const newShape = {};
- for (const key of util.objectKeys(this.shape)) {
- if (mask && !mask[key]) {
- newShape[key] = this.shape[key];
- } else {
- const fieldSchema = this.shape[key];
- let newField = fieldSchema;
- while (newField instanceof ZodOptional) {
- newField = newField._def.innerType;
- }
- newShape[key] = newField;
- }
- }
- return new _ZodObject({
- ...this._def,
- shape: () => newShape
- });
- }
- keyof() {
- return createZodEnum(util.objectKeys(this.shape));
- }
- };
- ZodObject.create = (shape, params) => {
- return new ZodObject({
- shape: () => shape,
- unknownKeys: "strip",
- catchall: ZodNever.create(),
- typeName: ZodFirstPartyTypeKind.ZodObject,
- ...processCreateParams(params)
- });
- };
- ZodObject.strictCreate = (shape, params) => {
- return new ZodObject({
- shape: () => shape,
- unknownKeys: "strict",
- catchall: ZodNever.create(),
- typeName: ZodFirstPartyTypeKind.ZodObject,
- ...processCreateParams(params)
- });
- };
- ZodObject.lazycreate = (shape, params) => {
- return new ZodObject({
- shape,
- unknownKeys: "strip",
- catchall: ZodNever.create(),
- typeName: ZodFirstPartyTypeKind.ZodObject,
- ...processCreateParams(params)
- });
- };
- var ZodUnion = class extends ZodType {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const options = this._def.options;
- function handleResults(results) {
- for (const result of results) {
- if (result.result.status === "valid") {
- return result.result;
- }
- }
- for (const result of results) {
- if (result.result.status === "dirty") {
- ctx.common.issues.push(...result.ctx.common.issues);
- return result.result;
- }
- }
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_union,
- unionErrors
- });
- return INVALID;
- }
- if (ctx.common.async) {
- return Promise.all(options.map(async (option) => {
- const childCtx = {
- ...ctx,
- common: {
- ...ctx.common,
- issues: []
- },
- parent: null
- };
- return {
- result: await option._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: childCtx
- }),
- ctx: childCtx
- };
- })).then(handleResults);
- } else {
- let dirty = void 0;
- const issues = [];
- for (const option of options) {
- const childCtx = {
- ...ctx,
- common: {
- ...ctx.common,
- issues: []
- },
- parent: null
- };
- const result = option._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: childCtx
- });
- if (result.status === "valid") {
- return result;
- } else if (result.status === "dirty" && !dirty) {
- dirty = { result, ctx: childCtx };
- }
- if (childCtx.common.issues.length) {
- issues.push(childCtx.common.issues);
- }
- }
- if (dirty) {
- ctx.common.issues.push(...dirty.ctx.common.issues);
- return dirty.result;
- }
- const unionErrors = issues.map((issues2) => new ZodError(issues2));
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_union,
- unionErrors
- });
- return INVALID;
- }
- }
- get options() {
- return this._def.options;
- }
- };
- ZodUnion.create = (types, params) => {
- return new ZodUnion({
- options: types,
- typeName: ZodFirstPartyTypeKind.ZodUnion,
- ...processCreateParams(params)
- });
- };
- var getDiscriminator = (type) => {
- if (type instanceof ZodLazy) {
- return getDiscriminator(type.schema);
- } else if (type instanceof ZodEffects) {
- return getDiscriminator(type.innerType());
- } else if (type instanceof ZodLiteral) {
- return [type.value];
- } else if (type instanceof ZodEnum) {
- return type.options;
- } else if (type instanceof ZodNativeEnum) {
- return util.objectValues(type.enum);
- } else if (type instanceof ZodDefault) {
- return getDiscriminator(type._def.innerType);
- } else if (type instanceof ZodUndefined) {
- return [void 0];
- } else if (type instanceof ZodNull) {
- return [null];
- } else if (type instanceof ZodOptional) {
- return [void 0, ...getDiscriminator(type.unwrap())];
- } else if (type instanceof ZodNullable) {
- return [null, ...getDiscriminator(type.unwrap())];
- } else if (type instanceof ZodBranded) {
- return getDiscriminator(type.unwrap());
- } else if (type instanceof ZodReadonly) {
- return getDiscriminator(type.unwrap());
- } else if (type instanceof ZodCatch) {
- return getDiscriminator(type._def.innerType);
- } else {
- return [];
- }
- };
- var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.object) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.object,
- received: ctx.parsedType
- });
- return INVALID;
- }
- const discriminator = this.discriminator;
- const discriminatorValue = ctx.data[discriminator];
- const option = this.optionsMap.get(discriminatorValue);
- if (!option) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_union_discriminator,
- options: Array.from(this.optionsMap.keys()),
- path: [discriminator]
- });
- return INVALID;
- }
- if (ctx.common.async) {
- return option._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- } else {
- return option._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- }
- }
- get discriminator() {
- return this._def.discriminator;
- }
- get options() {
- return this._def.options;
- }
- get optionsMap() {
- return this._def.optionsMap;
- }
- /**
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
- * have a different value for each object in the union.
- * @param discriminator the name of the discriminator property
- * @param types an array of object schemas
- * @param params
- */
- static create(discriminator, options, params) {
- const optionsMap = /* @__PURE__ */ new Map();
- for (const type of options) {
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
- if (!discriminatorValues.length) {
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
- }
- for (const value of discriminatorValues) {
- if (optionsMap.has(value)) {
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
- }
- optionsMap.set(value, type);
- }
- }
- return new _ZodDiscriminatedUnion({
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
- discriminator,
- options,
- optionsMap,
- ...processCreateParams(params)
- });
- }
- };
- function mergeValues(a, b) {
- const aType = getParsedType(a);
- const bType = getParsedType(b);
- if (a === b) {
- return { valid: true, data: a };
- } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
- const bKeys = util.objectKeys(b);
- const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
- const newObj = { ...a, ...b };
- for (const key of sharedKeys) {
- const sharedValue = mergeValues(a[key], b[key]);
- if (!sharedValue.valid) {
- return { valid: false };
- }
- newObj[key] = sharedValue.data;
- }
- return { valid: true, data: newObj };
- } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
- if (a.length !== b.length) {
- return { valid: false };
- }
- const newArray = [];
- for (let index6 = 0; index6 < a.length; index6++) {
- const itemA = a[index6];
- const itemB = b[index6];
- const sharedValue = mergeValues(itemA, itemB);
- if (!sharedValue.valid) {
- return { valid: false };
- }
- newArray.push(sharedValue.data);
- }
- return { valid: true, data: newArray };
- } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
- return { valid: true, data: a };
- } else {
- return { valid: false };
- }
- }
- var ZodIntersection = class extends ZodType {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- const handleParsed = (parsedLeft, parsedRight) => {
- if (isAborted(parsedLeft) || isAborted(parsedRight)) {
- return INVALID;
- }
- const merged = mergeValues(parsedLeft.value, parsedRight.value);
- if (!merged.valid) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_intersection_types
- });
- return INVALID;
- }
- if (isDirty(parsedLeft) || isDirty(parsedRight)) {
- status.dirty();
- }
- return { status: status.value, value: merged.data };
- };
- if (ctx.common.async) {
- return Promise.all([
- this._def.left._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- }),
- this._def.right._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- })
- ]).then(([left, right]) => handleParsed(left, right));
- } else {
- return handleParsed(this._def.left._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- }), this._def.right._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- }));
- }
- }
- };
- ZodIntersection.create = (left, right, params) => {
- return new ZodIntersection({
- left,
- right,
- typeName: ZodFirstPartyTypeKind.ZodIntersection,
- ...processCreateParams(params)
- });
- };
- var ZodTuple = class _ZodTuple extends ZodType {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.array) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.array,
- received: ctx.parsedType
- });
- return INVALID;
- }
- if (ctx.data.length < this._def.items.length) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: this._def.items.length,
- inclusive: true,
- exact: false,
- type: "array"
- });
- return INVALID;
- }
- const rest = this._def.rest;
- if (!rest && ctx.data.length > this._def.items.length) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: this._def.items.length,
- inclusive: true,
- exact: false,
- type: "array"
- });
- status.dirty();
- }
- const items = [...ctx.data].map((item, itemIndex) => {
- const schema4 = this._def.items[itemIndex] || this._def.rest;
- if (!schema4)
- return null;
- return schema4._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
- }).filter((x) => !!x);
- if (ctx.common.async) {
- return Promise.all(items).then((results) => {
- return ParseStatus.mergeArray(status, results);
- });
- } else {
- return ParseStatus.mergeArray(status, items);
- }
- }
- get items() {
- return this._def.items;
- }
- rest(rest) {
- return new _ZodTuple({
- ...this._def,
- rest
- });
- }
- };
- ZodTuple.create = (schemas, params) => {
- if (!Array.isArray(schemas)) {
- throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
- }
- return new ZodTuple({
- items: schemas,
- typeName: ZodFirstPartyTypeKind.ZodTuple,
- rest: null,
- ...processCreateParams(params)
- });
- };
- var ZodRecord = class _ZodRecord extends ZodType {
- get keySchema() {
- return this._def.keyType;
- }
- get valueSchema() {
- return this._def.valueType;
- }
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.object) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.object,
- received: ctx.parsedType
- });
- return INVALID;
- }
- const pairs = [];
- const keyType = this._def.keyType;
- const valueType = this._def.valueType;
- for (const key in ctx.data) {
- pairs.push({
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
- alwaysSet: key in ctx.data
- });
- }
- if (ctx.common.async) {
- return ParseStatus.mergeObjectAsync(status, pairs);
- } else {
- return ParseStatus.mergeObjectSync(status, pairs);
- }
- }
- get element() {
- return this._def.valueType;
- }
- static create(first, second, third) {
- if (second instanceof ZodType) {
- return new _ZodRecord({
- keyType: first,
- valueType: second,
- typeName: ZodFirstPartyTypeKind.ZodRecord,
- ...processCreateParams(third)
- });
- }
- return new _ZodRecord({
- keyType: ZodString.create(),
- valueType: first,
- typeName: ZodFirstPartyTypeKind.ZodRecord,
- ...processCreateParams(second)
- });
- }
- };
- var ZodMap = class extends ZodType {
- get keySchema() {
- return this._def.keyType;
- }
- get valueSchema() {
- return this._def.valueType;
- }
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.map) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.map,
- received: ctx.parsedType
- });
- return INVALID;
- }
- const keyType = this._def.keyType;
- const valueType = this._def.valueType;
- const pairs = [...ctx.data.entries()].map(([key, value], index6) => {
- return {
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index6, "key"])),
- value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index6, "value"]))
- };
- });
- if (ctx.common.async) {
- const finalMap = /* @__PURE__ */ new Map();
- return Promise.resolve().then(async () => {
- for (const pair of pairs) {
- const key = await pair.key;
- const value = await pair.value;
- if (key.status === "aborted" || value.status === "aborted") {
- return INVALID;
- }
- if (key.status === "dirty" || value.status === "dirty") {
- status.dirty();
- }
- finalMap.set(key.value, value.value);
- }
- return { status: status.value, value: finalMap };
- });
- } else {
- const finalMap = /* @__PURE__ */ new Map();
- for (const pair of pairs) {
- const key = pair.key;
- const value = pair.value;
- if (key.status === "aborted" || value.status === "aborted") {
- return INVALID;
- }
- if (key.status === "dirty" || value.status === "dirty") {
- status.dirty();
- }
- finalMap.set(key.value, value.value);
- }
- return { status: status.value, value: finalMap };
- }
- }
- };
- ZodMap.create = (keyType, valueType, params) => {
- return new ZodMap({
- valueType,
- keyType,
- typeName: ZodFirstPartyTypeKind.ZodMap,
- ...processCreateParams(params)
- });
- };
- var ZodSet = class _ZodSet extends ZodType {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.set) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.set,
- received: ctx.parsedType
- });
- return INVALID;
- }
- const def = this._def;
- if (def.minSize !== null) {
- if (ctx.data.size < def.minSize.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_small,
- minimum: def.minSize.value,
- type: "set",
- inclusive: true,
- exact: false,
- message: def.minSize.message
- });
- status.dirty();
- }
- }
- if (def.maxSize !== null) {
- if (ctx.data.size > def.maxSize.value) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.too_big,
- maximum: def.maxSize.value,
- type: "set",
- inclusive: true,
- exact: false,
- message: def.maxSize.message
- });
- status.dirty();
- }
- }
- const valueType = this._def.valueType;
- function finalizeSet(elements2) {
- const parsedSet = /* @__PURE__ */ new Set();
- for (const element of elements2) {
- if (element.status === "aborted")
- return INVALID;
- if (element.status === "dirty")
- status.dirty();
- parsedSet.add(element.value);
- }
- return { status: status.value, value: parsedSet };
- }
- const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
- if (ctx.common.async) {
- return Promise.all(elements).then((elements2) => finalizeSet(elements2));
- } else {
- return finalizeSet(elements);
- }
- }
- min(minSize, message) {
- return new _ZodSet({
- ...this._def,
- minSize: { value: minSize, message: errorUtil.toString(message) }
- });
- }
- max(maxSize, message) {
- return new _ZodSet({
- ...this._def,
- maxSize: { value: maxSize, message: errorUtil.toString(message) }
- });
- }
- size(size, message) {
- return this.min(size, message).max(size, message);
- }
- nonempty(message) {
- return this.min(1, message);
- }
- };
- ZodSet.create = (valueType, params) => {
- return new ZodSet({
- valueType,
- minSize: null,
- maxSize: null,
- typeName: ZodFirstPartyTypeKind.ZodSet,
- ...processCreateParams(params)
- });
- };
- var ZodFunction = class _ZodFunction extends ZodType {
- constructor() {
- super(...arguments);
- this.validate = this.implement;
- }
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.function) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.function,
- received: ctx.parsedType
- });
- return INVALID;
- }
- function makeArgsIssue(args, error) {
- return makeIssue({
- data: args,
- path: ctx.path,
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
- issueData: {
- code: ZodIssueCode.invalid_arguments,
- argumentsError: error
- }
- });
- }
- function makeReturnsIssue(returns, error) {
- return makeIssue({
- data: returns,
- path: ctx.path,
- errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
- issueData: {
- code: ZodIssueCode.invalid_return_type,
- returnTypeError: error
- }
- });
- }
- const params = { errorMap: ctx.common.contextualErrorMap };
- const fn = ctx.data;
- if (this._def.returns instanceof ZodPromise) {
- const me = this;
- return OK(async function(...args) {
- const error = new ZodError([]);
- const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
- error.addIssue(makeArgsIssue(args, e));
- throw error;
- });
- const result = await Reflect.apply(fn, this, parsedArgs);
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
- error.addIssue(makeReturnsIssue(result, e));
- throw error;
- });
- return parsedReturns;
- });
- } else {
- const me = this;
- return OK(function(...args) {
- const parsedArgs = me._def.args.safeParse(args, params);
- if (!parsedArgs.success) {
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
- }
- const result = Reflect.apply(fn, this, parsedArgs.data);
- const parsedReturns = me._def.returns.safeParse(result, params);
- if (!parsedReturns.success) {
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
- }
- return parsedReturns.data;
- });
- }
- }
- parameters() {
- return this._def.args;
- }
- returnType() {
- return this._def.returns;
- }
- args(...items) {
- return new _ZodFunction({
- ...this._def,
- args: ZodTuple.create(items).rest(ZodUnknown.create())
- });
- }
- returns(returnType) {
- return new _ZodFunction({
- ...this._def,
- returns: returnType
- });
- }
- implement(func) {
- const validatedFunc = this.parse(func);
- return validatedFunc;
- }
- strictImplement(func) {
- const validatedFunc = this.parse(func);
- return validatedFunc;
- }
- static create(args, returns, params) {
- return new _ZodFunction({
- args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
- returns: returns || ZodUnknown.create(),
- typeName: ZodFirstPartyTypeKind.ZodFunction,
- ...processCreateParams(params)
- });
- }
- };
- var ZodLazy = class extends ZodType {
- get schema() {
- return this._def.getter();
- }
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const lazySchema = this._def.getter();
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
- }
- };
- ZodLazy.create = (getter, params) => {
- return new ZodLazy({
- getter,
- typeName: ZodFirstPartyTypeKind.ZodLazy,
- ...processCreateParams(params)
- });
- };
- var ZodLiteral = class extends ZodType {
- _parse(input) {
- if (input.data !== this._def.value) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- received: ctx.data,
- code: ZodIssueCode.invalid_literal,
- expected: this._def.value
- });
- return INVALID;
- }
- return { status: "valid", value: input.data };
- }
- get value() {
- return this._def.value;
- }
- };
- ZodLiteral.create = (value, params) => {
- return new ZodLiteral({
- value,
- typeName: ZodFirstPartyTypeKind.ZodLiteral,
- ...processCreateParams(params)
- });
- };
- function createZodEnum(values, params) {
- return new ZodEnum({
- values,
- typeName: ZodFirstPartyTypeKind.ZodEnum,
- ...processCreateParams(params)
- });
- }
- var ZodEnum = class _ZodEnum extends ZodType {
- _parse(input) {
- if (typeof input.data !== "string") {
- const ctx = this._getOrReturnCtx(input);
- const expectedValues = this._def.values;
- addIssueToContext(ctx, {
- expected: util.joinValues(expectedValues),
- received: ctx.parsedType,
- code: ZodIssueCode.invalid_type
- });
- return INVALID;
- }
- if (!this._cache) {
- this._cache = new Set(this._def.values);
- }
- if (!this._cache.has(input.data)) {
- const ctx = this._getOrReturnCtx(input);
- const expectedValues = this._def.values;
- addIssueToContext(ctx, {
- received: ctx.data,
- code: ZodIssueCode.invalid_enum_value,
- options: expectedValues
- });
- return INVALID;
- }
- return OK(input.data);
- }
- get options() {
- return this._def.values;
- }
- get enum() {
- const enumValues = {};
- for (const val of this._def.values) {
- enumValues[val] = val;
- }
- return enumValues;
- }
- get Values() {
- const enumValues = {};
- for (const val of this._def.values) {
- enumValues[val] = val;
- }
- return enumValues;
- }
- get Enum() {
- const enumValues = {};
- for (const val of this._def.values) {
- enumValues[val] = val;
- }
- return enumValues;
- }
- extract(values, newDef = this._def) {
- return _ZodEnum.create(values, {
- ...this._def,
- ...newDef
- });
- }
- exclude(values, newDef = this._def) {
- return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
- ...this._def,
- ...newDef
- });
- }
- };
- ZodEnum.create = createZodEnum;
- var ZodNativeEnum = class extends ZodType {
- _parse(input) {
- const nativeEnumValues = util.getValidEnumValues(this._def.values);
- const ctx = this._getOrReturnCtx(input);
- if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
- const expectedValues = util.objectValues(nativeEnumValues);
- addIssueToContext(ctx, {
- expected: util.joinValues(expectedValues),
- received: ctx.parsedType,
- code: ZodIssueCode.invalid_type
- });
- return INVALID;
- }
- if (!this._cache) {
- this._cache = new Set(util.getValidEnumValues(this._def.values));
- }
- if (!this._cache.has(input.data)) {
- const expectedValues = util.objectValues(nativeEnumValues);
- addIssueToContext(ctx, {
- received: ctx.data,
- code: ZodIssueCode.invalid_enum_value,
- options: expectedValues
- });
- return INVALID;
- }
- return OK(input.data);
- }
- get enum() {
- return this._def.values;
- }
- };
- ZodNativeEnum.create = (values, params) => {
- return new ZodNativeEnum({
- values,
- typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
- ...processCreateParams(params)
- });
- };
- var ZodPromise = class extends ZodType {
- unwrap() {
- return this._def.type;
- }
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.promise,
- received: ctx.parsedType
- });
- return INVALID;
- }
- const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
- return OK(promisified.then((data) => {
- return this._def.type.parseAsync(data, {
- path: ctx.path,
- errorMap: ctx.common.contextualErrorMap
- });
- }));
- }
- };
- ZodPromise.create = (schema4, params) => {
- return new ZodPromise({
- type: schema4,
- typeName: ZodFirstPartyTypeKind.ZodPromise,
- ...processCreateParams(params)
- });
- };
- var ZodEffects = class extends ZodType {
- innerType() {
- return this._def.schema;
- }
- sourceType() {
- return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
- }
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- const effect = this._def.effect || null;
- const checkCtx = {
- addIssue: (arg) => {
- addIssueToContext(ctx, arg);
- if (arg.fatal) {
- status.abort();
- } else {
- status.dirty();
- }
- },
- get path() {
- return ctx.path;
- }
- };
- checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
- if (effect.type === "preprocess") {
- const processed = effect.transform(ctx.data, checkCtx);
- if (ctx.common.async) {
- return Promise.resolve(processed).then(async (processed2) => {
- if (status.value === "aborted")
- return INVALID;
- const result = await this._def.schema._parseAsync({
- data: processed2,
- path: ctx.path,
- parent: ctx
- });
- if (result.status === "aborted")
- return INVALID;
- if (result.status === "dirty")
- return DIRTY(result.value);
- if (status.value === "dirty")
- return DIRTY(result.value);
- return result;
- });
- } else {
- if (status.value === "aborted")
- return INVALID;
- const result = this._def.schema._parseSync({
- data: processed,
- path: ctx.path,
- parent: ctx
- });
- if (result.status === "aborted")
- return INVALID;
- if (result.status === "dirty")
- return DIRTY(result.value);
- if (status.value === "dirty")
- return DIRTY(result.value);
- return result;
- }
- }
- if (effect.type === "refinement") {
- const executeRefinement = (acc) => {
- const result = effect.refinement(acc, checkCtx);
- if (ctx.common.async) {
- return Promise.resolve(result);
- }
- if (result instanceof Promise) {
- throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
- }
- return acc;
- };
- if (ctx.common.async === false) {
- const inner = this._def.schema._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- if (inner.status === "aborted")
- return INVALID;
- if (inner.status === "dirty")
- status.dirty();
- executeRefinement(inner.value);
- return { status: status.value, value: inner.value };
- } else {
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
- if (inner.status === "aborted")
- return INVALID;
- if (inner.status === "dirty")
- status.dirty();
- return executeRefinement(inner.value).then(() => {
- return { status: status.value, value: inner.value };
- });
- });
- }
- }
- if (effect.type === "transform") {
- if (ctx.common.async === false) {
- const base = this._def.schema._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- if (!isValid(base))
- return INVALID;
- const result = effect.transform(base.value, checkCtx);
- if (result instanceof Promise) {
- throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
- }
- return { status: status.value, value: result };
- } else {
- return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
- if (!isValid(base))
- return INVALID;
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
- status: status.value,
- value: result
- }));
- });
- }
- }
- util.assertNever(effect);
- }
- };
- ZodEffects.create = (schema4, effect, params) => {
- return new ZodEffects({
- schema: schema4,
- typeName: ZodFirstPartyTypeKind.ZodEffects,
- effect,
- ...processCreateParams(params)
- });
- };
- ZodEffects.createWithPreprocess = (preprocess, schema4, params) => {
- return new ZodEffects({
- schema: schema4,
- effect: { type: "preprocess", transform: preprocess },
- typeName: ZodFirstPartyTypeKind.ZodEffects,
- ...processCreateParams(params)
- });
- };
- var ZodOptional = class extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType === ZodParsedType.undefined) {
- return OK(void 0);
- }
- return this._def.innerType._parse(input);
- }
- unwrap() {
- return this._def.innerType;
- }
- };
- ZodOptional.create = (type, params) => {
- return new ZodOptional({
- innerType: type,
- typeName: ZodFirstPartyTypeKind.ZodOptional,
- ...processCreateParams(params)
- });
- };
- var ZodNullable = class extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType === ZodParsedType.null) {
- return OK(null);
- }
- return this._def.innerType._parse(input);
- }
- unwrap() {
- return this._def.innerType;
- }
- };
- ZodNullable.create = (type, params) => {
- return new ZodNullable({
- innerType: type,
- typeName: ZodFirstPartyTypeKind.ZodNullable,
- ...processCreateParams(params)
- });
- };
- var ZodDefault = class extends ZodType {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- let data = ctx.data;
- if (ctx.parsedType === ZodParsedType.undefined) {
- data = this._def.defaultValue();
- }
- return this._def.innerType._parse({
- data,
- path: ctx.path,
- parent: ctx
- });
- }
- removeDefault() {
- return this._def.innerType;
- }
- };
- ZodDefault.create = (type, params) => {
- return new ZodDefault({
- innerType: type,
- typeName: ZodFirstPartyTypeKind.ZodDefault,
- defaultValue: typeof params.default === "function" ? params.default : () => params.default,
- ...processCreateParams(params)
- });
- };
- var ZodCatch = class extends ZodType {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const newCtx = {
- ...ctx,
- common: {
- ...ctx.common,
- issues: []
- }
- };
- const result = this._def.innerType._parse({
- data: newCtx.data,
- path: newCtx.path,
- parent: {
- ...newCtx
- }
- });
- if (isAsync(result)) {
- return result.then((result2) => {
- return {
- status: "valid",
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
- get error() {
- return new ZodError(newCtx.common.issues);
- },
- input: newCtx.data
- })
- };
- });
- } else {
- return {
- status: "valid",
- value: result.status === "valid" ? result.value : this._def.catchValue({
- get error() {
- return new ZodError(newCtx.common.issues);
- },
- input: newCtx.data
- })
- };
- }
- }
- removeCatch() {
- return this._def.innerType;
- }
- };
- ZodCatch.create = (type, params) => {
- return new ZodCatch({
- innerType: type,
- typeName: ZodFirstPartyTypeKind.ZodCatch,
- catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
- ...processCreateParams(params)
- });
- };
- var ZodNaN = class extends ZodType {
- _parse(input) {
- const parsedType = this._getType(input);
- if (parsedType !== ZodParsedType.nan) {
- const ctx = this._getOrReturnCtx(input);
- addIssueToContext(ctx, {
- code: ZodIssueCode.invalid_type,
- expected: ZodParsedType.nan,
- received: ctx.parsedType
- });
- return INVALID;
- }
- return { status: "valid", value: input.data };
- }
- };
- ZodNaN.create = (params) => {
- return new ZodNaN({
- typeName: ZodFirstPartyTypeKind.ZodNaN,
- ...processCreateParams(params)
- });
- };
- var BRAND = Symbol("zod_brand");
- var ZodBranded = class extends ZodType {
- _parse(input) {
- const { ctx } = this._processInputParams(input);
- const data = ctx.data;
- return this._def.type._parse({
- data,
- path: ctx.path,
- parent: ctx
- });
- }
- unwrap() {
- return this._def.type;
- }
- };
- var ZodPipeline = class _ZodPipeline extends ZodType {
- _parse(input) {
- const { status, ctx } = this._processInputParams(input);
- if (ctx.common.async) {
- const handleAsync = async () => {
- const inResult = await this._def.in._parseAsync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- if (inResult.status === "aborted")
- return INVALID;
- if (inResult.status === "dirty") {
- status.dirty();
- return DIRTY(inResult.value);
- } else {
- return this._def.out._parseAsync({
- data: inResult.value,
- path: ctx.path,
- parent: ctx
- });
- }
- };
- return handleAsync();
- } else {
- const inResult = this._def.in._parseSync({
- data: ctx.data,
- path: ctx.path,
- parent: ctx
- });
- if (inResult.status === "aborted")
- return INVALID;
- if (inResult.status === "dirty") {
- status.dirty();
- return {
- status: "dirty",
- value: inResult.value
- };
- } else {
- return this._def.out._parseSync({
- data: inResult.value,
- path: ctx.path,
- parent: ctx
- });
- }
- }
- }
- static create(a, b) {
- return new _ZodPipeline({
- in: a,
- out: b,
- typeName: ZodFirstPartyTypeKind.ZodPipeline
- });
- }
- };
- var ZodReadonly = class extends ZodType {
- _parse(input) {
- const result = this._def.innerType._parse(input);
- const freeze = (data) => {
- if (isValid(data)) {
- data.value = Object.freeze(data.value);
- }
- return data;
- };
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
- }
- unwrap() {
- return this._def.innerType;
- }
- };
- ZodReadonly.create = (type, params) => {
- return new ZodReadonly({
- innerType: type,
- typeName: ZodFirstPartyTypeKind.ZodReadonly,
- ...processCreateParams(params)
- });
- };
- var late = {
- object: ZodObject.lazycreate
- };
- var ZodFirstPartyTypeKind;
- (function(ZodFirstPartyTypeKind2) {
- ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
- ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
- ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
- ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
- ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
- ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
- ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
- ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
- ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
- ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
- ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
- ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
- ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
- ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
- ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
- ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
- ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
- ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
- ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
- ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
- ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
- ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
- ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
- ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
- ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
- ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
- ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
- ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
- ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
- ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
- ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
- ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
- ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
- ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
- ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
- ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
- var stringType = ZodString.create;
- var numberType = ZodNumber.create;
- var nanType = ZodNaN.create;
- var bigIntType = ZodBigInt.create;
- var booleanType = ZodBoolean.create;
- var dateType = ZodDate.create;
- var symbolType = ZodSymbol.create;
- var undefinedType = ZodUndefined.create;
- var nullType = ZodNull.create;
- var anyType = ZodAny.create;
- var unknownType = ZodUnknown.create;
- var neverType = ZodNever.create;
- var voidType = ZodVoid.create;
- var arrayType = ZodArray.create;
- var objectType = ZodObject.create;
- var strictObjectType = ZodObject.strictCreate;
- var unionType = ZodUnion.create;
- var discriminatedUnionType = ZodDiscriminatedUnion.create;
- var intersectionType = ZodIntersection.create;
- var tupleType = ZodTuple.create;
- var recordType = ZodRecord.create;
- var mapType = ZodMap.create;
- var setType = ZodSet.create;
- var functionType = ZodFunction.create;
- var lazyType = ZodLazy.create;
- var literalType = ZodLiteral.create;
- var enumType = ZodEnum.create;
- var nativeEnumType = ZodNativeEnum.create;
- var promiseType = ZodPromise.create;
- var effectsType = ZodEffects.create;
- var optionalType = ZodOptional.create;
- var nullableType = ZodNullable.create;
- var preprocessType = ZodEffects.createWithPreprocess;
- var pipelineType = ZodPipeline.create;
- // src/serializer/gelSchema.ts
- var enumSchema = objectType({
- name: stringType(),
- schema: stringType(),
- values: stringType().array()
- }).strict();
- var enumSchemaV1 = objectType({
- name: stringType(),
- values: recordType(stringType(), stringType())
- }).strict();
- var indexColumn = objectType({
- expression: stringType(),
- isExpression: booleanType(),
- asc: booleanType(),
- nulls: stringType().optional(),
- opclass: stringType().optional()
- });
- var index = objectType({
- name: stringType(),
- columns: indexColumn.array(),
- isUnique: booleanType(),
- with: recordType(stringType(), anyType()).optional(),
- method: stringType().default("btree"),
- where: stringType().optional(),
- concurrently: booleanType().default(false)
- }).strict();
- var fk = objectType({
- name: stringType(),
- tableFrom: stringType(),
- columnsFrom: stringType().array(),
- tableTo: stringType(),
- schemaTo: stringType().optional(),
- columnsTo: stringType().array(),
- onUpdate: stringType().optional(),
- onDelete: stringType().optional()
- }).strict();
- var sequenceSchema = objectType({
- name: stringType(),
- increment: stringType().optional(),
- minValue: stringType().optional(),
- maxValue: stringType().optional(),
- startWith: stringType().optional(),
- cache: stringType().optional(),
- cycle: booleanType().optional(),
- schema: stringType()
- }).strict();
- var roleSchema = objectType({
- name: stringType(),
- createDb: booleanType().optional(),
- createRole: booleanType().optional(),
- inherit: booleanType().optional()
- }).strict();
- var sequenceSquashed = objectType({
- name: stringType(),
- schema: stringType(),
- values: stringType()
- }).strict();
- var column = objectType({
- name: stringType(),
- type: stringType(),
- typeSchema: stringType().optional(),
- primaryKey: booleanType(),
- notNull: booleanType(),
- default: anyType().optional(),
- isUnique: anyType().optional(),
- uniqueName: stringType().optional(),
- nullsNotDistinct: booleanType().optional(),
- generated: objectType({
- type: literalType("stored"),
- as: stringType()
- }).optional(),
- identity: sequenceSchema.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
- }).strict();
- var checkConstraint = objectType({
- name: stringType(),
- value: stringType()
- }).strict();
- var columnSquashed = objectType({
- name: stringType(),
- type: stringType(),
- typeSchema: stringType().optional(),
- primaryKey: booleanType(),
- notNull: booleanType(),
- default: anyType().optional(),
- isUnique: anyType().optional(),
- uniqueName: stringType().optional(),
- nullsNotDistinct: booleanType().optional(),
- generated: objectType({
- type: literalType("stored"),
- as: stringType()
- }).optional(),
- identity: stringType().optional()
- }).strict();
- var compositePK = objectType({
- name: stringType(),
- columns: stringType().array()
- }).strict();
- var uniqueConstraint = objectType({
- name: stringType(),
- columns: stringType().array(),
- nullsNotDistinct: booleanType()
- }).strict();
- var policy = objectType({
- name: stringType(),
- as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
- for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
- to: stringType().array().optional(),
- using: stringType().optional(),
- withCheck: stringType().optional(),
- on: stringType().optional(),
- schema: stringType().optional()
- }).strict();
- var policySquashed = objectType({
- name: stringType(),
- values: stringType()
- }).strict();
- var viewWithOption = objectType({
- checkOption: enumType(["local", "cascaded"]).optional(),
- securityBarrier: booleanType().optional(),
- securityInvoker: booleanType().optional()
- }).strict();
- var matViewWithOption = objectType({
- fillfactor: numberType().optional(),
- toastTupleTarget: numberType().optional(),
- parallelWorkers: numberType().optional(),
- autovacuumEnabled: booleanType().optional(),
- vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
- vacuumTruncate: booleanType().optional(),
- autovacuumVacuumThreshold: numberType().optional(),
- autovacuumVacuumScaleFactor: numberType().optional(),
- autovacuumVacuumCostDelay: numberType().optional(),
- autovacuumVacuumCostLimit: numberType().optional(),
- autovacuumFreezeMinAge: numberType().optional(),
- autovacuumFreezeMaxAge: numberType().optional(),
- autovacuumFreezeTableAge: numberType().optional(),
- autovacuumMultixactFreezeMinAge: numberType().optional(),
- autovacuumMultixactFreezeMaxAge: numberType().optional(),
- autovacuumMultixactFreezeTableAge: numberType().optional(),
- logAutovacuumMinDuration: numberType().optional(),
- userCatalogTable: booleanType().optional()
- }).strict();
- var mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
- var view = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), column),
- definition: stringType().optional(),
- materialized: booleanType(),
- with: mergedViewWithOption.optional(),
- isExisting: booleanType(),
- withNoData: booleanType().optional(),
- using: stringType().optional(),
- tablespace: stringType().optional()
- }).strict();
- var table = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), column),
- indexes: recordType(stringType(), index),
- foreignKeys: recordType(stringType(), fk),
- compositePrimaryKeys: recordType(stringType(), compositePK),
- uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}),
- policies: recordType(stringType(), policy).default({}),
- checkConstraints: recordType(stringType(), checkConstraint).default({}),
- isRLSEnabled: booleanType().default(false)
- }).strict();
- var schemaHash = objectType({
- id: stringType(),
- prevId: stringType()
- });
- var kitInternals = objectType({
- tables: recordType(
- stringType(),
- objectType({
- columns: recordType(
- stringType(),
- objectType({
- isArray: booleanType().optional(),
- dimensions: numberType().optional(),
- rawType: stringType().optional(),
- isDefaultAnExpression: booleanType().optional()
- }).optional()
- )
- }).optional()
- )
- }).optional();
- var gelSchemaExternal = objectType({
- version: literalType("1"),
- dialect: literalType("gel"),
- tables: arrayType(table),
- enums: arrayType(enumSchemaV1),
- schemas: arrayType(objectType({ name: stringType() })),
- _meta: objectType({
- schemas: recordType(stringType(), stringType()),
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- })
- }).strict();
- var gelSchemaInternal = objectType({
- version: literalType("1"),
- dialect: literalType("gel"),
- tables: recordType(stringType(), table),
- enums: recordType(stringType(), enumSchema),
- schemas: recordType(stringType(), stringType()),
- views: recordType(stringType(), view).default({}),
- sequences: recordType(stringType(), sequenceSchema).default({}),
- roles: recordType(stringType(), roleSchema).default({}),
- policies: recordType(stringType(), policy).default({}),
- _meta: objectType({
- schemas: recordType(stringType(), stringType()),
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- }),
- internal: kitInternals
- }).strict();
- var tableSquashed = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), columnSquashed),
- indexes: recordType(stringType(), stringType()),
- foreignKeys: recordType(stringType(), stringType()),
- compositePrimaryKeys: recordType(stringType(), stringType()),
- uniqueConstraints: recordType(stringType(), stringType()),
- policies: recordType(stringType(), stringType()),
- checkConstraints: recordType(stringType(), stringType()),
- isRLSEnabled: booleanType().default(false)
- }).strict();
- var gelSchemaSquashed = objectType({
- version: literalType("1"),
- dialect: literalType("gel"),
- tables: recordType(stringType(), tableSquashed),
- enums: recordType(stringType(), enumSchema),
- schemas: recordType(stringType(), stringType()),
- views: recordType(stringType(), view),
- sequences: recordType(stringType(), sequenceSquashed),
- roles: recordType(stringType(), roleSchema).default({}),
- policies: recordType(stringType(), policySquashed).default({})
- }).strict();
- var gelSchema = gelSchemaInternal.merge(schemaHash);
- var backwardCompatibleGelSchema = gelSchema;
- var dryGel = gelSchema.parse({
- version: "1",
- dialect: "gel",
- id: originUUID,
- prevId: "",
- tables: {},
- enums: {},
- schemas: {},
- policies: {},
- roles: {},
- sequences: {},
- _meta: {
- schemas: {},
- tables: {},
- columns: {}
- }
- });
- // src/serializer/mysqlSchema.ts
- var index2 = objectType({
- name: stringType(),
- columns: stringType().array(),
- isUnique: booleanType(),
- using: enumType(["btree", "hash"]).optional(),
- algorithm: enumType(["default", "inplace", "copy"]).optional(),
- lock: enumType(["default", "none", "shared", "exclusive"]).optional()
- }).strict();
- var fk2 = objectType({
- name: stringType(),
- tableFrom: stringType(),
- columnsFrom: stringType().array(),
- tableTo: stringType(),
- columnsTo: stringType().array(),
- onUpdate: stringType().optional(),
- onDelete: stringType().optional()
- }).strict();
- var column2 = objectType({
- name: stringType(),
- type: stringType(),
- primaryKey: booleanType(),
- notNull: booleanType(),
- autoincrement: booleanType().optional(),
- default: anyType().optional(),
- onUpdate: anyType().optional(),
- generated: objectType({
- type: enumType(["stored", "virtual"]),
- as: stringType()
- }).optional()
- }).strict();
- var tableV3 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column2),
- indexes: recordType(stringType(), index2),
- foreignKeys: recordType(stringType(), fk2)
- }).strict();
- var compositePK2 = objectType({
- name: stringType(),
- columns: stringType().array()
- }).strict();
- var uniqueConstraint2 = objectType({
- name: stringType(),
- columns: stringType().array()
- }).strict();
- var checkConstraint2 = objectType({
- name: stringType(),
- value: stringType()
- }).strict();
- var tableV4 = objectType({
- name: stringType(),
- schema: stringType().optional(),
- columns: recordType(stringType(), column2),
- indexes: recordType(stringType(), index2),
- foreignKeys: recordType(stringType(), fk2)
- }).strict();
- var table2 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column2),
- indexes: recordType(stringType(), index2),
- foreignKeys: recordType(stringType(), fk2),
- compositePrimaryKeys: recordType(stringType(), compositePK2),
- uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
- checkConstraint: recordType(stringType(), checkConstraint2).default({})
- }).strict();
- var viewMeta = objectType({
- algorithm: enumType(["undefined", "merge", "temptable"]),
- sqlSecurity: enumType(["definer", "invoker"]),
- withCheckOption: enumType(["local", "cascaded"]).optional()
- }).strict();
- var view2 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column2),
- definition: stringType().optional(),
- isExisting: booleanType()
- }).strict().merge(viewMeta);
- var kitInternals2 = objectType({
- tables: recordType(
- stringType(),
- objectType({
- columns: recordType(
- stringType(),
- objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
- )
- }).optional()
- ).optional(),
- indexes: recordType(
- stringType(),
- objectType({
- columns: recordType(
- stringType(),
- objectType({ isExpression: booleanType().optional() }).optional()
- )
- }).optional()
- ).optional()
- }).optional();
- var dialect = literalType("mysql");
- var schemaHash2 = objectType({
- id: stringType(),
- prevId: stringType()
- });
- var schemaInternalV3 = objectType({
- version: literalType("3"),
- dialect,
- tables: recordType(stringType(), tableV3)
- }).strict();
- var schemaInternalV4 = objectType({
- version: literalType("4"),
- dialect,
- tables: recordType(stringType(), tableV4),
- schemas: recordType(stringType(), stringType())
- }).strict();
- var schemaInternalV5 = objectType({
- version: literalType("5"),
- dialect,
- tables: recordType(stringType(), table2),
- schemas: recordType(stringType(), stringType()),
- _meta: objectType({
- schemas: recordType(stringType(), stringType()),
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- }),
- internal: kitInternals2
- }).strict();
- var schemaInternal = objectType({
- version: literalType("5"),
- dialect,
- tables: recordType(stringType(), table2),
- views: recordType(stringType(), view2).default({}),
- _meta: objectType({
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- }),
- internal: kitInternals2
- }).strict();
- var schemaV3 = schemaInternalV3.merge(schemaHash2);
- var schemaV4 = schemaInternalV4.merge(schemaHash2);
- var schemaV5 = schemaInternalV5.merge(schemaHash2);
- var schema = schemaInternal.merge(schemaHash2);
- var tableSquashedV4 = objectType({
- name: stringType(),
- schema: stringType().optional(),
- columns: recordType(stringType(), column2),
- indexes: recordType(stringType(), stringType()),
- foreignKeys: recordType(stringType(), stringType())
- }).strict();
- var tableSquashed2 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column2),
- indexes: recordType(stringType(), stringType()),
- foreignKeys: recordType(stringType(), stringType()),
- compositePrimaryKeys: recordType(stringType(), stringType()),
- uniqueConstraints: recordType(stringType(), stringType()).default({}),
- checkConstraints: recordType(stringType(), stringType()).default({})
- }).strict();
- var viewSquashed = view2.omit({
- algorithm: true,
- sqlSecurity: true,
- withCheckOption: true
- }).extend({ meta: stringType() });
- var schemaSquashed = objectType({
- version: literalType("5"),
- dialect,
- tables: recordType(stringType(), tableSquashed2),
- views: recordType(stringType(), viewSquashed)
- }).strict();
- var schemaSquashedV4 = objectType({
- version: literalType("4"),
- dialect,
- tables: recordType(stringType(), tableSquashedV4),
- schemas: recordType(stringType(), stringType())
- }).strict();
- var mysqlSchema = schema;
- var mysqlSchemaV5 = schemaV5;
- var backwardCompatibleMysqlSchema = unionType([mysqlSchemaV5, schema]);
- var dryMySql = mysqlSchema.parse({
- version: "5",
- dialect: "mysql",
- id: originUUID,
- prevId: "",
- tables: {},
- schemas: {},
- views: {},
- _meta: {
- schemas: {},
- tables: {},
- columns: {}
- }
- });
- // src/serializer/pgSchema.ts
- var indexV2 = objectType({
- name: stringType(),
- columns: recordType(
- stringType(),
- objectType({
- name: stringType()
- })
- ),
- isUnique: booleanType()
- }).strict();
- var columnV2 = objectType({
- name: stringType(),
- type: stringType(),
- primaryKey: booleanType(),
- notNull: booleanType(),
- default: anyType().optional(),
- references: stringType().optional()
- }).strict();
- var tableV2 = objectType({
- name: stringType(),
- columns: recordType(stringType(), columnV2),
- indexes: recordType(stringType(), indexV2)
- }).strict();
- var enumSchemaV12 = objectType({
- name: stringType(),
- values: recordType(stringType(), stringType())
- }).strict();
- var enumSchema2 = objectType({
- name: stringType(),
- schema: stringType(),
- values: stringType().array()
- }).strict();
- var pgSchemaV2 = objectType({
- version: literalType("2"),
- tables: recordType(stringType(), tableV2),
- enums: recordType(stringType(), enumSchemaV12)
- }).strict();
- var references = objectType({
- foreignKeyName: stringType(),
- table: stringType(),
- column: stringType(),
- onDelete: stringType().optional(),
- onUpdate: stringType().optional()
- }).strict();
- var columnV1 = objectType({
- name: stringType(),
- type: stringType(),
- primaryKey: booleanType(),
- notNull: booleanType(),
- default: anyType().optional(),
- references: references.optional()
- }).strict();
- var tableV1 = objectType({
- name: stringType(),
- columns: recordType(stringType(), columnV1),
- indexes: recordType(stringType(), indexV2)
- }).strict();
- var pgSchemaV1 = objectType({
- version: literalType("1"),
- tables: recordType(stringType(), tableV1),
- enums: recordType(stringType(), enumSchemaV12)
- }).strict();
- var indexColumn2 = objectType({
- expression: stringType(),
- isExpression: booleanType(),
- asc: booleanType(),
- nulls: stringType().optional(),
- opclass: stringType().optional()
- });
- var index3 = objectType({
- name: stringType(),
- columns: indexColumn2.array(),
- isUnique: booleanType(),
- with: recordType(stringType(), anyType()).optional(),
- method: stringType().default("btree"),
- where: stringType().optional(),
- concurrently: booleanType().default(false)
- }).strict();
- var indexV4 = objectType({
- name: stringType(),
- columns: stringType().array(),
- isUnique: booleanType(),
- with: recordType(stringType(), stringType()).optional(),
- method: stringType().default("btree"),
- where: stringType().optional(),
- concurrently: booleanType().default(false)
- }).strict();
- var indexV5 = objectType({
- name: stringType(),
- columns: stringType().array(),
- isUnique: booleanType(),
- with: recordType(stringType(), stringType()).optional(),
- method: stringType().default("btree"),
- where: stringType().optional(),
- concurrently: booleanType().default(false)
- }).strict();
- var indexV6 = objectType({
- name: stringType(),
- columns: stringType().array(),
- isUnique: booleanType(),
- with: recordType(stringType(), stringType()).optional(),
- method: stringType().default("btree"),
- where: stringType().optional(),
- concurrently: booleanType().default(false)
- }).strict();
- var fk3 = objectType({
- name: stringType(),
- tableFrom: stringType(),
- columnsFrom: stringType().array(),
- tableTo: stringType(),
- schemaTo: stringType().optional(),
- columnsTo: stringType().array(),
- onUpdate: stringType().optional(),
- onDelete: stringType().optional()
- }).strict();
- var sequenceSchema2 = objectType({
- name: stringType(),
- increment: stringType().optional(),
- minValue: stringType().optional(),
- maxValue: stringType().optional(),
- startWith: stringType().optional(),
- cache: stringType().optional(),
- cycle: booleanType().optional(),
- schema: stringType()
- }).strict();
- var roleSchema2 = objectType({
- name: stringType(),
- createDb: booleanType().optional(),
- createRole: booleanType().optional(),
- inherit: booleanType().optional()
- }).strict();
- var sequenceSquashed2 = objectType({
- name: stringType(),
- schema: stringType(),
- values: stringType()
- }).strict();
- var columnV7 = objectType({
- name: stringType(),
- type: stringType(),
- typeSchema: stringType().optional(),
- primaryKey: booleanType(),
- notNull: booleanType(),
- default: anyType().optional(),
- isUnique: anyType().optional(),
- uniqueName: stringType().optional(),
- nullsNotDistinct: booleanType().optional()
- }).strict();
- var column3 = objectType({
- name: stringType(),
- type: stringType(),
- typeSchema: stringType().optional(),
- primaryKey: booleanType(),
- notNull: booleanType(),
- default: anyType().optional(),
- isUnique: anyType().optional(),
- uniqueName: stringType().optional(),
- nullsNotDistinct: booleanType().optional(),
- generated: objectType({
- type: literalType("stored"),
- as: stringType()
- }).optional(),
- identity: sequenceSchema2.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
- }).strict();
- var checkConstraint3 = objectType({
- name: stringType(),
- value: stringType()
- }).strict();
- var columnSquashed2 = objectType({
- name: stringType(),
- type: stringType(),
- typeSchema: stringType().optional(),
- primaryKey: booleanType(),
- notNull: booleanType(),
- default: anyType().optional(),
- isUnique: anyType().optional(),
- uniqueName: stringType().optional(),
- nullsNotDistinct: booleanType().optional(),
- generated: objectType({
- type: literalType("stored"),
- as: stringType()
- }).optional(),
- identity: stringType().optional()
- }).strict();
- var tableV32 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column3),
- indexes: recordType(stringType(), index3),
- foreignKeys: recordType(stringType(), fk3)
- }).strict();
- var compositePK3 = objectType({
- name: stringType(),
- columns: stringType().array()
- }).strict();
- var uniqueConstraint3 = objectType({
- name: stringType(),
- columns: stringType().array(),
- nullsNotDistinct: booleanType()
- }).strict();
- var policy2 = objectType({
- name: stringType(),
- as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
- for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
- to: stringType().array().optional(),
- using: stringType().optional(),
- withCheck: stringType().optional(),
- on: stringType().optional(),
- schema: stringType().optional()
- }).strict();
- var policySquashed2 = objectType({
- name: stringType(),
- values: stringType()
- }).strict();
- var viewWithOption2 = objectType({
- checkOption: enumType(["local", "cascaded"]).optional(),
- securityBarrier: booleanType().optional(),
- securityInvoker: booleanType().optional()
- }).strict();
- var matViewWithOption2 = objectType({
- fillfactor: numberType().optional(),
- toastTupleTarget: numberType().optional(),
- parallelWorkers: numberType().optional(),
- autovacuumEnabled: booleanType().optional(),
- vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
- vacuumTruncate: booleanType().optional(),
- autovacuumVacuumThreshold: numberType().optional(),
- autovacuumVacuumScaleFactor: numberType().optional(),
- autovacuumVacuumCostDelay: numberType().optional(),
- autovacuumVacuumCostLimit: numberType().optional(),
- autovacuumFreezeMinAge: numberType().optional(),
- autovacuumFreezeMaxAge: numberType().optional(),
- autovacuumFreezeTableAge: numberType().optional(),
- autovacuumMultixactFreezeMinAge: numberType().optional(),
- autovacuumMultixactFreezeMaxAge: numberType().optional(),
- autovacuumMultixactFreezeTableAge: numberType().optional(),
- logAutovacuumMinDuration: numberType().optional(),
- userCatalogTable: booleanType().optional()
- }).strict();
- var mergedViewWithOption2 = viewWithOption2.merge(matViewWithOption2).strict();
- var view3 = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), column3),
- definition: stringType().optional(),
- materialized: booleanType(),
- with: mergedViewWithOption2.optional(),
- isExisting: booleanType(),
- withNoData: booleanType().optional(),
- using: stringType().optional(),
- tablespace: stringType().optional()
- }).strict();
- var tableV42 = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), column3),
- indexes: recordType(stringType(), indexV4),
- foreignKeys: recordType(stringType(), fk3)
- }).strict();
- var tableV5 = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), column3),
- indexes: recordType(stringType(), indexV5),
- foreignKeys: recordType(stringType(), fk3),
- compositePrimaryKeys: recordType(stringType(), compositePK3),
- uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
- }).strict();
- var tableV6 = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), column3),
- indexes: recordType(stringType(), indexV6),
- foreignKeys: recordType(stringType(), fk3),
- compositePrimaryKeys: recordType(stringType(), compositePK3),
- uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
- }).strict();
- var tableV7 = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), columnV7),
- indexes: recordType(stringType(), index3),
- foreignKeys: recordType(stringType(), fk3),
- compositePrimaryKeys: recordType(stringType(), compositePK3),
- uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
- }).strict();
- var table3 = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), column3),
- indexes: recordType(stringType(), index3),
- foreignKeys: recordType(stringType(), fk3),
- compositePrimaryKeys: recordType(stringType(), compositePK3),
- uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}),
- policies: recordType(stringType(), policy2).default({}),
- checkConstraints: recordType(stringType(), checkConstraint3).default({}),
- isRLSEnabled: booleanType().default(false)
- }).strict();
- var schemaHash3 = objectType({
- id: stringType(),
- prevId: stringType()
- });
- var kitInternals3 = objectType({
- tables: recordType(
- stringType(),
- objectType({
- columns: recordType(
- stringType(),
- objectType({
- isArray: booleanType().optional(),
- dimensions: numberType().optional(),
- rawType: stringType().optional(),
- isDefaultAnExpression: booleanType().optional()
- }).optional()
- )
- }).optional()
- )
- }).optional();
- var pgSchemaInternalV3 = objectType({
- version: literalType("3"),
- dialect: literalType("pg"),
- tables: recordType(stringType(), tableV32),
- enums: recordType(stringType(), enumSchemaV12)
- }).strict();
- var pgSchemaInternalV4 = objectType({
- version: literalType("4"),
- dialect: literalType("pg"),
- tables: recordType(stringType(), tableV42),
- enums: recordType(stringType(), enumSchemaV12),
- schemas: recordType(stringType(), stringType())
- }).strict();
- var pgSchemaInternalV5 = objectType({
- version: literalType("5"),
- dialect: literalType("pg"),
- tables: recordType(stringType(), tableV5),
- enums: recordType(stringType(), enumSchemaV12),
- schemas: recordType(stringType(), stringType()),
- _meta: objectType({
- schemas: recordType(stringType(), stringType()),
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- }),
- internal: kitInternals3
- }).strict();
- var pgSchemaInternalV6 = objectType({
- version: literalType("6"),
- dialect: literalType("postgresql"),
- tables: recordType(stringType(), tableV6),
- enums: recordType(stringType(), enumSchema2),
- schemas: recordType(stringType(), stringType()),
- _meta: objectType({
- schemas: recordType(stringType(), stringType()),
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- }),
- internal: kitInternals3
- }).strict();
- var pgSchemaExternal = objectType({
- version: literalType("5"),
- dialect: literalType("pg"),
- tables: arrayType(table3),
- enums: arrayType(enumSchemaV12),
- schemas: arrayType(objectType({ name: stringType() })),
- _meta: objectType({
- schemas: recordType(stringType(), stringType()),
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- })
- }).strict();
- var pgSchemaInternalV7 = objectType({
- version: literalType("7"),
- dialect: literalType("postgresql"),
- tables: recordType(stringType(), tableV7),
- enums: recordType(stringType(), enumSchema2),
- schemas: recordType(stringType(), stringType()),
- sequences: recordType(stringType(), sequenceSchema2),
- _meta: objectType({
- schemas: recordType(stringType(), stringType()),
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- }),
- internal: kitInternals3
- }).strict();
- var pgSchemaInternal = objectType({
- version: literalType("7"),
- dialect: literalType("postgresql"),
- tables: recordType(stringType(), table3),
- enums: recordType(stringType(), enumSchema2),
- schemas: recordType(stringType(), stringType()),
- views: recordType(stringType(), view3).default({}),
- sequences: recordType(stringType(), sequenceSchema2).default({}),
- roles: recordType(stringType(), roleSchema2).default({}),
- policies: recordType(stringType(), policy2).default({}),
- _meta: objectType({
- schemas: recordType(stringType(), stringType()),
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- }),
- internal: kitInternals3
- }).strict();
- var tableSquashed3 = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), columnSquashed2),
- indexes: recordType(stringType(), stringType()),
- foreignKeys: recordType(stringType(), stringType()),
- compositePrimaryKeys: recordType(stringType(), stringType()),
- uniqueConstraints: recordType(stringType(), stringType()),
- policies: recordType(stringType(), stringType()),
- checkConstraints: recordType(stringType(), stringType()),
- isRLSEnabled: booleanType().default(false)
- }).strict();
- var tableSquashedV42 = objectType({
- name: stringType(),
- schema: stringType(),
- columns: recordType(stringType(), column3),
- indexes: recordType(stringType(), stringType()),
- foreignKeys: recordType(stringType(), stringType())
- }).strict();
- var pgSchemaSquashedV4 = objectType({
- version: literalType("4"),
- dialect: literalType("pg"),
- tables: recordType(stringType(), tableSquashedV42),
- enums: recordType(stringType(), enumSchemaV12),
- schemas: recordType(stringType(), stringType())
- }).strict();
- var pgSchemaSquashedV6 = objectType({
- version: literalType("6"),
- dialect: literalType("postgresql"),
- tables: recordType(stringType(), tableSquashed3),
- enums: recordType(stringType(), enumSchema2),
- schemas: recordType(stringType(), stringType())
- }).strict();
- var pgSchemaSquashed = objectType({
- version: literalType("7"),
- dialect: literalType("postgresql"),
- tables: recordType(stringType(), tableSquashed3),
- enums: recordType(stringType(), enumSchema2),
- schemas: recordType(stringType(), stringType()),
- views: recordType(stringType(), view3),
- sequences: recordType(stringType(), sequenceSquashed2),
- roles: recordType(stringType(), roleSchema2).default({}),
- policies: recordType(stringType(), policySquashed2).default({})
- }).strict();
- var pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash3);
- var pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash3);
- var pgSchemaV5 = pgSchemaInternalV5.merge(schemaHash3);
- var pgSchemaV6 = pgSchemaInternalV6.merge(schemaHash3);
- var pgSchemaV7 = pgSchemaInternalV7.merge(schemaHash3);
- var pgSchema = pgSchemaInternal.merge(schemaHash3);
- var backwardCompatiblePgSchema = unionType([
- pgSchemaV5,
- pgSchemaV6,
- pgSchema
- ]);
- var dryPg = pgSchema.parse({
- version: snapshotVersion,
- dialect: "postgresql",
- id: originUUID,
- prevId: "",
- tables: {},
- enums: {},
- schemas: {},
- policies: {},
- roles: {},
- sequences: {},
- _meta: {
- schemas: {},
- tables: {},
- columns: {}
- }
- });
- // src/serializer/singlestoreSchema.ts
- var index4 = objectType({
- name: stringType(),
- columns: stringType().array(),
- isUnique: booleanType(),
- using: enumType(["btree", "hash"]).optional(),
- algorithm: enumType(["default", "inplace", "copy"]).optional(),
- lock: enumType(["default", "none", "shared", "exclusive"]).optional()
- }).strict();
- var column4 = objectType({
- name: stringType(),
- type: stringType(),
- primaryKey: booleanType(),
- notNull: booleanType(),
- autoincrement: booleanType().optional(),
- default: anyType().optional(),
- onUpdate: anyType().optional(),
- generated: objectType({
- type: enumType(["stored", "virtual"]),
- as: stringType()
- }).optional()
- }).strict();
- var compositePK4 = objectType({
- name: stringType(),
- columns: stringType().array()
- }).strict();
- var uniqueConstraint4 = objectType({
- name: stringType(),
- columns: stringType().array()
- }).strict();
- var table4 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column4),
- indexes: recordType(stringType(), index4),
- compositePrimaryKeys: recordType(stringType(), compositePK4),
- uniqueConstraints: recordType(stringType(), uniqueConstraint4).default({})
- }).strict();
- var viewMeta2 = objectType({
- algorithm: enumType(["undefined", "merge", "temptable"]),
- sqlSecurity: enumType(["definer", "invoker"]),
- withCheckOption: enumType(["local", "cascaded"]).optional()
- }).strict();
- var kitInternals4 = objectType({
- tables: recordType(
- stringType(),
- objectType({
- columns: recordType(
- stringType(),
- objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
- )
- }).optional()
- ).optional(),
- indexes: recordType(
- stringType(),
- objectType({
- columns: recordType(
- stringType(),
- objectType({ isExpression: booleanType().optional() }).optional()
- )
- }).optional()
- ).optional()
- }).optional();
- var dialect2 = literalType("singlestore");
- var schemaHash4 = objectType({
- id: stringType(),
- prevId: stringType()
- });
- var schemaInternal2 = objectType({
- version: literalType("1"),
- dialect: dialect2,
- tables: recordType(stringType(), table4),
- /* views: record(string(), view).default({}), */
- _meta: objectType({
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- }),
- internal: kitInternals4
- }).strict();
- var schema2 = schemaInternal2.merge(schemaHash4);
- var tableSquashed4 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column4),
- indexes: recordType(stringType(), stringType()),
- compositePrimaryKeys: recordType(stringType(), stringType()),
- uniqueConstraints: recordType(stringType(), stringType()).default({})
- }).strict();
- var schemaSquashed2 = objectType({
- version: literalType("1"),
- dialect: dialect2,
- tables: recordType(stringType(), tableSquashed4)
- /* views: record(string(), viewSquashed), */
- }).strict();
- var singlestoreSchema = schema2;
- var backwardCompatibleSingleStoreSchema = unionType([singlestoreSchema, schema2]);
- var drySingleStore = singlestoreSchema.parse({
- version: "1",
- dialect: "singlestore",
- id: originUUID,
- prevId: "",
- tables: {},
- schemas: {},
- /* views: {}, */
- _meta: {
- schemas: {},
- tables: {},
- columns: {}
- }
- });
- // src/serializer/sqliteSchema.ts
- var index5 = objectType({
- name: stringType(),
- columns: stringType().array(),
- where: stringType().optional(),
- isUnique: booleanType()
- }).strict();
- var fk4 = objectType({
- name: stringType(),
- tableFrom: stringType(),
- columnsFrom: stringType().array(),
- tableTo: stringType(),
- columnsTo: stringType().array(),
- onUpdate: stringType().optional(),
- onDelete: stringType().optional()
- }).strict();
- var compositePK5 = objectType({
- columns: stringType().array(),
- name: stringType().optional()
- }).strict();
- var column5 = objectType({
- name: stringType(),
- type: stringType(),
- primaryKey: booleanType(),
- notNull: booleanType(),
- autoincrement: booleanType().optional(),
- default: anyType().optional(),
- generated: objectType({
- type: enumType(["stored", "virtual"]),
- as: stringType()
- }).optional()
- }).strict();
- var tableV33 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column5),
- indexes: recordType(stringType(), index5),
- foreignKeys: recordType(stringType(), fk4)
- }).strict();
- var uniqueConstraint5 = objectType({
- name: stringType(),
- columns: stringType().array()
- }).strict();
- var checkConstraint4 = objectType({
- name: stringType(),
- value: stringType()
- }).strict();
- var table5 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column5),
- indexes: recordType(stringType(), index5),
- foreignKeys: recordType(stringType(), fk4),
- compositePrimaryKeys: recordType(stringType(), compositePK5),
- uniqueConstraints: recordType(stringType(), uniqueConstraint5).default({}),
- checkConstraints: recordType(stringType(), checkConstraint4).default({})
- }).strict();
- var view4 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column5),
- definition: stringType().optional(),
- isExisting: booleanType()
- }).strict();
- var dialect3 = enumType(["sqlite"]);
- var schemaHash5 = objectType({
- id: stringType(),
- prevId: stringType()
- }).strict();
- var schemaInternalV32 = objectType({
- version: literalType("3"),
- dialect: dialect3,
- tables: recordType(stringType(), tableV33),
- enums: objectType({})
- }).strict();
- var schemaInternalV42 = objectType({
- version: literalType("4"),
- dialect: dialect3,
- tables: recordType(stringType(), table5),
- views: recordType(stringType(), view4).default({}),
- enums: objectType({})
- }).strict();
- var schemaInternalV52 = objectType({
- version: literalType("5"),
- dialect: dialect3,
- tables: recordType(stringType(), table5),
- enums: objectType({}),
- _meta: objectType({
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- })
- }).strict();
- var kitInternals5 = objectType({
- indexes: recordType(
- stringType(),
- objectType({
- columns: recordType(
- stringType(),
- objectType({ isExpression: booleanType().optional() }).optional()
- )
- }).optional()
- ).optional()
- }).optional();
- var latestVersion = literalType("6");
- var schemaInternal3 = objectType({
- version: latestVersion,
- dialect: dialect3,
- tables: recordType(stringType(), table5),
- views: recordType(stringType(), view4).default({}),
- enums: objectType({}),
- _meta: objectType({
- tables: recordType(stringType(), stringType()),
- columns: recordType(stringType(), stringType())
- }),
- internal: kitInternals5
- }).strict();
- var schemaV32 = schemaInternalV32.merge(schemaHash5).strict();
- var schemaV42 = schemaInternalV42.merge(schemaHash5).strict();
- var schemaV52 = schemaInternalV52.merge(schemaHash5).strict();
- var schema3 = schemaInternal3.merge(schemaHash5).strict();
- var tableSquashed5 = objectType({
- name: stringType(),
- columns: recordType(stringType(), column5),
- indexes: recordType(stringType(), stringType()),
- foreignKeys: recordType(stringType(), stringType()),
- compositePrimaryKeys: recordType(stringType(), stringType()),
- uniqueConstraints: recordType(stringType(), stringType()).default({}),
- checkConstraints: recordType(stringType(), stringType()).default({})
- }).strict();
- var schemaSquashed3 = objectType({
- version: latestVersion,
- dialect: dialect3,
- tables: recordType(stringType(), tableSquashed5),
- views: recordType(stringType(), view4),
- enums: anyType()
- }).strict();
- var drySQLite = schema3.parse({
- version: "6",
- dialect: "sqlite",
- id: originUUID,
- prevId: "",
- tables: {},
- views: {},
- enums: {},
- _meta: {
- tables: {},
- columns: {}
- }
- });
- var sqliteSchemaV5 = schemaV52;
- var backwardCompatibleSqliteSchema = unionType([sqliteSchemaV5, schema3]);
- // src/utils.ts
- var copy = (it) => {
- return JSON.parse(JSON.stringify(it));
- };
- var objectValues = (obj) => {
- return Object.values(obj);
- };
- var assertV1OutFolder = (out) => {
- if (!(0, import_fs.existsSync)(out)) return;
- const oldMigrationFolders = (0, import_fs.readdirSync)(out).filter(
- (it) => it.length === 14 && /^\d+$/.test(it)
- );
- if (oldMigrationFolders.length > 0) {
- console.log(
- `Your migrations folder format is outdated, please run ${source_default.green.bold(
- `drizzle-kit up`
- )}`
- );
- process.exit(1);
- }
- };
- var dryJournal = (dialect4) => {
- return {
- version: snapshotVersion,
- dialect: dialect4,
- entries: []
- };
- };
- var prepareOutFolder = (out, dialect4) => {
- const meta = (0, import_path.join)(out, "meta");
- const journalPath = (0, import_path.join)(meta, "_journal.json");
- if (!(0, import_fs.existsSync)((0, import_path.join)(out, "meta"))) {
- (0, import_fs.mkdirSync)(meta, { recursive: true });
- (0, import_fs.writeFileSync)(journalPath, JSON.stringify(dryJournal(dialect4)));
- }
- const journal = JSON.parse((0, import_fs.readFileSync)(journalPath).toString());
- const snapshots = (0, import_fs.readdirSync)(meta).filter((it) => !it.startsWith("_")).map((it) => (0, import_path.join)(meta, it));
- snapshots.sort();
- return { meta, snapshots, journal };
- };
- var validatorForDialect = (dialect4) => {
- switch (dialect4) {
- case "postgresql":
- return { validator: backwardCompatiblePgSchema, version: 7 };
- case "sqlite":
- return { validator: backwardCompatibleSqliteSchema, version: 6 };
- case "turso":
- return { validator: backwardCompatibleSqliteSchema, version: 6 };
- case "mysql":
- return { validator: backwardCompatibleMysqlSchema, version: 5 };
- case "singlestore":
- return { validator: backwardCompatibleSingleStoreSchema, version: 1 };
- case "gel":
- return { validator: backwardCompatibleGelSchema, version: 1 };
- }
- };
- var validateWithReport = (snapshots, dialect4) => {
- const { validator, version } = validatorForDialect(dialect4);
- const result = snapshots.reduce(
- (accum, it) => {
- const raw = JSON.parse((0, import_fs.readFileSync)(`./${it}`).toString());
- accum.rawMap[it] = raw;
- if (raw["version"] && Number(raw["version"]) > version) {
- console.log(
- info(
- `${it} snapshot is of unsupported version, please update drizzle-kit`
- )
- );
- process.exit(0);
- }
- const result2 = validator.safeParse(raw);
- if (!result2.success) {
- accum.malformed.push(it);
- return accum;
- }
- const snapshot = result2.data;
- if (snapshot.version !== String(version)) {
- accum.nonLatest.push(it);
- return accum;
- }
- const idEntry = accum.idsMap[snapshot["prevId"]] ?? {
- parent: it,
- snapshots: []
- };
- idEntry.snapshots.push(it);
- accum.idsMap[snapshot["prevId"]] = idEntry;
- return accum;
- },
- {
- malformed: [],
- nonLatest: [],
- idToNameMap: {},
- idsMap: {},
- rawMap: {}
- }
- );
- return result;
- };
- var prepareMigrationFolder = (outFolder = "drizzle", dialect4) => {
- const { snapshots, journal } = prepareOutFolder(outFolder, dialect4);
- const report = validateWithReport(snapshots, dialect4);
- if (report.nonLatest.length > 0) {
- console.log(
- report.nonLatest.map((it) => {
- return `${it}/snapshot.json is not of the latest version`;
- }).concat(`Run ${source_default.green.bold(`drizzle-kit up`)}`).join("\n")
- );
- process.exit(0);
- }
- if (report.malformed.length) {
- const message2 = report.malformed.map((it) => {
- return `${it} data is malformed`;
- }).join("\n");
- console.log(message2);
- }
- const collisionEntries = Object.entries(report.idsMap).filter(
- (it) => it[1].snapshots.length > 1
- );
- const message = collisionEntries.map((it) => {
- const data = it[1];
- return `[${data.snapshots.join(
- ", "
- )}] are pointing to a parent snapshot: ${data.parent}/snapshot.json which is a collision.`;
- }).join("\n").trim();
- if (message) {
- console.log(source_default.red.bold("Error:"), message);
- }
- const abort = report.malformed.length || collisionEntries.length > 0;
- if (abort) {
- process.exit(0);
- }
- return { snapshots, journal };
- };
- var prepareMigrationMeta = (schemas, tables, columns) => {
- const _meta = {
- schemas: {},
- tables: {},
- columns: {}
- };
- schemas.forEach((it) => {
- const from = schemaRenameKey(it.from);
- const to = schemaRenameKey(it.to);
- _meta.schemas[from] = to;
- });
- tables.forEach((it) => {
- const from = tableRenameKey(it.from);
- const to = tableRenameKey(it.to);
- _meta.tables[from] = to;
- });
- columns.forEach((it) => {
- const from = columnRenameKey(it.from.table, it.from.schema, it.from.column);
- const to = columnRenameKey(it.to.table, it.to.schema, it.to.column);
- _meta.columns[from] = to;
- });
- return _meta;
- };
- var schemaRenameKey = (it) => {
- return it;
- };
- var tableRenameKey = (it) => {
- const out = it.schema ? `"${it.schema}"."${it.name}"` : `"${it.name}"`;
- return out;
- };
- var columnRenameKey = (table6, schema4, column6) => {
- const out = schema4 ? `"${schema4}"."${table6}"."${column6}"` : `"${table6}"."${column6}"`;
- return out;
- };
- var kloudMeta = () => {
- return {
- pg: [5],
- mysql: [],
- sqlite: []
- };
- };
- var normaliseSQLiteUrl = (it, type) => {
- if (type === "libsql") {
- if (it.startsWith("file:")) {
- return it;
- }
- try {
- const url = (0, import_url.parse)(it);
- if (url.protocol === null) {
- return `file:${it}`;
- }
- return it;
- } catch (e) {
- return `file:${it}`;
- }
- }
- if (type === "better-sqlite") {
- if (it.startsWith("file:")) {
- return it.substring(5);
- }
- return it;
- }
- assertUnreachable(type);
- };
- var normalisePGliteUrl = (it) => {
- if (it.startsWith("file:")) {
- return it.substring(5);
- }
- return it;
- };
- function isPgArrayType(sqlType) {
- return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
- }
- function findAddedAndRemoved(columnNames1, columnNames2) {
- const set1 = new Set(columnNames1);
- const set2 = new Set(columnNames2);
- const addedColumns = columnNames2.filter((it) => !set1.has(it));
- const removedColumns = columnNames1.filter((it) => !set2.has(it));
- return { addedColumns, removedColumns };
- }
- function escapeSingleQuotes(str) {
- return str.replace(/'/g, "''");
- }
- function unescapeSingleQuotes(str, ignoreFirstAndLastChar) {
- const regex = ignoreFirstAndLastChar ? /(?<!^)'(?!$)/g : /'/g;
- return str.replace(/''/g, "'").replace(regex, "\\'");
- }
- // Annotate the CommonJS export names for ESM import in node:
- 0 && (module.exports = {
- assertV1OutFolder,
- columnRenameKey,
- copy,
- dryJournal,
- escapeSingleQuotes,
- findAddedAndRemoved,
- isPgArrayType,
- kloudMeta,
- normalisePGliteUrl,
- normaliseSQLiteUrl,
- objectValues,
- prepareMigrationFolder,
- prepareMigrationMeta,
- prepareOutFolder,
- schemaRenameKey,
- tableRenameKey,
- unescapeSingleQuotes,
- validateWithReport
- });
|